Deep dive · #03 / 30Decision models & orchestration
calendar_todayNovember 24, 2026schedule7 min readschoolAdvanced
translateAlso in:
Idea 03 · Orchestration

The Guardrail That Deletes a Choice

An edit run tries to finish with a dirty workspace. We ask again without end_agent_run and add one line explaining why. The guard fails closed; the retry fails open.

Cluster: Decision models

A louder prompt is not a guardrail

The last decision in an edit run goes like this: the decision model answers next_action with end_agent_run, even though the thread’s workspace still holds three edited files that were never merged into a release. The usual patch is one more line in the system prompt — never finish while files are dirty. That’s a request. The model can ignore it, and when it does, the run ends with drafts nobody committed.

The alternative is to take that answer away. Not by scolding the model — by deleting the label from the choice map before asking the same question again.

Ask louder04
  • Add another sentence to the system prompt: 'do not finish while files are dirty'
  • Hope the model reads and follows it on this turn
  • A wrong answer is a normal completion — the run simply ends
  • Same choice set, same failure mode, more tokens
Remove the choice04
  • Delete end_agent_run from the decision's criteria map
  • Append one fact: the actual count of uncommitted files
  • The blocked label cannot be selected again in the retry
  • Fail closed on the guard; fail open only on the retry

We build on Cheap router, strong writer: it explains the decision model, the next_action question and the two built-in labels. The argument-routing half lives in Not Every Tool Argument Needs the Same Model. Here we look only at the veto.

The choice set is the control surface

The decision call asks one choice question with id next_action. Its criteria is a Record<string, DecisionCriterion> built by mapping every bound tool name to its description, with two built-ins added: defer_to_agent_llm and end_agent_run. The root end criterion even warns in prose that finishing is “Not allowed while the workspace has uncommitted changes”.

That sentence is a hint, not enforcement. Enforcement lives in the criteria object: if a key is absent, the decision model can’t return it, because the provider validates answers against the supplied choices. Deleting end_agent_run is a mechanical edit to the action space — not a change of model or prompt policy.

The guard is a policy slot, not a prompt string

The decision engine serves both the root agent and its delegated editors, but it has no idea what a workspace is. The caller supplies that policy: an optional guard function and a function that turns a reason into a retry instruction.

// decision-orchestrator.ts
/** Returns a reason why the run may not finish yet, or undefined when it may. */
export type FinishGuardCheck = () => Promise<string | undefined>;

interface FinishGuardAllowed {
  readonly kind: 'allowed';
}
interface FinishGuardBlocked {
  readonly kind: 'blocked';
  readonly reason: string;
}
type FinishGuardDecision = FinishGuardAllowed | FinishGuardBlocked;

/** Built-in choices offered alongside the bound tools. */
export const DEFER_ACTION = 'defer_to_agent_llm';
export const END_RUN_ACTION = 'end_agent_run';
// decision-orchestrator.ts — DecisionStepPolicy
export interface DecisionStepPolicy {
  readonly agentName: DecisionAgentName;
  readonly instructions: string;
  readonly deferAction: DecisionActionChoice;
  readonly endAction: DecisionActionChoice;
  /** A returned reason blocks the end-run action for this step. */
  readonly finishGuard?: FinishGuardCheck;
  readonly finishGuardInstruction: (reason: string) => string;
}

// The shared engine only knows how to execute the policy:
const { agentName, instructions, deferAction, endAction,
        finishGuard, finishGuardInstruction } = policy;

Returning a reason string instead of a boolean matters. The retry isn’t stuck with “you can’t do that” — it can say how many files are still pending, since the guard’s string is inserted into the instruction. The engine stays agnostic: another policy could return “tests are still failing” without touching this file.

One pass through the finish guard

The guard runs at exactly one point in the decision flow: after the first decision has picked the end label, before any action is dispatched. Tool steps and defers never read the workspace.

  1. 01

    The model picks end_agent_run

    The decision call answers next_action from the bound tool names plus the two built-ins. No workspace check has run yet.

  2. 02

    The guard runs once

    evaluateFinishGuard() converts a returned reason — or a thrown error — into a single blocked decision. The counter is called exactly once for this step.

  3. 03

    The choice set is edited

    omitDecisionAction() drops only end_agent_run; the one-line reason is appended to the decision instructions. State, question id and traced decisionId are reused.

  4. 04

    The retry decides the rest

    The retry runs a tool, defers with handler(request), or returns handler(request) even if it selects the end label again. Only a clean end produces Command({ goto: END }).

graph TD
    A["DecisionModel: next_action"] --> B{"choice == end_agent_run?"}
    B -->|"no"| C["defer to agent LLM<br/>or bound tool call"]
    B -->|"yes, no guard"| D["Command({ goto: END })"]
    B -->|"yes, guard present"| E["evaluateFinishGuard()"]
    E --> F{"reason?"}
    F -->|"undefined - clean"| D
    F -->|"string or throw - dirty"| G["omitDecisionAction(criteria, end_agent_run)"]
    G --> H["chooseAction with finishGuardInstruction(reason)"]
    H --> I{"new choice?"}
    I -->|"end_agent_run again"| J["handler(request) - agent LLM"]
    I -->|"defer or tool"| C
    H -->|"retry throws"| J

The re-ask changes two things

The retry makes two changes at once, and they’re easy to conflate. Shrinking the action space is only one of them.

// decision-orchestrator.ts
/** Added to the retry after a premature end-run decision in a root agent. */
const finishGuardInstruction = (reason: string): string =>
  `The agent loop cannot finish: ${reason}. Choose the next step that reviews and commits them.`;

/** A copy without one action, so the decision model cannot repeat a blocked choice. */
function omitDecisionAction(
  criteria: Readonly<Record<string, DecisionCriterion>>,
  action: string,
): Record<string, DecisionCriterion> {
  return Object.fromEntries(Object.entries(criteria).filter(([label]) => label !== action));
}
// decision-orchestrator.ts — inside buildDecisionWrapModelCall
let blockedFinishReason: string | undefined;
if (decision.choice === endAction.label && finishGuard !== undefined) {
  const guard = await evaluateFinishGuard(finishGuard);
  if (guard.kind === 'blocked') {
    blockedFinishReason = guard.reason;
    try {
      decision = await chooseAction(
        omitDecisionAction(criteria, endAction.label),
        finishGuardInstruction(guard.reason),
      );
      decisionDurationMs += decision.durationMs;
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      emitDecisionFinished({
        durationMs: Date.now() - startedAtMs,
        options: decision.options,
        errorMessage: truncateErrorMessage(message),
      });
      logger.warn('finish guard retry failed — falling back to the agent LLM: {error}', {
        error: message,
      });
      return handler(request);
    }
  }
}
// decision-orchestrator.ts — chooseAction()
const chooseAction = (
  actionCriteria: Record<string, DecisionCriterion>,
  extraInstructions?: string,
): Promise<DecisionResult> =>
  decisionRun.invoke(
    {
      model: decisionModel.model,
      state: buildDecisionState(agentName, request.systemMessage, request.messages),
      questions: {
        [DECISION_QUESTION_ID]: {
          type: 'choice',
          instructions: extraInstructions === undefined
            ? instructions
            : `${instructions} ${extraInstructions}`,
        criteria: actionCriteria,
      },
    },
    ...(metadata !== undefined ? { metadata } : {}),
  } satisfies DecisionInput,
  { signal: request.runtime.signal },
);

// DECISION_QUESTION_ID = 'next_action'

The same buildDecisionState output goes out again — agent name, system prompt and unchanged conversation — and both calls share one decisionId on the live timeline. The second call continues the same decision; it isn’t a new turn. Its duration is added to the first, so the trace row accounts for both cheap calls.

Fail closed on the guard, fail open on the retry

Every other uncertainty in this orchestrator degrades to the agent LLM: an unusable choice, an unknown tool, invalid arguments, a failed extraction. The guard is the deliberate exception.

// decision-orchestrator.ts — evaluateFinishGuard()
async function evaluateFinishGuard(guard: FinishGuardCheck): Promise<FinishGuardDecision> {
  try {
    const reason = await guard();
    return reason === undefined ? { kind: 'allowed' } : { kind: 'blocked', reason };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    logger.warn('finish guard could not be read — blocking the finish: {error}', { error: message });
    return { kind: 'blocked', reason: 'the finish guard check was unavailable' };
  }
}
// decision-orchestrator.ts — first decision call
try {
  decision = await chooseAction(criteria);
  decisionDurationMs = decision.durationMs;
} catch (error) {
  const message = error instanceof Error ? error.message : String(error);
  emitDecisionFinished({
    durationMs: Date.now() - startedAtMs,
    options: [],
    errorMessage: truncateErrorMessage(message),
  });
  logger.warn('decision call failed — falling back to the agent LLM: {error}', {
    error: message,
  });
  return handler(request);
}

The specs make this explicit. A counter throwing 'workspace read failed' still produces two decision calls and a tool call, with the handler never invoked; a counter returning 2 produces exactly one counter read and a retry instruction containing the literal 2 uncommitted workspace file change(s).

Only commit-capable root agents get a guard

The root policy builds its guard from an injected counter, which exists only when the agent can commit. Capability is detected by inspecting the tool list at build time.

build-agent.ts computes canCommit from the presence of the COMMIT_RELEASE_CHANGES tool and passes countUncommittedWorkspaceChanges: canCommit ? () => countUncommittedSkillWorkspaceFiles(scope) : undefined. The two agent names outside SKILL_BUILDER_COMMIT_AGENT_NAMES — intake and audit — are built without that tool, so their end_agent_run is honoured immediately. That’s intentional: a read-only agent has nothing to commit, so a dirty workspace isn’t an unfinished edit of its own.

Delegated skill editors are the subtler case. They use the same buildDecisionWrapModelCall engine and even supply a finishGuardInstruction — but no finishGuard. The engine’s condition requires finishGuard !== undefined, so their end-run choice is never vetoed. The editor’s scope is one file; the root agent reviews the diff and commits.

What “uncommitted” actually means

There’s no Git repository behind this check. “Dirty” means comparing two ObjectId maps.

// services/skill-builder/skill-workspace-state.ts
export async function countUncommittedSkillWorkspaceFiles(
  skillBuilderRequestScope: SkillBuilderRequestScope,
): Promise<number> {
  const threadStorage = skillBuilderRequestScope.container.resolve(SkillBuilderThreadStorage);
  const workspace = await threadStorage.findWorkspaceByThread(
    skillBuilderRequestScope.tenantId,
    skillBuilderRequestScope.businessEntityId,
    skillBuilderRequestScope.threadId,
  );
  if (workspace === undefined || workspace.state !== WorkspaceState.ACTIVE) return 0;

  const codeBaseStorage = skillBuilderRequestScope.container.resolve(BusinessCodeBaseStorageService);
  const { changedFiles } = await calculateSkillWorkspaceChanges(
    codeBaseStorage,
    workspace,
    skillBuilderRequestScope.tenantId,
    skillBuilderRequestScope.businessEntityId,
  );
  return changedFiles.length;
}
// skill-workspace-state.ts — readSkillWorkspaceChangeSet()
const codeBaseHead = await businessCodeBaseStorage.getCodeBaseHead(tenantId, businessEntityId);
const nextReleaseId = codeBaseHead?.environments[BusinessCodeBaseEnvironmentName.NEXT]?.currentReleaseId;
if (!nextReleaseId) return undefined;

const nextRelease = await businessCodeBaseStorage.getReleaseById(tenantId, nextReleaseId);
const baseFiles = nextRelease?.files ?? {};
const workspaceFiles = (workspace.files ?? {}) as Record<string, ObjectId>;

// ... classified against the baseline file paths:
changedFiles: [
  ...addedFilePaths.map((path) => ({ path, changeType: BusinessCodeBaseFileChangeAction.ADDED })),
  ...modifiedFilePaths.map((path) => ({ path, changeType: BusinessCodeBaseFileChangeAction.MODIFIED })),
  ...removedFilePaths.map((path) => ({ path, changeType: BusinessCodeBaseFileChangeAction.REMOVED })),
],

The baseline is the current release in NEXT (In Development), not a VCS HEAD. A non-ACTIVE workspace counts as clean. Committing merges the drafts into a new NEXT release and closes the workspace, so the count drops back to zero and the next end decision passes. Publishing NEXT to customer-visible LIVE (Main) is a separate action — the guard protects the draft-to-NEXT handoff, not the deployment.

Three exits from a blocked finish

Once the guard says “blocked”, the step can settle three ways. Only one ends the run.

Exit 101 / 03

Clean finish

The guard returns undefined, or no guard is configured. decision_finished is emitted and the middleware returns new Command({ goto: END }) — no further model call.

Exit 202 / 03

Re-asked into work

end_agent_run is gone from the criteria. The second decision picks a bound tool (arguments resolved as usual) or defer_to_agent_llm, which returns handler(request).

Exit 303 / 03

Blocked, but the model insists

If the retry still returns end_agent_run, blockedFinishReason is set: the middleware warns and returns handler(request). No END is issued.

The model can’t literally choose the removed label in Exit 2 — the provider validates against the supplied criteria — but the code handles it anyway. That redundant branch covers a provider echoing a stale choice, or any future change to the decision client. Command({ goto: END }) is LangGraph’s terminal routing primitive; upstream docs describe a run as ending when no nodes are active and no messages remain in transit.

The sibling guardrail edits the prompt instead

The same agent also carries ToolLoopGuardMiddleware, which tackles a different failure with a different lever: it changes what the model sees and which tools it may repeat, not the terminal action menu.

Finish guard — wrapModelCall04
  • Fires only on the end_agent_run decision
  • Deletes a label from the decision criteria and appends a reason
  • Fails closed if the workspace check throws
  • Falls back to the agent LLM if the retry fails
Tool-loop guard — wrapToolCall04
  • Fires on repeated calls and on the soft turn budget
  • Appends FINALIZE_DIRECTIVE to the system message; returns error ToolMessages
  • Canonical JSON argument comparison blocks identical successful repeats
  • Failed test re-runs stay legal until something modifies the suite

The loop guard’s FINALIZE_DIRECTIVE is a real prompt edit — applied once the AI-turn count reaches softTurnLimit. Repeated successful calls get a synthetic ToolMessage carrying LOOP PREVENTED; failed calls can be retried, because fixing a validation error is productive work.

Both are guardrails as code rather than poetry. The difference is the seam. The finish guard makes a destructive action unselectable; the loop guard makes unproductive behaviour expensive and, when needed, blocks it at the tool boundary. Anthropic’s agent-engineering guidance calls the same instinct poka-yoke — change the interface so the mistake is harder to make — and recommends explicit stopping conditions for autonomous loops.

Trade-offs and rules of thumb

  • It is a decision-time guard, not a hard invariant. It intercepts the decision model’s end_agent_run. The fallback is handler(request) — the original agent LLM — which can still decide to end with drafts pending. Treat the guard as strong friction, not a transaction boundary.
  • A blocked finish costs a second cheap call. Both calls share one decisionId and one live timeline row, and decisionDurationMs sums them. Error strings are truncated at MAX_ERROR_MESSAGE_LENGTH (500 characters) before they reach that row.
  • Silent no-ops are possible by construction. A policy may supply finishGuardInstruction without finishGuard — the skill editors do exactly that. The engine will never invoke the guard, so the end criterion stays prose-only. Audit the policy object, not the prompt, when reviewing a new agent.
  • Read-only agents are deliberately exempt. intake and audit have no commit tool and therefore no counter; a dirty workspace cannot block them.
  • Upstream facts are version-sensitive (checked 24 Nov 2026). OpenAI documents that structured outputs remove the need for strongly worded prompting but still require application-side business-rule validation. That is why a schema-constrained choice is not enough here. LangGraph’s Command/END semantics and recursion-limit defaults change between releases; the code, not the docs, is the contract for this article.

The events produced by these decisions needed a protocol of their own — The Event Stream Isn’t Your API.

Share this article

Common questions

What does it mean to edit an agent's action space instead of re-prompting?
The retry changes the decision model's choice map by deleting end_agent_run, so it cannot be selected again. One extra line of instruction states the concrete reason, such as '2 uncommitted workspace file change(s) remain'. The tool surface, question id and conversation state stay the same.
What happens when the finish guard throws?
evaluateFinishGuard catches the error, logs a warning and returns a blocked decision with the reason 'the finish guard check was unavailable'. A failed workspace read is therefore treated as unfinished work, and the end-run choice is still removed from the retry.
Can the agent still end the run after the guard blocks it?
The decision retry cannot: if the re-asked decision returns end_agent_run again, the middleware ignores it and returns the original agent LLM handler. The guard acts at decision time, not as a hard runtime invariant, so the agent LLM fallback can still end a run.
Which agents have a finish guard?
Only commit-capable root agents have a finish guard. build-agent.ts detects the commitReleaseChanges tool by name and passes a workspace counter; read-only agents such as intake and audit get undefined and can finish immediately. Delegated skill editors share the decision engine but supply no finishGuard, so they have no end-run veto.
What counts as an uncommitted workspace change?
The workspace is compared with the NEXT release's file map to find added, modified and removed file revision ids. A missing or non-ACTIVE workspace counts as clean. Committing merges the workspace into a new NEXT release and closes it, so the count returns to zero; publishing NEXT to LIVE is a separate step.

Related articles

Keep reading

DB
Dmitrii Bolotov
Decision models & orchestration
Engineeringarrow_forward