@sema-agent/core 7.5.0 → 7.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/core/auto-mode.d.ts +9 -0
  3. package/dist/core/auto-mode.js +11 -0
  4. package/dist/core/checkpoint-store.js +5 -1
  5. package/dist/core/protocol-table.d.ts +5 -0
  6. package/dist/core/protocol-table.js +1 -0
  7. package/dist/core/runner/abort-race.d.ts +41 -0
  8. package/dist/core/runner/abort-race.js +38 -0
  9. package/dist/core/runner/checkpoint-scope.d.ts +44 -0
  10. package/dist/core/runner/checkpoint-scope.js +7 -0
  11. package/dist/core/runner/compaction-call-options.d.ts +1 -1
  12. package/dist/core/runner/content-ask-bindings.d.ts +27 -0
  13. package/dist/core/runner/content-ask-bindings.js +1 -0
  14. package/dist/core/runner/contracts.d.ts +1990 -0
  15. package/dist/core/runner/contracts.js +1 -0
  16. package/dist/core/runner/denial-limit-arms.d.ts +24 -1
  17. package/dist/core/runner/denial-limit-arms.js +21 -0
  18. package/dist/core/runner/derived-route-fallback.d.ts +34 -0
  19. package/dist/core/runner/derived-route-fallback.js +16 -0
  20. package/dist/core/runner/inherited-ask-grants.d.ts +46 -0
  21. package/dist/core/runner/inherited-ask-grants.js +29 -0
  22. package/dist/core/runner/park-commit.d.ts +108 -0
  23. package/dist/core/runner/park-commit.js +32 -0
  24. package/dist/core/runner/{prepare-permission-rules.d.ts → permission-rule-lanes.d.ts} +109 -3
  25. package/dist/core/runner/{prepare-permission-rules.js → permission-rule-lanes.js} +47 -1
  26. package/dist/core/runner/prepare-acquire-reconcile.d.ts +1 -1
  27. package/dist/core/runner/prepare-ask-lane.d.ts +110 -0
  28. package/dist/core/runner/prepare-ask-lane.js +133 -0
  29. package/dist/core/runner/prepare-boundary-parks.d.ts +105 -0
  30. package/dist/core/runner/prepare-boundary-parks.js +169 -0
  31. package/dist/core/runner/prepare-caps-and-workflow.d.ts +170 -0
  32. package/dist/core/runner/prepare-caps-and-workflow.js +255 -0
  33. package/dist/core/runner/prepare-config-doors.d.ts +2 -10
  34. package/dist/core/runner/prepare-context-lane.d.ts +119 -0
  35. package/dist/core/runner/prepare-context-lane.js +230 -0
  36. package/dist/core/runner/prepare-defer-classify.d.ts +86 -0
  37. package/dist/core/runner/prepare-defer-classify.js +107 -0
  38. package/dist/core/runner/prepare-delegation-surface.d.ts +104 -0
  39. package/dist/core/runner/prepare-delegation-surface.js +144 -0
  40. package/dist/core/runner/prepare-execution-env.d.ts +54 -0
  41. package/dist/core/runner/prepare-execution-env.js +86 -0
  42. package/dist/core/runner/prepare-file-history.d.ts +95 -0
  43. package/dist/core/runner/prepare-file-history.js +383 -0
  44. package/dist/core/runner/prepare-gate-stations.d.ts +177 -0
  45. package/dist/core/runner/prepare-gate-stations.js +290 -0
  46. package/dist/core/runner/prepare-hands-readface.d.ts +9 -11
  47. package/dist/core/runner/prepare-hands-readface.js +1 -1
  48. package/dist/core/runner/prepare-inherited-gate.d.ts +268 -0
  49. package/dist/core/runner/prepare-inherited-gate.js +266 -0
  50. package/dist/core/runner/prepare-listings.d.ts +77 -0
  51. package/dist/core/runner/prepare-listings.js +76 -0
  52. package/dist/core/runner/prepare-lsp.d.ts +55 -0
  53. package/dist/core/runner/prepare-lsp.js +27 -0
  54. package/dist/core/runner/prepare-memory-engine-session.d.ts +84 -0
  55. package/dist/core/runner/prepare-memory-engine-session.js +233 -0
  56. package/dist/core/runner/prepare-memory.d.ts +1 -1
  57. package/dist/core/runner/prepare-offload-wrappers.d.ts +62 -0
  58. package/dist/core/runner/prepare-offload-wrappers.js +45 -0
  59. package/dist/core/runner/prepare-park-ask.d.ts +164 -0
  60. package/dist/core/runner/prepare-park-ask.js +377 -0
  61. package/dist/core/runner/prepare-policy-chain.d.ts +208 -0
  62. package/dist/core/runner/prepare-policy-chain.js +584 -0
  63. package/dist/core/runner/prepare-project-context.d.ts +119 -0
  64. package/dist/core/runner/prepare-project-context.js +148 -0
  65. package/dist/core/runner/prepare-prompt-assembly.d.ts +95 -0
  66. package/dist/core/runner/prepare-prompt-assembly.js +162 -0
  67. package/dist/core/runner/prepare-prompt-inputs.d.ts +119 -0
  68. package/dist/core/runner/prepare-prompt-inputs.js +141 -0
  69. package/dist/core/runner/prepare-protocol-tools.d.ts +91 -0
  70. package/dist/core/runner/prepare-protocol-tools.js +179 -0
  71. package/dist/core/runner/prepare-question-face.d.ts +101 -0
  72. package/dist/core/runner/prepare-question-face.js +84 -0
  73. package/dist/core/runner/prepare-run-refs.d.ts +89 -0
  74. package/dist/core/runner/prepare-run-refs.js +39 -0
  75. package/dist/core/runner/prepare-safety-scan.d.ts +3 -7
  76. package/dist/core/runner/prepare-safety-scan.js +1 -2
  77. package/dist/core/runner/prepare-suspend-saga.d.ts +170 -0
  78. package/dist/core/runner/prepare-suspend-saga.js +308 -0
  79. package/dist/core/runner/prepare-task.d.ts +14 -1976
  80. package/dist/core/runner/prepare-task.js +182 -5162
  81. package/dist/core/runner/prepare-tool-disclosure-mount.d.ts +111 -0
  82. package/dist/core/runner/prepare-tool-disclosure-mount.js +219 -0
  83. package/dist/core/runner/prepare-turn-wiring.d.ts +154 -0
  84. package/dist/core/runner/prepare-turn-wiring.js +201 -0
  85. package/dist/core/runner/prepare-wiring-manifest.d.ts +192 -0
  86. package/dist/core/runner/prepare-wiring-manifest.js +247 -0
  87. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -56
  88. package/dist/core/runner/prepare-workspace-restore.js +4 -38
  89. package/dist/core/runner/prompt-hash-salt.d.ts +1 -0
  90. package/dist/core/runner/prompt-hash-salt.js +2 -0
  91. package/dist/core/runner/remote-env-retry.d.ts +29 -0
  92. package/dist/core/runner/remote-env-retry.js +16 -0
  93. package/dist/core/runner/rollback-stack.d.ts +32 -0
  94. package/dist/core/runner/rollback-stack.js +30 -0
  95. package/dist/core/runner/runtask.js +1 -1
  96. package/dist/core/runner/workspace-path.d.ts +33 -0
  97. package/dist/core/runner/workspace-path.js +22 -0
  98. package/dist/core/session.d.ts +12 -0
  99. package/dist/core/session.js +3 -0
  100. package/dist/core/tool-policy.d.ts +16 -0
  101. package/dist/core/tool-policy.js +3 -0
  102. package/dist/core/types.d.ts +2 -2
  103. package/dist/core/write-protect.js +3 -2
  104. package/package.json +6 -2
  105. /package/dist/core/runner/{prepare-announce-once.d.ts → announce-once-ledger.d.ts} +0 -0
  106. /package/dist/core/runner/{prepare-announce-once.js → announce-once-ledger.js} +0 -0
@@ -0,0 +1,1990 @@
1
+ /**
2
+ * The prepare CONTRACTS — the types that cross between `prepareTask` and the phase modules it drives.
3
+ *
4
+ * WHY THEY LIVE HERE. Every one of these was declared inside `prepare-task.ts`, the file that PRODUCES
5
+ * them, so any module needing to name one had to import its own driver. Thirteen such edges had
6
+ * accumulated by the time the dependency-direction gate was written: six phases reaching up for a
7
+ * contract type, the vocabulary file reaching up for two more through inline `import()` type
8
+ * positions, a phase reaching sideways for a pure path helper, and the orchestrator and its own
9
+ * consumer naming each other. A contract belongs BELOW both the producer and the consumer; that is
10
+ * all this file is.
11
+ *
12
+ * It declares TYPES ONLY — nothing is emitted, so it sits on the vocabulary floor beside `types.ts`
13
+ * without adding a runtime edge anywhere. The blocks below are verbatim moves, in their original
14
+ * order, JSDoc included, so the move stays auditable as a move.
15
+ */
16
+ import type { RepairBundle } from "../../agents/repair-loop.js";
17
+ import type { SubagentRetainLedger } from "../../agents/retain-ledger.js";
18
+ import type { BrainCallGuardrailRef } from "../../brain/timeout.js";
19
+ import type { ActiveWorktreeSession, AgentHarness, AgentMessage, AgentTool, AnnouncedListingSnapshotInput, ExecutionEnv, ThinkingLevel } from "../../internal/harness.js";
20
+ import type { Model } from "../../internal/llm.js";
21
+ import type { WorkflowSizeGuideline } from "../../orchestration/workflow-size-guideline.js";
22
+ import type { ToolManifestRow } from "../../prompt-assembly/tool-catalog.js";
23
+ import type { CwdRef, ReadFace } from "../../tools/fs/index.js";
24
+ import type { MaterializedA2a } from "../a2a.js";
25
+ import type { CompactionForkContext } from "../auto-compaction.js";
26
+ import type { AutoModeArmingRecipe } from "../auto-mode-arming.js";
27
+ import type { AutoModeDecider, AutoModeDenialTracker } from "../auto-mode.js";
28
+ import type { CacheBreakDetector, ToolFingerprintInput } from "../cache-break-detector.js";
29
+ import type { Checkpoint, CheckpointGate, CheckpointState, CheckpointToken, PlatformLimitReason, ResourceLedger, ResourceLimitReason, SerializedCheckpointState } from "../checkpoint-store.js";
30
+ import type { ClearedProjectionLedger, ContextEditMachine, OccurrenceIndex } from "../context-edit.js";
31
+ import type { HookInvocationIdentity, Hooks, OrgGateVerdict, PermissionDeniedPayload, ToolGateInput } from "../hooks.js";
32
+ import type { MaterializedMcp } from "../mcp.js";
33
+ import type { MemoryEngine } from "../memory-engine/engine.js";
34
+ import type { HarvestReport, MemorySessionHandle } from "../memory-engine/types.js";
35
+ import type { SessionPermissionRules } from "../session-policy-store.js";
36
+ import type { RecoveredOrphan } from "../session-reconcile.js";
37
+ import type { StoredSession } from "../session.js";
38
+ import type { TaskNotificationPayload } from "../task-notification.js";
39
+ import type { OnAsk, PermissionResult, ResolvedAsk, ToolCallRequest, ToolPolicy } from "../tool-policy.js";
40
+ import type { RemoteExecutionEnv, SnapshotId, WorkspaceHandle } from "../remote-env.js";
41
+ import type { ToolDisclosureManifest } from "../trace.js";
42
+ import type { NestedUsageAccum, RunnerDeps, TaskEvent, TaskResult, TaskSpec, ToolActivity, ToolEffect } from "../types.js";
43
+ import type { WiringManifest } from "../wiring-manifest.js";
44
+ import type { ActiveSkillFrame } from "./active-skill-scope.js";
45
+ import type { GitStatusLaneRef } from "./git-status-frame.js";
46
+ import type { SessionReadFileStates } from "./prepare-hands-readface.js";
47
+ import type { BlockedRef, OutputRef, SkillListingEntry } from "./synthetic-tools.js";
48
+ /**
49
+ * The frozen task-start snapshot of the caller's tool-face control arrays: produced by the
50
+ * config-doors phase, read by the hands/read-face phase. Named here rather than reached for as
51
+ * `PrepareConfigDoorsResult["toolFaceSnapshot"]` — an indexed access into a sibling phase's Result
52
+ * is a sideways dependency wearing a type's clothes.
53
+ */
54
+ export interface ToolFaceSnapshot {
55
+ exclude: readonly string[] | undefined;
56
+ defer: readonly string[] | undefined;
57
+ alwaysLoad: readonly string[] | undefined;
58
+ /** design/277 — the model-gate restore selector ({@link TaskSpec.restoreGatedTools}), fourth
59
+ * seat of the same frozen task-start snapshot: the gate decision and the delegation carrier
60
+ * read THIS, never the live spec. */
61
+ restoreGated: readonly string[] | true | undefined;
62
+ }
63
+ /**
64
+ * The once-per-session announcement ledger's OPERATOR SINK as the phases see it: the
65
+ * `RunnerDeps.onError` signature, deduplicated per (code, text) across the session. The ledger itself
66
+ * (load, digests, settle) lives in announce-once-ledger.ts; a phase that announces once invokes only
67
+ * this member, so the member's shape is declared here — below every phase — rather than reached for
68
+ * sideways as the ledger module's type.
69
+ */
70
+ export interface AnnounceOnceSink {
71
+ onError: NonNullable<RunnerDeps["onError"]>;
72
+ }
73
+ /** Static per-tool irreversibility tier, resolved at prepare time by the safety scan. */
74
+ export type IrreversibilityTier = Map<string, "never" | "maybe" | "always">;
75
+ /** Declared reversibility probes by tool name, collected by the safety scan on the same pass. */
76
+ export type ReversibilityProbes = Map<string, NonNullable<TaskSpec["tools"]>[number]["reversibilityProbe"]>;
77
+ /**
78
+ * The prepare-FAILURE cleanup stack. A phase that acquires a resource (an execution env, an MCP
79
+ * client, an A2A client) pushes its release the moment the handle exists, so a throw further down
80
+ * cannot leak it — before this the driver could only see a half-acquired handle by hoisting a `let`
81
+ * to the top of the function and hoping every acquisition site remembered to assign it.
82
+ *
83
+ * IT IS ARMED ONLY ON THE FAILURE PATH. The driver calls {@link RollbackStack.commit} before it
84
+ * builds `Prepared`: past that point the stack is empty and every resource's cleanup belongs to the
85
+ * Runner's finish/teardown, which is where a SUCCESSFUL run's resources have always been released.
86
+ * The catch path calls {@link RollbackStack.unwindAll}, which runs the cleanups in reverse order,
87
+ * each exactly once, none of them able to stop another — a bounded settle, the same posture the
88
+ * teardown leg already uses. NEVER call unwind on the success path.
89
+ *
90
+ * The detach guard for an owned execution env and the worktree-isolation check stay with the DRIVER
91
+ * (design/238 D-8 case ①): a phase pushes, it does not destroy, because the driver's reference is
92
+ * the authoritative one and a phase-local rebind could never reach it.
93
+ */
94
+ export interface RollbackStack {
95
+ /** Register one cleanup for the failure path. Called immediately after the handle is acquired. */
96
+ push(cleanup: () => void | Promise<void>): void;
97
+ /** Disarm: prepare succeeded, so ownership passes to `Prepared` and the stack is emptied. */
98
+ commit(): void;
99
+ /** Failure path only — run every registered cleanup in reverse order, each once, none blocking another. */
100
+ unwindAll(): Promise<void>;
101
+ }
102
+ /**
103
+ * design/164 件五 — the run's view of deployment usage governance, built once at prepare when
104
+ * `RunnerDeps.usageWindows` + `usageWindowStore` are both wired (absent otherwise, so every consumer is
105
+ * an explicit `!== undefined` test and an ungoverned deployment executes not one extra line).
106
+ *
107
+ * Both methods are called SEQUENTIALLY by the run loop (entry check, then one commit per turn boundary,
108
+ * then one final commit) — the delta bookkeeping in `commit` assumes that and is not a concurrency
109
+ * primitive.
110
+ */
111
+ export interface UsageGovernance {
112
+ /** The ledger key this run is governed under — the principal, or the shared global key. */
113
+ readonly key: string;
114
+ /** Does any governed window carry a MONEY ceiling? Read by the run loop's pricing seats: only a
115
+ * cost-governing deployment has to treat an unevaluable price table as unpriced spend. */
116
+ readonly governsCost: boolean;
117
+ /** Ms the caller must wait before ANY window would admit work again, or `undefined` when none is
118
+ * exhausted as of `now`. Reads the ledger; propagates a store failure (an unreadable ceiling must not
119
+ * read as an open one). */
120
+ check(now: number): Promise<number | undefined>;
121
+ /**
122
+ * Charge whatever of the run's cumulative spend has not been charged yet. Takes the run's CUMULATIVE
123
+ * totals rather than deltas so no caller can double-charge by calling twice, and so a caller that skips
124
+ * a boundary loses nothing.
125
+ *
126
+ * `cumulativeCostMicroUsd` is the MONEY half (integer micro-USD, `stats.costMicroUsd`). Pass `undefined`
127
+ * when the run's spend has no cost figure at all (RB-368's unpriced state) — a deployment governing a
128
+ * `maxCostUsd` window then REFUSES here rather than charging the fabricated 0 that would let the ceiling
129
+ * silently stop applying. A token-only deployment ignores the argument entirely.
130
+ */
131
+ commit(cumulativeTokens: number, cumulativeCostMicroUsd: number | undefined, now: number): Promise<void>;
132
+ }
133
+ /**
134
+ * design/381 — the run's turn-start file-history BOUNDARY seat. `begin(entryId)` starts the capture
135
+ * for the turn's own initial entry (first-wins: exactly one boundary per turn incarnation, DV-4);
136
+ * `settle()` awaits the in-flight capture's settle and is the caller's LEASE CLOSE (awaited before
137
+ * the first tool executes) as well as the finish-tail durability await. The capture is bounded by a
138
+ * 30s timeout whose abort FENCES the attempt (the store's `boundaryPublishVerdict` guarantees a
139
+ * timed-out capture never publishes); failure is disclosed via onError(phase:"rewind") and NEVER
140
+ * blocks the turn — a turn whose capture failed simply has no boundary (the reference behaves the
141
+ * same), and there is no mid-turn re-capture (the store's spent lease refuses it with zero reads).
142
+ */
143
+ export interface FileHistoryBoundarySeat {
144
+ begin(entryId: string): void;
145
+ settle(): Promise<void>;
146
+ }
147
+ export interface Prepared {
148
+ harness: AgentHarness;
149
+ /** The CONCRETE built-in session (engine-internal: prepare constructs/acquires `StoredSession` itself,
150
+ * and the epoch pin path needs its `appendPromptEpoch`/`getPromptEpoch`). Public consumer faces take
151
+ * the `Session` contract instead. */
152
+ session: StoredSession;
153
+ sessionId: string;
154
+ /**
155
+ * #499 — THIS INVOCATION's own identity, minted once at the top of {@link prepareTask} and never
156
+ * rewritten. The third id of the trio, and the only one the engine owns outright:
157
+ * - `spec.taskId` — the HOST's task identity (absent whenever the host names nothing);
158
+ * - `sessionId` — the CONVERSATION's identity (shared by every run that continues it);
159
+ * - `runId` — THIS call of the engine.
160
+ *
161
+ * The gap it closes: the repo-wide `spec.taskId ?? sessionId` spelling answers the same value for
162
+ * two runs of one session whenever the host supplies no task id, so every per-run account keyed on
163
+ * it FOLDED two runs into one row (two runs each losing one steer read as one run losing one).
164
+ * A per-run account must key on this; a per-TASK fact (trace `taskId`, the host's own correlation
165
+ * handle) must keep the task spelling — the two are different questions and the station sweep
166
+ * judged each one.
167
+ *
168
+ * Minted here (never at the Runner's stream entry) so that a standalone `prepareTask` exercise gets
169
+ * a real id too, and so the mint has exactly one site. A leg whose prepare THROWS never returns a
170
+ * `Prepared` at all — but the id still reaches its caller through the `runIdSink` carrier, because
171
+ * prepare emits run-scoped disclosures of its own and each must have a terminal that names it.
172
+ */
173
+ runId: string;
174
+ /** design/319 (A ticket) — the session's reminder provenance mark this run mints under (adopted
175
+ * through the prepare adoption ladder: checkpoint seed → trusted fork channel → session entry →
176
+ * fresh mint). Every engine-authored `<system-reminder>` open tag in the run carries it, and the
177
+ * system prompt's Harness declaration names it. Always present on a completed prepare. */
178
+ reminderMark: string;
179
+ /** design/319 (B ticket) — the leg's reminder-disclosure trigger counters (mutated by the
180
+ * disclosure outlets at tool-execute time; read once at result assembly into
181
+ * `stats.mechanisms.reminderDisclosures` when any key is non-zero). Always present. */
182
+ reminderDisclosureCounts: import("../reminder-disclosure.js").ReminderDisclosureCounts;
183
+ /** The ISOLATION-AWARE working-tree root for this task (a worktree's cwd when `isolation: "worktree"`, else
184
+ * `deps.rootPath ?? executionEnv.cwd`) — the same value the hands/LSP/policy/restore use. The Runner's
185
+ * rewind/snapshot path MUST key off THIS, not `deps.rootPath`, or a worktree-isolated turn snapshots the base
186
+ * repo (CORE-1~9 audit MAJOR). */
187
+ taskRootPath: string;
188
+ model: Model;
189
+ /** Effective thinking level (explicit `spec.thinking` or the resolved role's default). */
190
+ thinking?: ThinkingLevel;
191
+ compModel?: Model;
192
+ mcp: MaterializedMcp;
193
+ /** Present only when `spec.a2a` declared peers — the run loop owes it the same end-of-task dispose
194
+ * it owes {@link mcp} (no sockets are held, but a disposed mount is what makes a post-task tool
195
+ * call refuse loudly instead of dialing a peer on a dead task's behalf). */
196
+ a2a?: MaterializedA2a;
197
+ blockedRef: BlockedRef;
198
+ /** Holds the structured output once `submit_output` is called (when `spec.outputSchema` is set). */
199
+ outputRef: OutputRef;
200
+ /** Fires when the task aborts (timeout / max turns / end). Passed to `ToolPolicy.check` so a
201
+ * pending human-approval gate is released instead of hanging past the deadline (F4). */
202
+ abortController: AbortController;
203
+ /** Flipped if any session write lost the optimistic lock during the run → `errorCode = "conflict"`. */
204
+ conflictRef: {
205
+ hit: boolean;
206
+ };
207
+ /** design/134 复审: tool-call ids the gate blocked (policy/hook/plan-mode deny) or suspended —
208
+ * populated only while a consumer is wired (per-tool post hooks or postToolBatch). The runner's
209
+ * batch collector DELETES on match (its tool_execution_end is the only end-event a blocked call
210
+ * emits; the tool_result-side delete in prepare-task never fires for immediate results). */
211
+ blockedToolCalls: Set<string>;
212
+ /**
213
+ * WHAT ended the approval a gated call was waiting on and — design/252 G-7 — WHOSE settlement it
214
+ * was, keyed by tool-call id: written ONLY by the tool gate, at the one exit where an ask resolved,
215
+ * and read once when that call's `tool_end` frame is minted (the reader deletes on read; a call the
216
+ * gate never settled has no entry, and an entry never names neither fact).
217
+ *
218
+ * ONE record rather than two parallel maps because they are one observation: an attribution without
219
+ * the settlement kind beside it is unreadable ("alice" — approved? her window elapsed?), and two maps
220
+ * keyed alike are two chances to drain one and leak the other.
221
+ *
222
+ * It is a sideband and not a field on the tool RESULT because a result is not a trustworthy carrier
223
+ * for this: `details` is arbitrary tool-authored data that post-tool hooks may also replace, so a
224
+ * failing tool could stamp `settledBy:"human"` on itself and tell a consumer's audit view that a
225
+ * person approved something nobody was ever shown. Provenance has to travel on a channel only the
226
+ * adjudicating layer can write. Same reason the entries are keyed by CALL id: the gate adjudicated
227
+ * that exact call, and the frame that reads it is that call's own.
228
+ */
229
+ approvalSettlement: Map<string, {
230
+ settledBy?: import("../tool-policy.js").ApprovalSettledBy;
231
+ approver?: string;
232
+ resolution?: import("../tool-policy.js").AskDenyResolution;
233
+ autoDenied?: true;
234
+ }>;
235
+ /**
236
+ * The parent-thread human-rejection halt fact (see `maybeHumanRejectionHalt`): present from the
237
+ * moment a bare human rejection halts the turn's batch until the run ends or the NEXT provider
238
+ * request begins (user input continuing the run clears it). Consumers: the runner's stop gate
239
+ * (suppress natural-end pushback / final-verify injection — engine continuations must not restart
240
+ * a run a person just stopped), the turn-boundary engine steers (same reason), and the result
241
+ * stamp (`TaskResult.haltedOnUserRejection` — a human-halted run must not read as an ordinary
242
+ * completion). Engine-owned sideband, same trust reasoning as `approvalSettlement` above.
243
+ */
244
+ batchHaltRef: {
245
+ current?: {
246
+ rejectedToolCallId: string;
247
+ };
248
+ };
249
+ /** Summed usage of nested sub-runs (sub-agents) spawned by this task's tools. */
250
+ nestedStats: NestedUsageAccum;
251
+ /** RB-430-a: prepare-time rewind disclosures (conversation-only branch / no snapshot backend / no file
252
+ * env), echoed verbatim onto `TaskResult.rewindNotes`. Present only when there is something to say. */
253
+ rewindNotes?: NonNullable<TaskResult["rewindNotes"]>;
254
+ /** The run's edited-file ledger read face — what its OWN hands landed, as `TaskResult.editedFiles`
255
+ * (undefined when nothing landed: the key is absent, never an empty array). A LIVE reader rather
256
+ * than a snapshot, so the throw-path backstop terminal reports the same ledger the ordinary
257
+ * assembly would. Always present on Prepared; independent of whether a fileHistoryStore is wired. */
258
+ editedFilesSnapshot: () => TaskResult["editedFiles"];
259
+ /** design/381 — the run's turn-start boundary seat (present iff a fileHistoryStore is wired and
260
+ * the run mounts a real fs env). runtask calls begin() at the first committed user entry and
261
+ * awaits settle() at the lease close + the finish tail. */
262
+ fileHistoryBoundary?: FileHistoryBoundarySeat;
263
+ /** #240 (design/199 v1.1) + #242 — the run's RESOLVED read face for the result observation seat
264
+ * (`TaskResult.effectiveReadFace`): `carrierReadFace()`'s value at prepare completion — the hands
265
+ * block's single resolution, or the hands-less legs' resolver run (live spec-time facts, with the
266
+ * checkpoint seed folded stricter-wins where one exists). Every leg that completes prepare has a
267
+ * read posture now — this is what its delegation subtree is clamped by even where no faces mount. */
268
+ effectiveReadFace?: ReadFace;
269
+ /** #240 — the normalized deny ADDITIONS in force (deployment ∪ task ∪ checkpoint seed; built-ins
270
+ * excluded), echoed on `TaskResult.effectiveReadDenyPatterns`. Present iff non-empty; a defensive
271
+ * copy (the wide-scope working array stays the engine's own). */
272
+ effectiveReadDenyPatterns?: readonly import("../../tools/fs/read-deny.js").NormalizedReadDenyEntry[];
273
+ /** design/178 v2 §2.3 (件①) — the memory-visibility observation prepareMemory minted (echoed on
274
+ * `TaskResult.effectiveMemoryScopes`). Always present on a completed prepare (the memory-less
275
+ * states are their own values); the seat is optional only so a Prepared shape without the phase
276
+ * cannot fabricate one. */
277
+ effectiveMemoryScopes?: import("../types.js").EffectiveMemoryScopes;
278
+ /** design/99 §E13 — the per-task logical cwd ref when a real shell is mounted (else undefined). The Runner
279
+ * reads `cwdRef.current` after each tool to detect a `cd` move and emit `workspace_changed`. */
280
+ cwdRef?: CwdRef;
281
+ /** design/155: the ACTIVE EnterWorktree session ref (mounted with the worktree tools; undefined without
282
+ * real write hands). runtask's settle write reads `current` for the workspace-state entry. */
283
+ worktreeSessionRef?: {
284
+ current?: ActiveWorktreeSession;
285
+ };
286
+ /** design/155: the settle-write base — the canonical root + what the cwd/worktree were RESTORED to at
287
+ * prepare. runtask diffs the live refs against this at settle and appends a `workspace_state` entry
288
+ * when the state changed (skipped on a durable suspend — the checkpoint lane owns that state). */
289
+ workspaceStateSettle?: {
290
+ rootCanonical: string;
291
+ restoredHandsCwd?: string;
292
+ restoredWorktreeDir?: string;
293
+ baselineUnknown?: boolean;
294
+ };
295
+ /** #483 codex r2+r3 — the settle-time session-seat SEAL (see prepare-hands-readface): re-anchors
296
+ * the per-session read-state seat to the entry id THIS run last committed (its own
297
+ * message_committed tail — provenance, never a shared-leaf re-read). The driver calls it once at
298
+ * the run's settle, every terminal (suspend included), under the session lock; undefined argument
299
+ * (no commits) is a no-op. Synchronous, never throws. Absent ⇔ hands-less / no seat channel. */
300
+ sealReadStateSeat?: (ownCommittedTailEntryId: string | undefined) => void;
301
+ /** design/99 §E6 — the DENY-NARROWING layers (session rules + skill scope, deny-only). Re-checked on RESUME
302
+ * before an approved pending tool executes, so a rule tightened during the suspend still applies. */
303
+ denyNarrowingPolicy?: ToolPolicy;
304
+ /** RB-63: the deployment's own caller policy, re-checked on a durable resume ONLY when the approver
305
+ * rewrote the pending call's args (see the composition site for why the edit case is special). */
306
+ basePolicyForResumeEdit?: ToolPolicy;
307
+ /** design/182 §7 — the ORG adjudication face, re-resolved on a durable RESUME before an approved
308
+ * pending call executes. The resume path bypasses the harness gate by design (a human already
309
+ * adjudicated the checkpointed call), which is exactly where org policy skew is most likely: the
310
+ * suspend may have outlived the snapshot revision that was current when it was minted. Present only
311
+ * on a governed deployment. */
312
+ permissionRuleOrg?: {
313
+ adjudicate: (req: ToolCallRequest) => Promise<OrgGateVerdict>;
314
+ };
315
+ /** Removes the `spec.signal` abort listener on task end (else a long-lived signal leaks listeners). */
316
+ releaseSignal: () => void;
317
+ /**
318
+ * design/174 — end-of-leg sweep for questions this leg's gate routed to a person. Called once by the
319
+ * run loop at task end, on every exit path. A binding that is still present means a person ANSWERED and
320
+ * the call never executed to collect it (aborted, batch torn down, loop threw): that answer is disclosed
321
+ * through the deployment's error sink rather than dropped, because "a human answered and it vanished" is
322
+ * precisely the failure this whole path exists to remove — it must not reappear inside the mechanism
323
+ * that removes it. Idempotent, never throws.
324
+ */
325
+ settleContentAskBindings: () => ReadonlyArray<{
326
+ deliveryId: string;
327
+ toolCallId: string;
328
+ }>;
329
+ /** Per-task prefix-cache-break detector (design/31). The fingerprint is mutated when deferred tools
330
+ * materialize (design/36) — see `cacheFingerprint`. */
331
+ cacheBreakDetector?: CacheBreakDetector;
332
+ /** The fingerprinted prefix. `systemPrompt` is stable; `tools` is REFRESHED in place when a deferred
333
+ * tool is materialized (placeholder→full schema), so the design/31 detector sees the real tool set. */
334
+ cacheFingerprint?: {
335
+ systemPrompt: string;
336
+ tools: ToolFingerprintInput[];
337
+ };
338
+ /**
339
+ * 提示词主权批 — the labelled composition of the assembled system prompt, emitted as the
340
+ * `prompt.assembled` trace event at task start. `constitution` says who owned the safety layer:
341
+ * `"core"` (structural, the default), `"replaced"` (provider set `replaceAll` — deliberate opt-out),
342
+ * `"provider-assembled"` (migration guard: a historic provider returned a full prompt, passed through
343
+ * un-doubled + onError hint). Deployments/tests assert on this to make "which blocks were in the
344
+ * prompt" a runtime fact instead of archaeology.
345
+ */
346
+ /**
347
+ * design/173 §8.1 — this leg's EFFECTIVE wiring manifest (built once in prepare from resolved
348
+ * facts through the same derivation as the static half). runtask emits it as the
349
+ * `wiring_manifest` TaskEvent after the prepare consume point and before the leg's first
350
+ * model/tool interaction. Host/operator plane — never enters model context.
351
+ */
352
+ wiringManifest: WiringManifest;
353
+ /**
354
+ * #281 件A — this leg's frozen identity envelope, minted ONCE in prepare beside the wiring
355
+ * manifest (same leg derivation, one mint — {@link mintHookInvocationIdentity}). Every hook
356
+ * station runtask drives (stop/stopFailure/userPromptSubmit/postToolBatch, the compaction
357
+ * wrapper) and the 件B delegation-lifecycle observer read THIS object; prepare's own stations
358
+ * (the tool gate, the post-tool contexts) close over the same const. Always present — a prepared
359
+ * leg always knows its identity.
360
+ */
361
+ hookIdentity: HookInvocationIdentity;
362
+ /**
363
+ * The per-invocation TIME BOUND every hook seat of this leg runs under (`Hooks.timeoutMs`, already
364
+ * validated — a garbage value was refused to the default and disclosed ONCE, here, rather than on
365
+ * every tool call). Published for the same reason `hookIdentity` is: the seats live in two files, and
366
+ * a number each station re-derived would be two answers to one wiring question — including two
367
+ * chances to re-refuse the same bad value.
368
+ */
369
+ hookTimeoutMs: number;
370
+ promptManifest: {
371
+ constitution: "core" | "replaced" | "provider-assembled";
372
+ blocks: Array<{
373
+ id: string;
374
+ chars: number;
375
+ hash: string;
376
+ }>;
377
+ /** Manifest v2 (stage S1, additive): the compiled-IR section view (slot/carrier/cadence/
378
+ * cacheClass per section). `contentHash` is the
379
+ * digest-tiering face: present ONLY on operator-declared sections (the typed
380
+ * `stableBlocks` lane, owner "deployment") as an UNSALTED full sha256 of the section text —
381
+ * the center-publish ↔ manifest end-to-end reconciliation anchor. Core-native sections (env
382
+ * facts, memory tail, user role text) stay salted-only: a plain hash of a short guessable
383
+ * block is a dictionary-preimage surface for trace readers ([E]). */
384
+ sections?: Array<{
385
+ id: string;
386
+ slot: string;
387
+ carrier: string;
388
+ cadence: string;
389
+ cacheClass: string;
390
+ chars: number;
391
+ hash: string;
392
+ contentHash?: string;
393
+ }>;
394
+ /** S2 (additive): the mounted tools plane — contract identity, durable-replay aliases,
395
+ * presentation-invariant shape digest and full wire digest per tool (initial mount face). */
396
+ tools?: ToolManifestRow[];
397
+ /** design/148 S3 (additive, §10.2): the nine-element cache identity — digests only, no prompt
398
+ * text; backfilled once the final wire tool list exists. Live post-refresh truth rides
399
+ * `prepared.turnSnapshot`. */
400
+ snapshot?: {
401
+ cacheIdentity: string;
402
+ elements: import("../../prompt-assembly/turn-snapshot.js").CacheIdentityElements;
403
+ };
404
+ /** design/148 S3 (additive, §10.1): the run's lowering record (version/wire form/known
405
+ * intentional divergences — run-static v1, one brain serves every call). */
406
+ lowering?: import("../../prompt-assembly/turn-snapshot.js").LoweringRecord;
407
+ /** design/168 (additive): the RESOLVED deferred-tool disclosure strategy for this leg and which
408
+ * seat chose it. Absent when nothing is deferred (there is no disclosure to describe). */
409
+ toolDisclosure?: ToolDisclosureManifest;
410
+ };
411
+ /** This run's provider-declared prompt sections (epoch declaration axis),
412
+ * threaded to every compaction-boundary epoch selection so boundary re-pins hash the same
413
+ * artifact identity as the prepare-time pin. Empty on declaration-free runs. */
414
+ epochDeclaredSections: import("../../prompt-assembly/epoch.js").EpochDeclaredSections;
415
+ /** design/148 S3 — the LIVE nine-element identity face (refreshed by deferred materialization and
416
+ * the RB-31 adoption swap); the manifest holds the prepare-time initial copy. */
417
+ turnSnapshot?: import("../../prompt-assembly/turn-snapshot.js").TurnPromptSnapshot;
418
+ /** RB-31 (design/148 S2) — the compaction-boundary center-adoption seam (undefined = no source
419
+ * wired or session not center-pinned). Returns the maybeCompact `centerAdoption` fragment or
420
+ * undefined; `apply` runs post-CAS only (auto-compaction owns the ordering). Both
421
+ * `epochDeclaredSections` and `promptOverheadTokens` on THIS object are mutated by a successful
422
+ * adoption (read them at call time, never capture early). */
423
+ centerCompactionCandidate?: () => {
424
+ centerArtifactDigest?: string;
425
+ sourceRevision?: string;
426
+ clear?: true;
427
+ declaredSections: import("../../prompt-assembly/epoch.js").EpochDeclaredSections;
428
+ overheadTokensAfter: number;
429
+ apply: (committedArtifactDigest?: string) => void;
430
+ } | undefined;
431
+ /** Deferred-tool disclosure (design/36): the monotonic set of activated deferred-tool names. Empty
432
+ * (and no `tool_search` injected) when nothing is deferred. Mutated by BOTH disclosure lanes across
433
+ * the run — the injected `tool_search` and the RB-403 direct-call placeholder lane (default ON) —
434
+ * under ONE shared activation critical section, plus resume seeding at prepare. A leg on which the
435
+ * model never calls `tool_search` is therefore NOT quiescent. */
436
+ activeTools: Set<string>;
437
+ /** RB-313 — the DECLARED deferred set (design/36 `classifyDeferred`, ghost names already pruned).
438
+ * Present iff the task has deferred tools at all; `deferredToolNames − activeTools` is the
439
+ * "undiscovered" census the tool_search_usage_reminder lane enumerates. Frozen at prepare time: a
440
+ * name never leaves the deferred set, it only moves into `activeTools`. */
441
+ deferredToolNames?: ReadonlySet<string>;
442
+ /** design/168 — the RESOLVED materialization strategy this run runs under (`true` = "static":
443
+ * activation never swaps the placeholder; the real schema's only in-context carrier is the
444
+ * ToolSearch result text). Consumed by the tools_delta boundary renderer, whose "full schemas are
445
+ * loaded" wording is a statement about the tools block and is only true under swap. `false` when
446
+ * nothing is deferred (the knob is inert then). */
447
+ toolMaterializeStatic: boolean;
448
+ /** RB-403 — is the direct-call lane mounted on this run's placeholders (`TaskSpec.deferSelfResolve`
449
+ * not disabled; default ON)? The SAME fact `createToolSearchTool` receives as `directCallEnabled`,
450
+ * surfaced here so every model-facing face that describes what happens to a call on a
451
+ * still-deferred tool reads ONE value — under the direct lane a schema-valid call executes rather
452
+ * than failing, so an absolute failure claim is only true for the opt-out posture. `false` when
453
+ * nothing is deferred (no placeholders, so the fact is inert). */
454
+ deferDirectCall: boolean;
455
+ /** design/168 — is THIS deferred name on the static face? False under `"swap"`, and false under
456
+ * `"static"` for a tool whose declaration the result-text carrier cannot hold (the per-tool
457
+ * exemption: it materializes into the tools block instead). Read at call time — the roster is
458
+ * mutated in place by MCP refresh, so renderability is a live fact. Absent when nothing is
459
+ * deferred; a caller with no accessor has no deferred family to describe. */
460
+ staticFaceFor?: (name: string) => boolean;
461
+ /**
462
+ * design/138 S1 — the MemoryEngine session. Present when `deps.memoryBackend` + `spec.memory.enabled`
463
+ * hold AND the engine mount succeeded: a materialize failure without a `config.memory_*` code is
464
+ * fail-open (reported via `deps.onError`, the task runs memory-less), leaving this absent even though
465
+ * both flags hold.
466
+ * `harvest` is the swallow-guarded boundary hook (task terminal in runtask + the checkpoint mint
467
+ * point in commitSuspendSaga): it runs the FULL gate set (containment/secret/caps/deletion fuse),
468
+ * commits entry patches to the backend, self-heals the derived index, and re-baselines (a second
469
+ * harvest of an unchanged session yields zero patches). It NEVER throws.
470
+ * S2-B (O-F7/C-F3): the report is NOT discarded — `harvest` hands it to the Runner-owned
471
+ * `deps.onMemoryHarvestReport` callback (with the boundary phase), and the engine itself enqueues
472
+ * the announcement-queue entry at its harvest tail (drained into the NEXT session's first inject —
473
+ * 时机①; the r1 in-run attachments lane was cut, O-F2/C-F4). `phase` defaults to "terminal" (the
474
+ * runtask call site passes nothing); the checkpoint-mint call site passes "checkpoint".
475
+ */
476
+ memoryEngineSession?: {
477
+ /** The WRITE-plane pair (design/142 S2b: dual roots collapse to one session face; these are the
478
+ * plane that owns the write gate — the read-only plane is internal to `inject`/`harvest`). */
479
+ engine: MemoryEngine;
480
+ handle: MemorySessionHandle;
481
+ /** Merged injection across all planes (single-root sessions: identical to engine.inject(handle)). */
482
+ inject: () => import("../memory-engine/engine.js").MemoryInjection;
483
+ harvest: (phase?: "checkpoint" | "terminal") => Promise<HarvestReport | undefined>;
484
+ /**
485
+ * design/383 §2.1 — the session's capture opt-out face (the `TaskStream.optOutMemoryCapture`
486
+ * verb's target; host-API only — no tool face reads it, §2.6). `flip` re-adjudicates the
487
+ * entitlement at call time (fresh caps resolve), mints the one-way record, runs the §2.3
488
+ * boundary sweep, and delivers the effectiveness notice; its typed refusals are the
489
+ * `memory.capture_optout_*` family. `optedOut` is the live state read (declared / standing /
490
+ * flipped) — a GENUINE-record read: a store fault answers false here and TRUE on
491
+ * `indeterminate` instead (rescan post-6.0.0-RC — the fault must reach the delegation floor
492
+ * as its own third state, never as either boolean; an irreversible record is never minted off
493
+ * an unreadable state, and an outage must not spawn un-floored children). Present whenever
494
+ * the memory session mounted.
495
+ */
496
+ captureOptOut?: {
497
+ /** Dual form: a sync capture store answers synchronously; a Promise-form store answers a Promise. `await` is correct on either arm. */
498
+ optedOut: () => boolean | Promise<boolean>;
499
+ indeterminate: () => boolean | Promise<boolean>;
500
+ flip: (reason?: string) => Promise<{
501
+ outcome: "created" | "existed";
502
+ }>;
503
+ };
504
+ /**
505
+ * design/178 §3 — the session's ONE-WAY pollution face. `markPolluted` fires when an
506
+ * external-content-class tool is invoked (the prepare-time tool wrap below is the caller);
507
+ * durable + in-process, no unmark exists at any layer. `polluted` is what the harvest legs read
508
+ * (they consult it at harvest time themselves — this accessor serves observers/tests).
509
+ */
510
+ pollution: {
511
+ polluted: () => {
512
+ at: number;
513
+ reason: string;
514
+ cause?: import("../memory-engine/types.js").MemoryOriginCause;
515
+ } | undefined;
516
+ /** design/336 §2.2 — `cause` is the structured mechanical fact the mark records (and the
517
+ * origin marker minted off it carries): `"observed"` for a witnessed external event,
518
+ * `"static"` for the capability over-approximation, `"derived"` for recall-taint. Absent
519
+ * folds to `"observed"` at mint time (the honest floor). */
520
+ markPolluted: (reason: string, cause?: import("../memory-engine/types.js").MemoryOriginCause) => void;
521
+ };
522
+ /** design/178 §3 — the task's content-safety config (normalized memory spec): the allowlist for
523
+ * UNDECLARED tools and the strict execution-class upgrade. Consumed by the tool wrap only. */
524
+ contentSafety: {
525
+ trustedTools: ReadonlySet<string>;
526
+ execIsExternalContent: boolean;
527
+ };
528
+ /**
529
+ * design/336 §3.3 — the delegation-settlement handle: the control-plane coordinates a
530
+ * settlement writer needs, as PURE DATA. Consumers (the subagent background leg's write-ahead
531
+ * + terminal observation, the tool wrap's sync unattestable row) can outlive this prepared
532
+ * leg, so they rebuild their write handle from these fields alone — never from the live
533
+ * engine/session objects above. Present only under `memoryProvenance: "carry"` (the default):
534
+ * an `"off"` deployment keeps the pre-336 accepted-cost posture byte-level.
535
+ */
536
+ settlement?: {
537
+ /** The WRITE plane's control-plane dir (the pollution-marker/lineage sidecar home). */
538
+ controlDir: string;
539
+ sessionId: string;
540
+ provenance: "carry";
541
+ };
542
+ /**
543
+ * design/336 §5.5 (file-face half) — the Read-tool recall-taint judgment, present only under
544
+ * `memoryProvenance: "carry"`. True ⇔ the delivered ABSOLUTE path sits inside a mounted memory
545
+ * plane and its head bytes carry a committed external-origin marker; the tool wrap then marks
546
+ * the session derived (same seat and cause as the memory_get propagation). Never throws;
547
+ * relative paths and unreadable files answer false (named residuals beside the Bash channel).
548
+ */
549
+ recallTaint?: {
550
+ judgeDeliveredPath: (absPath: string) => boolean;
551
+ };
552
+ };
553
+ /** A per-task env minted by `RunnerDeps.executionEnvFactory` (design/48 remote seam) that THIS task owns
554
+ * and the Runner must tear down on task end. Undefined when the env came from a (caller-owned) static
555
+ * `deps.executionEnv` or the stub — those outlive the task and must NOT be destroyed here. */
556
+ ownedEnv?: ExecutionEnv;
557
+ /** design/45: a mutable holder the durable-suspend gate writes when a policy `ask` was checkpointed
558
+ * (capture + abort). The run loop reads it to assemble `status:"suspended"`. Empty unless a suspension
559
+ * fired this run.
560
+ *
561
+ * `gatedCallId` is the id of the tool call the committed gate is holding — read straight off the
562
+ * committed checkpoint's `tool_approval` pendingAction, so the id a contaminated sibling frame names
563
+ * and the id the checkpoint parks on are the SAME value by construction, not by convention. ABSENT
564
+ * (never guessed) for a park that binds no tool call at all — a `resource_limit` slice and a
565
+ * `plan_review` pause both have pendingActions with no tool call, so there is no causal id to name.
566
+ * Written unconditionally by the commit-side publisher precisely so a later park cannot inherit an
567
+ * earlier one's id. */
568
+ suspendRef: {
569
+ token?: CheckpointToken;
570
+ checkpointId?: string;
571
+ gate?: CheckpointGate;
572
+ scope?: string;
573
+ restoreMode?: "snapshot" | "park_only";
574
+ gatedCallId?: string;
575
+ };
576
+ /** Ruled 2026-08-05 (matrix ruling arm A): set true by the resume engine when this leg EXECUTES the
577
+ * approved pending call — the restart-loop cap then counts from a fresh base (consecutive
578
+ * no-progress suspends only). See `suspendChainBase`. */
579
+ suspendProgressRef: {
580
+ executedApproved: boolean;
581
+ };
582
+ /** design/76 §2.5 (dry-run / shadow) + design/80 D-B (plan-gate): the DUAL of {@link suspendRef} for the
583
+ * REVIEW-PAUSE family — a `{kind:"needs_review"}` pause (a profile's dry-run interception committed a
584
+ * checkpoint whose predicted state-diff a human/judge must REVIEW) OR a `{kind:"plan_review"}` pause (a
585
+ * profile's plan-gate committed a checkpoint whose proposed PLAN a human must approve/edit/reject). The
586
+ * commit-side discriminant (`publishCommittedSuspend`) writes HERE for a `needs_review` OR `plan_review`
587
+ * gate and into {@link suspendRef} for every other gate kind — **never both** (else assemble-result's slot
588
+ * 8.6 `needs_review` branch is dead code, v4 MAJOR-A). The run loop reads it to assemble
589
+ * `status:"needs_review"`. Empty unless a review pause fired this run. */
590
+ reviewRef: {
591
+ token?: CheckpointToken;
592
+ checkpointId?: string;
593
+ gate?: CheckpointGate;
594
+ scope?: string;
595
+ restoreMode?: "snapshot" | "park_only";
596
+ gatedCallId?: string;
597
+ };
598
+ /** RB-439-a: the remote-workspace lifecycle failures this run hit, appended in call order and echoed
599
+ * verbatim on `TaskResult.remoteEnvFailures`. A shared array (not a per-call return) because a suspend
600
+ * refusal is reported through the deployment's `onError` side channel and the run then continues or
601
+ * stops by its own rules — without this collector the caller's result kept no trace that a durable
602
+ * suspend was even attempted, let alone which of the eleven codes refused it. Empty unless something
603
+ * failed. Resume-leg failures do NOT land here (that leg throws out of prepare before a `Prepared`
604
+ * exists) — they ride the thrown error's `remoteEnvFailure` carrier instead. */
605
+ remoteEnvFailures: NonNullable<TaskResult["remoteEnvFailures"]>;
606
+ /** design/72 §2.2 (B): set when a suspend was REFUSED because the task already suspended `maxSuspends`
607
+ * times (a resume/restart loop) — the run is aborted and assembles as `failed`/`suspend.loop` instead
608
+ * of minting yet another checkpoint. */
609
+ suspendLoopRef: {
610
+ hit: boolean;
611
+ };
612
+ /** design/74 Slice 3c: opt-in resource-slice suspend. Present (≠ undefined) ONLY when the task opted in
613
+ * (`spec.resourceSuspend`) AND it is eligible to suspend durably (a checkpoint store, durable tool
614
+ * results, and a remote — or static caller-owned, never per-task-stub — env). The run loop calls it at a
615
+ * CLEAN turn boundary when a resource limit (turns/budget/walltime) was hit: it mints a `resource_limit`
616
+ * checkpoint + pauses the workspace + stops the loop cleanly (NOT abort). Returns true iff it committed a
617
+ * resumable checkpoint (sets `suspendRef`); false ⇒ caller falls through to normal limit handling.
618
+ * `sliceSpend` (Slice 4) is THIS slice's cost/tokens/turns, debited onto the cross-slice ledger. */
619
+ suspendForResource?: (reason: ResourceLimitReason, sliceSpend: {
620
+ costMicroUsd: number;
621
+ tokens: number;
622
+ turns: number;
623
+ walltimeMs: number;
624
+ }) => Promise<boolean>;
625
+ /** design/164 件四/件五: the PLATFORM-cause suspend — the same commit saga as {@link suspendForResource},
626
+ * exposed on the INFRASTRUCTURE alone (checkpoint store + durable tool results + remote/no owned env),
627
+ * WITHOUT the `spec.resourceSuspend` opt-in. The run loop calls it at a clean turn boundary when the
628
+ * execution environment is about to be reclaimed (`env_lifetime`) or a deployment usage window is
629
+ * exhausted (`usage_window`) — causes the task did not choose and cannot ask differently for, so a
630
+ * deployment that CAN keep the work has no reason to be asked whether it wants to. `hint.resumeAfterMs`
631
+ * (usage windows only) rides the gate and extends the checkpoint deadline. Returns true iff it committed
632
+ * a resumable checkpoint; false ⇒ the caller stops the run LOUDLY with the cause's terminal code. */
633
+ suspendForPlatformLimit?: (reason: PlatformLimitReason, sliceSpend: {
634
+ costMicroUsd: number;
635
+ tokens: number;
636
+ turns: number;
637
+ walltimeMs: number;
638
+ }, hint?: {
639
+ resumeAfterMs: number;
640
+ }) => Promise<boolean>;
641
+ /** design/164 件四 — epoch ms at which this run must stop and checkpoint because the EXECUTION
642
+ * ENVIRONMENT's declared lifetime is about to expire (`ExecutionEnv.lifetimeMs` minus
643
+ * {@link ENV_LIFETIME_SUSPEND_MARGIN_MS}). Undefined ⇒ the env declared no lifetime (every local env,
644
+ * and any adapter on an unbounded host) or declared one the engine could not anchor — in both cases the
645
+ * boundary check is dead code, exactly as it was before design/164. Epoch, not monotonic: the anchor
646
+ * comes from the PLATFORM (an env can be older than this process), which is a wall-clock fact and the
647
+ * one domain both sides can name. */
648
+ envLifetimeSuspendAt?: number;
649
+ /** design/164 件五 — deployment usage governance for this run, or undefined when the deployment wired
650
+ * none (or wired windows without a ledger, which is reported and not enforced). */
651
+ usageGovernance?: UsageGovernance;
652
+ /** 1.296 件2b — epoch ms at which the loop ISSUED the current provider call (stamped by the
653
+ * per-call stall-watchdog closure, consumed+cleared by runtask's brain.call trace row as
654
+ * `callStartedAt`). Always present. */
655
+ callIssuedAtRef: {
656
+ current?: number;
657
+ };
658
+ /** RB-458 — records the FIRST brain call this run's outer guardrail gave up on (see
659
+ * {@link import("../../brain/timeout.js").withBrainCallGuardrail}). Always present; `timedOut`
660
+ * stays absent unless the guardrail fired. The run loop reads it AFTER the loop settles and gives
661
+ * the task the typed terminal — the harness turns a loop throw into an error assistant message, so
662
+ * without this the cause would reach the caller only as the generic `provider.error`. */
663
+ brainCallGuardrailRef: BrainCallGuardrailRef;
664
+ /**
665
+ * #548 — the tool gate's own TYPED STOP: set (once) when the classifier denial limit was reached with
666
+ * no approver to fall back to (headless), together with the run abort. The run loop adopts it as the
667
+ * terminal `threw` (`TaskResult.errorCode` = the error's `code`, `errorMessage` = its sentence) the
668
+ * same way it adopts the brain-call guardrail's — a loop that ended because THIS lane aborted it must
669
+ * report the cause, not the consequence. The abort-result details seam reads it too, so the aborted
670
+ * call's own `tool_end` carries the code. `undefined` ⇒ no gate stop happened.
671
+ */
672
+ gateStopRef: {
673
+ terminal?: Error & {
674
+ code: string;
675
+ };
676
+ };
677
+ /** design/80 D-B — set by a tool calling `ctx.requestReview()` (the first-party `present_plan` tool, CC
678
+ * ExitPlanMode parity): the run loop honors it at the next CLEAN turn boundary by minting a `plan_review`
679
+ * checkpoint. `{ pending }` is set (with an optional reason) the moment a tool requests review; the boundary
680
+ * reads + clears it. First request in a batch wins (idempotent). */
681
+ reviewRequestRef: {
682
+ pending?: {
683
+ reason?: string;
684
+ };
685
+ };
686
+ /** design/80 D-B: present (≠ undefined) ONLY when a `checkpointStore` is wired (the deployment can pause). The
687
+ * run loop calls it at a CLEAN turn boundary when `reviewRequestRef.pending` is set: it mints a `plan_review`
688
+ * checkpoint (`status:"needs_review"`, routes to `reviewRef`) + pauses the workspace + aborts the loop, reusing
689
+ * the SAME commit saga as the human/resource suspends. Returns true iff it committed a resumable checkpoint;
690
+ * false ⇒ the request could not be honored (caller drops it and continues). */
691
+ suspendForReview?: (reason?: string) => Promise<boolean>;
692
+ /** design/74 Slice 4: the prior cross-slice {@link ResourceLedger} (from the resumed checkpoint), so the run
693
+ * loop can size this slice's effective budget = `min(maxCostUsd, remaining)`. Undefined on the first slice
694
+ * (or a non-resource task). */
695
+ resourceLedger?: ResourceLedger;
696
+ /** design/80 D-E-core (A3): a mutable holder the run loop populates (right after `stats` exists) so the
697
+ * human/irreversible_ask suspend can debit THIS leg's live cumulative spend onto the durable approval
698
+ * ledger it attaches (the resource-slice path passes `sliceSpend` explicitly; this event-driven gate has
699
+ * no such arg, so it reads the live spend here). Read at suspend time; absent ⇒ this leg's spend is not
700
+ * debited (the prior ledger still rides for the cross-leg READ). */
701
+ liveSpendRef: {
702
+ get?: () => {
703
+ costMicroUsd: number;
704
+ tokens: number;
705
+ turns: number;
706
+ walltimeMs: number;
707
+ };
708
+ };
709
+ /** design/91: the per-task human-review accumulator (synchronous `resolveAsk` waits this leg + the carried
710
+ * prior-leg burden seeded from the resumed checkpoint). The run loop ADDS the durable-resume latency
711
+ * (`now() − cp.suspendedAt`) on a resume, then surfaces it as `stats.humanReview` at assembly (omitted when
712
+ * empty). **Budget-EXCLUDED** — never folded into cost/the budget gate (design/91 §1). */
713
+ humanReviewRef: {
714
+ count: number;
715
+ totalWaitMs: number;
716
+ gates: Array<{
717
+ kind: string;
718
+ waitMs: number;
719
+ decision?: string;
720
+ toolName?: string;
721
+ toolArg?: string;
722
+ }>;
723
+ };
724
+ /** design/91: the injectable wall-clock the run loop uses for the durable-resume human-review latency
725
+ * (`humanLatencyMs = now() − cp.suspendedAt`), so it reads the SAME clock as the suspend-side `suspendedAt`. */
726
+ now: () => number;
727
+ /** design/45 resume: the FULL resolved tool list (real tools, never deferred placeholders) so the
728
+ * resume engine can execute a previously-suspended pending tool call directly (it bypasses the gate —
729
+ * the human already adjudicated it). Same wrapping (offload + ctx) the harness runs with.
730
+ *
731
+ * ONE array, mutated in place; identity is the contract (every closure that resolves a name at run time
732
+ * reads this exact array). WRITER TABLE (design/238 R-3) — the only stations that write it, in prepare order:
733
+ * · caps-and-workflow — MINTS it (`spec.tools` through the ctx wrap + the large-result wrapper), then pushes
734
+ * ReportBlocked (enableBlockedReport ≠ false), ReportFindings (no caller tool of that name/alias),
735
+ * ExitPlanMode + EnterPlanMode (enablePlanMode ∧ the plan-review face), Workflow (self-orchestration active
736
+ * ∧ runner self ∧ hard sandbox ∧ governance baseline);
737
+ * · the driver — pushes StructuredOutput (outputSchema);
738
+ * · protocol-tools — pushes the MCP tools (through the remote wrapper), RefreshMcpTools (servers declared),
739
+ * the A2A tools; at RUN time its refresh closure splices a server's name-prefix domain out and back in;
740
+ * · hands mount — pushes the hands band (env wired);
741
+ * · delegation-surface — pushes TaskOutput/TaskStop (background ∨ workflow door), SendMessage (door ∨
742
+ * parentNotify ∨ peer lane, ∧ runner self ∧ no shadow), AgentTranscript (door ∧ runner self ∧ no shadow),
743
+ * ListAgents (peer lane ∧ built-in SendMessage ∧ mountable), Monitor (background), EnterWorktree +
744
+ * ExitWorktree (tracked cwd), ReadToolResult (offload store);
745
+ * · question-face — pushes AskUserQuestion (the mount decision);
746
+ * · the driver — pushes CronCreate/CronDelete/CronList (write hands; inert without a daemon);
747
+ * · lsp — pushes the LSP tool (manager wired);
748
+ * · project-context — pushes Skill (manifest), the shared-memory pair and the memory-engine tools;
749
+ * · defer-classify — SPLICES OUT the excluded names and the retracted pair (the only removals at prepare);
750
+ * · memory-engine-session — REPLACES entries in place with the content-origin wrappers when it arms (a mounted
751
+ * memory session or a recorder channel); the refresh seam re-runs the same pass through `contentOriginWrapRef`
752
+ * after a re-splice (identity-tracked, so a wrapper is never wrapped again).
753
+ * tool-disclosure and listings only READ it (`harnessTools` is a derived list; placeholders never enter here). */
754
+ tools: AgentTool[];
755
+ /** Name→effect map for every tool this task can call (design/44 §3). Used by the abort-path orphan
756
+ * reconcile (design/64 §9) to make interrupted tool_results effect-aware (read/idempotent = safe to
757
+ * repeat; write/unknown = outcome unknown). Unknown names default to `write` (conservative). */
758
+ toolEffects: Map<string, ToolEffect>;
759
+ /** scan-1/A5 — the orphans the WAKE/CRASH reconcile closed while preparing this run (empty on a fresh or
760
+ * clean session). The run loop replays them onto the stream at run open as synthetic `tool_end` +
761
+ * `message_committed` frames, the same pair the live-abort leg mints at run close: a previous PROCESS
762
+ * died holding those calls, so this run's stream is the only place a consumer can ever learn they ended.
763
+ * Not the live-abort set — that one is reconciled inside the run and never passes through here. */
764
+ wakeRecovered: RecoveredOrphan[];
765
+ /** Fixed per-request prompt overhead (system prompt + tool schemas, ≈chars/4 tokens). Fed to
766
+ * `maybeCompact.overheadTokens` so the compaction trigger stays accurate in the anchor-less
767
+ * regime (custom Brains that don't report usage — design/64 §26.7). */
768
+ promptOverheadTokens: number;
769
+ /** design/169-A — accessor for the MAIN lane's latest real brain request (systemPrompt/messages/
770
+ * tools snapshot, recorded at the harness's provider seam just before each main-loop call). Fed
771
+ * to `maybeCompact.forkContext` on all three compaction lanes so the summary request can FORK the
772
+ * already-paid main prefix (CC form). `undefined` until the run's first main-loop call. Summary
773
+ * calls themselves never pass through the recorded seam (they ride the separate compaction-brain
774
+ * wrapper), so the snapshot is never polluted by a summary request. */
775
+ lastBrainContext: () => CompactionForkContext | undefined;
776
+ /** Narrow workspace reader for compaction working-file attachments (LONGRUN-2): reads a task file
777
+ * via the SAME env the hands ran against (so remote/k8s/E2B tasks read the container's tree, not
778
+ * the control plane's). Present only when the hands are enabled — without an env there is no
779
+ * workspace to re-read. null = unreadable (deleted/binary/transport error); callers skip it.
780
+ * design/199 件B: `{ withheld }` = the target matches the sensitive-path read deny list — the
781
+ * attachment is deliberately withheld and the consumer must SAY so (an annotation, never a silent
782
+ * skip: a silently missing attachment reads as "file gone", which is a different fact). */
783
+ readTaskFile?: (path: string) => Promise<string | null | {
784
+ withheld: {
785
+ pattern: string;
786
+ };
787
+ }>;
788
+ /** CC post-compact restore parity (2026-07-03): the task's READ files, most recent
789
+ * first (from the hands' readFileState `lastReadAt` stamps). The compaction working-file
790
+ * attachment prefers this over the modified set — CC restores what the model RECENTLY READ,
791
+ * including untouched reference files. Present only with hands (same gate as readTaskFile).
792
+ * RB-197: seeded entries are excluded — their content lives in the system-prompt lane, which
793
+ * compaction never touches, so re-attaching them into the summary would be a duplicate. */
794
+ recentlyReadFiles?: () => string[];
795
+ /** RB-197②(独立复审 + 命中,已修) — canonicalizes a raw (often relative, model-typed) path the
796
+ * SAME way the hands toolkit does (`resolveKey` against the same containment root `readTaskFile`
797
+ * uses), so `maybeCompact`'s kept-tail/instruction-source exclusions compare paths in the SAME
798
+ * coordinate `recentlyReadFiles()` already uses — without this a plain string match silently never
799
+ * fires for the common relative-vs-canonical case. Present only with hands (same gate as
800
+ * readTaskFile); absent there is no containment root to resolve against, and every path source is
801
+ * already in the same raw coordinate anyway. */
802
+ normalizeAttachmentPath?: (raw: string) => Promise<string>;
803
+ /** RB-197②(交叉复审命中,已修) — recognizes the hands Read tool's own dedup-stub markers
804
+ * ({@link isReadDedupStubResult}), so `maybeCompact`'s kept-tail scan can tell a SUBSTANTIVE Read
805
+ * result from a stub hit whose original full transmission may already be summarized away. Present
806
+ * only with hands (same gate as readTaskFile). */
807
+ isDedupStubResult?: (resultText: string) => boolean;
808
+ /** RB-197 (form-one; CC 220 clears readFileState at its compaction landing site, @388663): wired to
809
+ * `MaybeCompactOptions.onApplied` by every compaction lane. Drops the non-seeded read-state entries
810
+ * (the summary just replaced the Read results the dedup stubs point at) and re-registers the files
811
+ * that were re-attached WHOLE. Present only with hands (same gate as readTaskFile).
812
+ * RB-197②(命中,已修): `preserveReadState` carries the kept-tail-visible files that were
813
+ * deliberately skipped for re-attachment — their existing entry must survive the clear too (same
814
+ * reasoning as a seeded entry: the model's view of the file did not change). */
815
+ onCompactionApplied?: (attachedComplete: ReadonlyArray<{
816
+ path: string;
817
+ content: string;
818
+ }>, preserveReadState?: ReadonlyArray<string>) => void;
819
+ /** design/121: the live diagnostics lane (present only when the gate passed — manager w/ registry +
820
+ * write hands + not opted out). `registry` is drained by runtask at turn boundaries; `nudge` is
821
+ * called (fire-and-forget) after each successful edit/write so the language server re-analyzes. */
822
+ lspDiagnostics?: {
823
+ registry: import("../lsp-diagnostics.js").LspDiagnosticsRegistry;
824
+ nudge: (rawPath: string) => void;
825
+ /** This run's key into the registry's delivered set (the registry is DEPLOYMENT-scoped — one per
826
+ * `NodeLspManager` — so "already delivered" has to be qualified by run). runtask passes it to every
827
+ * `drain` and calls `releaseRun` with it at the run's terminal. */
828
+ runIdent: string;
829
+ };
830
+ /** design/133 件④: the live plan-mode flag (`enter_plan_mode` flips it, run-local one-way). Exposed
831
+ * so the run loop's plan-mode attachment producer reads the SAME flag the write-deny enforces —
832
+ * never a second source of truth. Always present (`active:false` when plan mode is unused). */
833
+ planModeRef: {
834
+ active: boolean;
835
+ };
836
+ /** The ctx `requestStopAfterTurn` primitive's run-local mirror (one-way, set when a tool asked for a
837
+ * clean stop after the current turn). The harness latch itself is private to the loop; the turn
838
+ * boundary reads THIS to know that no next request follows — a boundary bundle collected there
839
+ * would be steered into a queue the loop never drains, and every one-shot announcement in it
840
+ * (listing frames, the once-per-session MCP arms) would be committed as delivered while it was not. */
841
+ stopRequestedRef: {
842
+ current: boolean;
843
+ };
844
+ /** Whether prepare's ONE read of the branch's announced snapshot succeeded (see
845
+ * `AnnounceOnceLedger.recovered`). False ⇒ the run loop must not flush the once-per-session arms
846
+ * as a whole-snapshot append on this leg (it would replace the branch's record with a partial
847
+ * one); the leg's announcements then simply repeat next run. */
848
+ announcedSnapshotRecovered: boolean;
849
+ /** A1 (design/66 anchor revision) — the date-flip detector seam: `legDate` = the date frozen
850
+ * into this leg's system prefix; `today()` = the boundary-time LOCAL date (user-zone-bound closure).
851
+ * The run loop feeds both to the `date_change` attachment producer; the prefix itself never
852
+ * re-renders mid-leg (cache preservation, CC parity). Present only when the prompt carries a date. */
853
+ dateChange?: {
854
+ legDate: string;
855
+ today: () => string;
856
+ };
857
+ /** [A2] C-4 (design-A §4) — the loadProjectMemory snapshot's declared instruction sources
858
+ * (`ProjectMemoryLoad.instructionSources`): the probe input AND the lane's per-path baseline
859
+ * hashes for the run loop's `instructions_change` attachment. Present only when the deployment's
860
+ * loader declared a non-empty list; the lane additionally requires
861
+ * `RunnerDeps.probeInstructionSources` — either absent ⇒ zero probe calls, byte-identical. */
862
+ instructionSources?: ReadonlyArray<{
863
+ path: string;
864
+ contentHash: string | null;
865
+ }>;
866
+ /** #500 — the RAW instruction-file text this leg's `loadProjectMemory` returned
867
+ * (`ProjectMemoryLoad.content`), for the compaction lanes' `contextInstructionFiles` seat.
868
+ *
869
+ * Which bytes, exactly: the string prepare-task hands `composeMemoryBlock(projectMem, "project")`
870
+ * — pre-compose, unfenced, straight from the host seam. The two neighbours are deliberately NOT
871
+ * candidates: the assembled `memoryBlock` carries the memory ENGINE's layers (bytes the model
872
+ * itself authored in-band this session through the memory tools) and the seat's contract is
873
+ * host/systemPrompt tier; the COMPOSED project block would arrive at a mint that neutralizes the
874
+ * whole authority family, `user_memory`/`scope` included, so the engine would rewrite the tags of
875
+ * its own composition. Raw text in, one fence at the mint.
876
+ *
877
+ * Present only when the deployment wired the loader AND it answered non-blank — the same
878
+ * predicate that composes the project layer, so the summarizer's copy and the main prompt's copy
879
+ * can never disagree about whether this deployment HAS instruction files. Absent ⇒ every
880
+ * compaction lane omits the key entirely. */
881
+ projectInstructionContent?: string;
882
+ /** The `workflow_size_guideline_change` lane's seam, the {@link dateChange} shape one lane over:
883
+ * `legGuideline` = the RESOLVED guideline this leg's Workflow tool card was built with (the card is
884
+ * a per-mount snapshot, so it never re-renders mid-leg — the model learns a retune from the tail
885
+ * frame instead); `current()` = the boundary-time resolved guideline, read live off
886
+ * `RunnerDeps.workflowLimits` so a deployment retuning it mid-run is observable without a re-prepare.
887
+ * Present only when the Workflow tool is actually MOUNTED — a run with no workflow card has no
888
+ * guideline to change. The direct-construction face (`RunWorkflowToolDeps.sizeGuideline`) is out of
889
+ * scope by construction: this mount never passes it, so the deps channel is the lane's only source. */
890
+ workflowSizeGuideline?: {
891
+ legGuideline: WorkflowSizeGuideline;
892
+ current: () => WorkflowSizeGuideline;
893
+ };
894
+ /** design/133 F5 (§R3 决议): boundary-time external-change scan over the ≤`maxFiles` most-recently-READ
895
+ * files. Stats each via `env.fileInfo` and reports paths whose `mtimeMs` moved past the recorded
896
+ * `lastReadAt` + 2s epsilon (CC getChangedFiles shape: readFileState needs NO new field; the agent's
897
+ * own write-backs refresh `lastReadAt`, so self-edits are immune). ENOENT evicts the readFileState
898
+ * entry (CC evict-only-on-ENOENT — transient stat failures skip, never evict) and is echoed in
899
+ * `evicted` so the caller drops its per-path dedup state in lockstep (LOW-9). Present only with
900
+ * hands; the run loop calls it ONLY when `spec.attachments.changedFiles` opted in (OFF ⇒ zero stat). */
901
+ detectExternalChanges?: (maxFiles: number) => Promise<{
902
+ changed: Array<{
903
+ path: string;
904
+ mtimeMs: number;
905
+ }>;
906
+ evicted: string[];
907
+ }>;
908
+ /** G1 通告层 — deferred tools MATERIALIZED (design/36 rematerialize) but not yet announced at a
909
+ * turn boundary. Appended by the rematerialize diff (newly-activated names only — the announced set
910
+ * is seeded with prepare-time actives INCLUDING resume-reseeded ones, so a resume never replays);
911
+ * DRAINED by the run loop only when the `tools_delta` attachment actually survived the byte cap.
912
+ * Present when the task has deferred tools at all — OR (RB-309) when a declared MCP server failed
913
+ * to connect, so the failure is announceable even on a task whose every MCP tool went missing with it.
914
+ *
915
+ * RB-309 — the same frame's MCP arms, filled by the SAME rematerialize seam / materialize-time
916
+ * projection and drained by the same intact-survival predicate:
917
+ * - `pendingRemoved`: previously-ANNOUNCED tool names that left the live roster (a RefreshMcpTools
918
+ * re-splice whose server withdrew them). CC `removedNames`.
919
+ * - `pendingReadded`: names in `pendingRemoved`'s history that came back on a later refresh. CC
920
+ * `readdedNames`.
921
+ * - `pendingFailed`: declared servers whose connect failed at materialize (`statuses`), name/error
922
+ * neutralized + bounded at intake, MINUS the pairs this session's record already announced (CC
923
+ * `failedMcpServers` compared against the previous attachment — a serving layer runs prepare once
924
+ * per user message, so the per-run set alone re-announced every message). */
925
+ toolsDeltaRef?: {
926
+ pending: string[];
927
+ pendingRemoved: string[];
928
+ pendingReadded: string[];
929
+ pendingFailed: Array<{
930
+ name: string;
931
+ error?: string;
932
+ }>;
933
+ };
934
+ /** G1 通告层续批 (CC `agent_listing_delta` parity) — the mounted delegation tool's agent-type roster
935
+ * (read off `ToolSpec.agentListing`, filled by createSubagentTool), plus the tool's mounted name for
936
+ * the CC-verbatim headers. [c209-C]: this seam is now the roster's ONLY model-facing carrier —
937
+ * the run loop delivers the initial full frame ON THE FIRST USER TURN (prompt-adjacent) and
938
+ * boundary drift deltas after. `models` (Q4, read off `ToolSpec.agentModels`) rides the initial
939
+ * frame's tail line. `seedAnnounced` = a durable-resume leg: the run loop seeds the producer's
940
+ * announced set from the checkpoint's `announcedListings.agents` name-set when present (drift
941
+ * since suspend IS delta-announced), else the MED-3② transcript probe (delivered ⇒ seeded as
942
+ * the current entries; unconfirmed ⇒ the resume leg re-announces the initial listing). Present
943
+ * only when such a tool is mounted AND its roster is non-empty. */
944
+ agentListing?: {
945
+ entries: ReadonlyArray<{
946
+ name: string;
947
+ description: string;
948
+ }>;
949
+ toolName: string;
950
+ seedAnnounced: boolean;
951
+ models?: readonly string[];
952
+ };
953
+ /** [c209-C] skills_listing counterpart of {@link agentListing} — the normalized skills METADATA
954
+ * projection (names/descriptions/attachment paths, never bodies; the exact list `createSkillTool`
955
+ * serves). Initial full `<skills>` frame on the first user turn, drift deltas at boundaries,
956
+ * same seeding contract. Present only when `spec.skills` is non-empty (post 1MB-gate). */
957
+ skillsListing?: {
958
+ entries: ReadonlyArray<SkillListingEntry>;
959
+ seedAnnounced: boolean;
960
+ };
961
+ /** [c209-C] Q5 — the run loop's live mirror of the listing frames' announced NAME-SETS (updated at
962
+ * every commit point: first-frame delivery, intact boundary survival, resume seed). Read by the
963
+ * suspend-time checkpoint serializer (`CheckpointState.announcedListings`) so a resume leg can
964
+ * diff the then-current roster/skills against what the model actually saw. Always present (empty
965
+ * object when nothing announced / no listing faces mounted). [c209-C] R2 C7: `models` mirrors the
966
+ * ANNOUNCED model catalog the same way (advanced only when a committed frame carried one), so a
967
+ * catalog change across a suspend is re-announced as a "Models available…" drift line.
968
+ * `mcpFailed` / `advisories` are the once-per-SESSION arms of the same snapshot (see
969
+ * announce-once-ledger.ts): seeded at prepare from the branch's record, advanced by the run loop
970
+ * on intact delivery of the tools_delta `failedServers` arm / the mcp_dropped_tools frame. */
971
+ announcedListingsRef: AnnouncedListingSnapshotInput;
972
+ /** env-tail migration (#254 shape) — the git-status frame lane's run-local state: this leg's
973
+ * resolved frame (probe outcome rendered + hashed at prepare), the announced `(kind, hash)`
974
+ * mirror the checkpoint serializer reads, the trim-protection slot the request-build context
975
+ * handler matches on, and the re-assert closure the compaction landing + boundary retry call.
976
+ * Always present (empty object on a hands-less leg — the lane is then out of scope). */
977
+ gitStatusRef: GitStatusLaneRef;
978
+ /** G1 通告层 — narrow post-compact getter over the process task registry: THIS run's visible
979
+ * pending/running background tasks (same owner/scope/session identity the TaskOutput/TaskStop tools
980
+ * use), as a bounded display projection (id/description/status — never handles/env/abort). Called by
981
+ * the run loop ONLY when `spec.attachments.backgroundTasks` opted in AND a compaction just landed. */
982
+ listBackgroundTasks: () => Array<{
983
+ id: string;
984
+ description?: string;
985
+ status: string;
986
+ }>;
987
+ /** design/122 D1 — the parent-run subagent-retain ledger (present ONLY when `spec.retainSubagentSessions`
988
+ * is enabled). The Runner disposes it (abort in-flight resumes + unpin + release every retained child
989
+ * session) in the task's terminal `finally` — same UNCONDITIONAL posture as the background-agent reap:
990
+ * retain is NOT durable (a suspend leg's in-memory ledger cannot survive a re-prepare), so releasing on
991
+ * every exit path is hygiene, never a loss. */
992
+ subagentRetain?: SubagentRetainLedger;
993
+ /** design/84 Seam C: run-scoped consecutive-`summaryProvider`-reuse counter, OWNED by the Runner and
994
+ * SHARED across both compaction call sites (within-task turn boundary + `finish()`), so the
995
+ * `maxConsecutiveProviderReuse` drift guard is enforced over the whole task — incremented when a
996
+ * compaction reused the provider's summary, reset to 0 on a real (LLM) summary. */
997
+ compactionReuseRef: {
998
+ consecutive: number;
999
+ };
1000
+ /** design/123 D4 — trim→compaction pressure propagation (16k live sawtooth root cause): set by the
1001
+ * context hook when `trimToBudget` actually DROPPED messages from a request view (request-only trim
1002
+ * + usage-anchor mismatch deflates the next boundary's estimate → the trigger and floor are both
1003
+ * deceived → full-size request spikes alternate with trimmed troughs). The next turn boundary's
1004
+ * `maybeCompact` consumes it as `force: true` (bypasses the auto threshold AND the §25.2 anti-thrash
1005
+ * floor — "the request layer was forced to drop history" is direct evidence compaction is overdue).
1006
+ * One-shot: cleared on consumption; a failed compaction does NOT re-arm it (existing breaker path).
1007
+ * Content-only clears (`clearStaleToolResults`) never set it — only real message drops do. */
1008
+ trimPressureRef: {
1009
+ droppedMessages: boolean;
1010
+ };
1011
+ /** design/374 slices 1b/2/3 — the microCompact machine state this run: the selected clearing
1012
+ * machine, the cleared-projection ledger (request-view application, durable decisions — see
1013
+ * `context-edit.ts`'s ledger note; per-run in-memory, so durable resume / `resumeAt` rebuilds
1014
+ * start EMPTY by construction), the last request's projection seat (what the provider actually
1015
+ * saw — the MC-R rejection arm computes its candidates and savings on THIS view, never on the
1016
+ * raw session rebuild), the MC-R knob, and the slice-3 arm-B seat. The explicit opt-out
1017
+ * (`machine: "legacy"` + MC-R off) ⇒ the ledger never gains an entry and every replay is a
1018
+ * same-reference no-op (opt-out bytes unchanged). */
1019
+ microCompact: PreparedMicroCompact;
1020
+ }
1021
+ /** See {@link Prepared.microCompact}. */
1022
+ export interface PreparedMicroCompact {
1023
+ /** The frontier-machine selection — `"off"` = no proactive frontier clearing (the unified
1024
+ * machine instead gets its one blocking-point shot, slice-3 arm A). */
1025
+ machine: "off" | ContextEditMachine;
1026
+ /** MC-R (design/374 §3.2): one-shot clear-and-retry on a provider input-too-long rejection.
1027
+ * Default true since the slice-3 flip. */
1028
+ clearOnRejection: boolean;
1029
+ /** design/374 slice 3 (arm B) — the in-turn forced-compaction seat: runtask wires a closure
1030
+ * that runs the SAME forced-compaction pass the prompt-too-long recovery uses (gates included)
1031
+ * and answers whether a compaction landed in the session. The context hook calls it when the
1032
+ * pre-send estimate breaks the guard budget and then returns `adoptSessionRebuild` so the
1033
+ * harness adopts the reduced transcript. `signal` is the TURN-scoped abort of the request
1034
+ * build (r3): a turn interrupt must be able to cut the summary call short instead of waiting
1035
+ * it out. `anchoredEstimate` is the chain's own trigger coordinate — the seat consults the
1036
+ * §25.2 anti-thrash floor against it (an ineffective landing must not be repeated per request
1037
+ * build; the chain's arm C owns the bounded fallback). Unwired (pure-prepare callers) ⇒ arm B
1038
+ * declines and the chain falls to the trim last resort — same posture as a compaction-disabled
1039
+ * run. */
1040
+ inTurnCompactionRef: {
1041
+ current?: (signal?: AbortSignal, anchoredEstimate?: number) => Promise<boolean>;
1042
+ };
1043
+ ledger: ClearedProjectionLedger;
1044
+ projectionRef: {
1045
+ current?: {
1046
+ /** The FINAL projected view of the last provider request (post trim/sweep). */
1047
+ messages: AgentMessage[];
1048
+ /** Occurrence coordinates of that view (object-identity first, unambiguous-group fallback). */
1049
+ keyOf: OccurrenceIndex["keyOf"];
1050
+ };
1051
+ };
1052
+ /** The same offload persist seat the frontier machine uses (write-once, idempotent), so MC-R
1053
+ * clears compose identical markers. Absent when no offload store is configured. */
1054
+ offloadPersist?: (toolCallId: string, fullText: string) => string;
1055
+ }
1056
+ /**
1057
+ * design/45 resume inputs threaded into {@link prepareTask} to continue a suspended task. The Runner
1058
+ * builds it from the persisted {@link Checkpoint}: rewind the branch to the suspension leaf, skip the
1059
+ * suspended batch during wake-reconcile, and re-seed the §4.bis per-task correctness state so the
1060
+ * resumed run is in the **same state space** it suspended in.
1061
+ */
1062
+ export interface PrepareResume {
1063
+ /** The session leaf to rewind to (the suspension point) BEFORE reconcile — discards the abort's
1064
+ * off-branch "Operation aborted" writes so the resume engine resolves the pending batch cleanly. */
1065
+ leafId: string;
1066
+ /** Batch tool-call ids of the suspended turn — wake-reconcile SKIPS these (they are resumed, not
1067
+ * crash-interrupted; closing them with `[INTERRUPTED]` would DESTROY the suspended batch, §15.2 #7). */
1068
+ suspendedBatch: ReadonlySet<string>;
1069
+ /** The §4.bis correctness-state snapshot to re-seed (activeTools / outputRef / nestedStats /
1070
+ * consolidationNotes / readFileState). */
1071
+ seed: CheckpointState;
1072
+ /** design/72 §2.2 (B): how many times this task already suspended (the resumed checkpoint's
1073
+ * `suspendCount`). The next suspend mints `priorSuspendCount + 1`; past `maxSuspends` it fails
1074
+ * (`suspend.loop`) instead of re-suspending. Absent/0 ⇒ no prior suspends. */
1075
+ priorSuspendCount?: number;
1076
+ /** design/74 Slice 4: the cross-slice {@link ResourceLedger} carried by the resumed `resource_limit`
1077
+ * checkpoint (cumulative spend + the frozen human totals). The next slice's effective budget is
1078
+ * `min(maxCostUsd, totalBudget − spent)`, and its own suspend debits onto this. Absent ⇒ the first slice. */
1079
+ priorLedger?: ResourceLedger;
1080
+ /** design/91: the accumulated human-review burden carried by the resumed checkpoint
1081
+ * ({@link import("../checkpoint-store.js").Checkpoint.humanReview}) — the gates resolved up to and including
1082
+ * the suspend BEFORE this one. Seeds the per-task accumulator so the resumed leg ADDS this suspend's own
1083
+ * latency (`now() − cp.suspendedAt`) on top, reporting the WHOLE chain's burden. Absent ⇒ no prior human time. */
1084
+ priorHumanReview?: {
1085
+ count: number;
1086
+ totalWaitMs: number;
1087
+ gates: Array<{
1088
+ kind: string;
1089
+ waitMs: number;
1090
+ decision?: string;
1091
+ toolName?: string;
1092
+ toolArg?: string;
1093
+ }>;
1094
+ };
1095
+ /** design/49 v1.5: when the suspend ran with a remote workspace, the {@link CheckpointState.workspaceHandle}
1096
+ * to restore — prepare rebuilds the per-task env via `deps.executionEnvFactory` then `resumeVM(snapshotId)`
1097
+ * + `postResumeInit()` (instead of running on a fresh, empty env). Threaded HERE (not via `ResumeTaskConfig`)
1098
+ * so the factory stays a deployment-level `RunnerDeps` capability and never pollutes `TaskSpec` — preserving
1099
+ * the "untrusted caller can't inject an env" red line ({@link import("../remote-env.js").ExecutionEnvFactory}'s
1100
+ * own contract states it: "Lives on `RunnerDeps` (deployment-level) — NOT on `TaskSpec`"; code-ready council round-2). */
1101
+ workspaceHandle?: import("../remote-env.js").WorkspaceHandle;
1102
+ /**
1103
+ * design/174 — the call id of the CONTENT ask whose answer an operator's approval was spent on, when
1104
+ * that is what this leg redeems. Scoped as an id, not a leg-wide flag: an `unavailable` outcome on
1105
+ * THAT call must become a coded failure (the approval bought a question nobody answered), while a NEW
1106
+ * question raised later on the same leg had no approval spent on it and keeps the ordinary
1107
+ * continuation. Absent when the resumed pending action is not a question.
1108
+ */
1109
+ redeemedContentAskCallId?: string;
1110
+ /** Digest of that question's batch — the id alone can repeat, so the pairing is what keeps a LATER
1111
+ * question from inheriting the claim that an operator approved it. */
1112
+ redeemedContentAskQuestionsHash?: string;
1113
+ /** true iff this resume will EXECUTE an approved pending tool (`tool_approval`
1114
+ * checkpoint × an `allow` winner). The divergent-restore fail-closed guard keys on THIS, not on the
1115
+ * batch being non-empty: a deny winner executes nothing, so a workspace-root divergence must not
1116
+ * wedge the refusal (it proceeds under the path-state rebase and records the deny). */
1117
+ executesApprovedAction?: boolean;
1118
+ }
1119
+ /**
1120
+ * Parent effective-policy inheritance (tighten-only, {@link RunInternals.inheritedGate}): the spawning
1121
+ * chain's already-evaluated FINAL gate, split into two halves —
1122
+ *
1123
+ * - **Data half** (`ancestorRules`, `shellGate`): serializable snapshots. Each ancestor's per-session
1124
+ * permission rules ride as (sessionId, principal, rev, rules) so the child's prepare can re-read them
1125
+ * LIVE (rev-monotonic — a lagging replica never loosens the snapshot) and re-compile them against the
1126
+ * CHILD's own env/root/effects as extra deny-narrowing layers. `shellGate` folds by max-rank
1127
+ * (off < classify < always): a child can only tighten the parent's shell doctrine, never relax it.
1128
+ * - **Opaque half** (`parentConstraints`): each ancestor's live caller `ToolPolicy` plus its FROZEN
1129
+ * `onAsk`, ancestors first — and, for a hook-wired ancestor, a SECOND entry: its PreToolUse screening
1130
+ * face folded into a `ToolPolicy` (`createPreToolUseConstraintPolicy`), carrying its own frozen
1131
+ * approver/mandate/env axes (the `preToolUse`/`hookEnv` fields below). Folded AFTER the child's own caller policy and BEFORE the trailing
1132
+ * deny-narrowing re-check, each wrapper resolving its own `ask` via the ancestor's frozen approver —
1133
+ * so a parent `ask` never widens into a child auto-allow, and a parent `allow{updatedInput}` rewrite
1134
+ * is still re-checked by the child's narrowing layers. NOT serializable: a durable resume must
1135
+ * re-supply it via `resumeStream(..., internals)` (see {@link CheckpointState.inheritedGate}).
1136
+ *
1137
+ * Chain assembly is single-sited in prepareTask's ctx injection (`inheritedGateForChildren`): upstream
1138
+ * chain + THIS task's own contribution (its session-rule snapshot, its RESOLVED caller policy —
1139
+ * `spec.toolPolicy ?? deps.toolPolicy`, the same slot its own gate enforces — + frozen onAsk, its
1140
+ * effective shellGate, and — when this task resolved a PreToolUse hook — a screening entry for that
1141
+ * hook, deduped by full installation so a deps-level hook is consulted once per call at any depth).
1142
+ * Depth-N delegation is therefore a linear chain, each layer evaluated at most once per tool call.
1143
+ */
1144
+ export interface InheritedGate {
1145
+ /** Serializable ancestor session-rule snapshots (data half), ancestors first. */
1146
+ ancestorRules?: ReadonlyArray<{
1147
+ sessionId: string;
1148
+ principal?: string;
1149
+ rev: number;
1150
+ rules: SessionPermissionRules;
1151
+ }>;
1152
+ /** The chain's effective shell-gate doctrine — the child folds it by max-rank with its own spec. */
1153
+ shellGate?: "off" | "always" | "classify";
1154
+ /**
1155
+ * The chain's AUTO-MODE INTENT (`TaskSpec.autoModeRequested`, session-wide like a permission mode):
1156
+ * emitted when the spawning task carried the intent itself or inherited it, so an engine-spawned
1157
+ * child of an auto-mode task arms its OWN per-run classifier exactly as its parent did — the
1158
+ * intent half only; the child's deny bit (`RuntimeCaps.autoMode === false`) and deployment face
1159
+ * (`RunnerDeps.autoMode`) are evaluated for the child. Trusted chain data (Runner-assembled, never a
1160
+ * model-authored argument); absent ⇒ the child is an auto-mode task only if its own spec says so.
1161
+ * Persists on the checkpoint's data half (`CheckpointState.inheritedGate.autoModeRequested`) so a
1162
+ * redemption in another process — no seat re-passed, no waking chain — reads the same intent the
1163
+ * suspend leg had; the intent folds by OR across seat, live chain and seed, while the deny bit and
1164
+ * the deployment face stay per-leg.
1165
+ */
1166
+ autoModeRequested?: true;
1167
+ /**
1168
+ * Org-memory admission freeze (ruled 2026-08-05): the spawning chain's FROZEN admitted org-scope
1169
+ * set — every org memory scope the parent actually mounted (deployment-origin + admitted request).
1170
+ * A delegated child's REQUEST-origin org scopes must be a subset (intersection ≠ request ⇒ the
1171
+ * child's prepare refuses, `memory.admission_denied`); deployment-origin scopes circumvent the freeze
1172
+ * (operator authority is deployment-wide). ALWAYS emitted by chain assembly (empty array = parent
1173
+ * mounted no org plane), so an ABSENT field discriminates an older-shape chain — which the child
1174
+ * side reads fail-closed as the empty set. Serializable (plain strings): persists on the
1175
+ * checkpoint's data half and folds seed ∩ live on resume (tighten-only).
1176
+ */
1177
+ admittedOrgScopes?: readonly string[];
1178
+ /**
1179
+ * The MONOTONIC org-governance provenance bit (falsification-style round 5): `true` when any leg of this
1180
+ * tree ran with an org-admission surface configured (resolver / deployment scope list) or
1181
+ * inherited the bit. It never clears once set (a governed tree stays governed), and it counts as
1182
+ * governance evidence at the admission door EVEN when every admitted set en route is empty — a
1183
+ * governed parent's org-less child, resumed on a surface-less worker, must still refuse
1184
+ * org-shaped non-v2 scopes instead of mounting them as opaque keys. Absent on trees that never
1185
+ * had a governance surface (their opaque posture is untouched). Serializable; persists on checkpoints.
1186
+ */
1187
+ orgAdmissionGoverned?: true;
1188
+ /** Live ancestor caller-policy constraints (opaque half), ancestors first. `policy` is the ancestor's
1189
+ * RESOLVED caller policy (`spec.toolPolicy ?? deps.toolPolicy` — the same slot the ancestor itself
1190
+ * enforces, so a deps-level baseline is inherited too).
1191
+ *
1192
+ * ⚖️ A-005.13 (ruled with the F-012 family, 2026-08-09): the ancestor's per-run BUDGET LEDGER does
1193
+ * NOT travel this chain — by design, not by omission. An inherited policy's `check` receives the
1194
+ * CHILD run's own `ToolCallRequest.budget` snapshot (the child's durable resource ledger), so a
1195
+ * SELF-LIMITING ancestor policy ("allow N escalations, then ask") sees a fresh ledger in each
1196
+ * delegated child rather than a continuation of the ancestor's counts. Freezing/snapshotting the
1197
+ * ancestor ledger was considered and rejected: a frozen ledger goes stale the moment the ancestor
1198
+ * keeps running (a stale ledger is a NEW wrongness surface, not a fix), and the durable resource
1199
+ * ledger's identity is per-run by contract. A deployment wanting cross-delegation budget coherence
1200
+ * carries it in its own policy state (the closure travels the chain intact — a closure-counter
1201
+ * policy DOES aggregate across the tree, since every layer evaluates the same instance).
1202
+ *
1203
+ * `onAsk` is the ancestor's frozen
1204
+ * `spec.onAsk ?? deps.onAsk` — an ancestor `ask` resolves at that ancestor's own approver
1205
+ * (headless ⇒ deny), never at the child's. `durableMandate` is frozen at chain-assembly time when the
1206
+ * ancestor ran under a durable-approval regime that would actually PARK its own plain asks — a
1207
+ * `forceDurableGate` entitlement, or `durableApproval` with NO live onAsk frozen (with a live approver
1208
+ * the ancestor's own plain asks resolve synchronously there, so a descendant's ask resolves at that
1209
+ * same frozen `onAsk` — no mandate). It is a CONSERVATIVE descendant-side mandate: whether or not a given ask would actually
1210
+ * have parked at the ancestor (the regime may be scoped), the durable-park semantics cannot be
1211
+ * reconstructed in a delegated child's context — so a wrapper seeing `ask` under this flag denies
1212
+ * fail-closed (tighten-only holds) instead of resolving synchronously. */
1213
+ parentConstraints?: ReadonlyArray<{
1214
+ policy: ToolPolicy;
1215
+ onAsk?: OnAsk;
1216
+ durableMandate?: boolean;
1217
+ /** The CONTENT-ask twin of `durableMandate`, frozen from the QUESTION seat (`spec.onQuestion ??
1218
+ * deps.onQuestion`) on the same rule: a `forceDurableGate` entitlement, or `durableApproval` with no
1219
+ * LIVE question face frozen (absent, or the reserved resume placeholder — neither can answer). A
1220
+ * wrapper seeing an `ask` on the question tool consults THIS bit, never the permission one: the two
1221
+ * asks are answered by two different faces, and a run with a live `onQuestion` and no permission
1222
+ * approver can answer a delegated question perfectly well. When it IS set the delegated question is
1223
+ * marked unresolvable and takes the child gate's park / honest-refusal leg, exactly as an inherited
1224
+ * permission ask does under `durableMandate`. */
1225
+ contentMandate?: boolean;
1226
+ /**
1227
+ * F-012 (#106) — the ancestor's FROZEN auto-mode classifier: the same decider instance the
1228
+ * ancestor's own gate consults for a surviving ask (`ToolGateInput.autoMode`). Without it the
1229
+ * ancestor's ask DECISION CHAIN did not travel — the wrappers resolved an inherited ask straight
1230
+ * at the frozen approver, so an ask the ancestor's classifier would have BLOCKED executed in the
1231
+ * child on the frozen approver's allow. The wrapper runs it BEFORE the frozen approver, in the
1232
+ * ancestor's own gate order (classifier → approver): `block` ⇒ deny (`decisionReason:"classifier"`),
1233
+ * `allow` ⇒ the classifier's auto-allow (the frozen approver is not consulted), anything else
1234
+ * falls through to the approver chain. Never consulted for the reserved question tool nor under a
1235
+ * durable mandate (a marked call must reach the park with no synchronous decision-maker between).
1236
+ */
1237
+ autoMode?: {
1238
+ decider: AutoModeDecider;
1239
+ /**
1240
+ * #548 — the ancestor's per-run DENIAL-LIMIT tracker, frozen beside its decider (same owner). The
1241
+ * wrapper arms count the frozen classifier's blocks on it and, at a bound, resolve the fallback
1242
+ * ask at the frozen approver instead of denying (`requiresRealApproval` set, sandbox admission
1243
+ * excluded). Live-only, like the decider: a cross-process redemption starts a fresh count.
1244
+ */
1245
+ denialTracking?: AutoModeDenialTracker;
1246
+ /**
1247
+ * #503 — the SERIALIZABLE criteria half of this classifier (assembly inputs + knobs + the
1248
+ * deployment's settings epoch), present when the arming deployment opted in
1249
+ * (`RunnerDeps.autoMode.persistArming`). A durable park records it on the chain entry so a
1250
+ * CROSS-PROCESS redemption can rebuild an equivalent decider over its own model leg instead of
1251
+ * answering `unavailable` forever; the constraint-chain digest binds it, so a resume re-supplies
1252
+ * exactly what the row carries. It never affects THIS process's decisions — the live `decider` is
1253
+ * the one every gate consults, here and on every descendant.
1254
+ */
1255
+ arming?: AutoModeArmingRecipe;
1256
+ };
1257
+ /**
1258
+ * Set ONLY on an entry whose `policy` is the folded form of an ancestor's PreToolUse screening face
1259
+ * (issue #33 — the face used to stop at the task that installed it, so a call the ancestor had
1260
+ * refused executed one level down). It carries the raw callback for ONE purpose: identity. A
1261
+ * deployment-level face (`RunnerDeps.hooks`) is resolved by every task in the tree on its own, so
1262
+ * each descendant's gate already runs it in phase 1 — folding it AGAIN as an inherited constraint
1263
+ * would consult the same callback twice per call at depth 1 and once more per level below. Two
1264
+ * identity tests keep that at exactly one consultation per call: chain assembly does not re-append a
1265
+ * face already on the chain, and a descendant substitutes a pass-through for the entry naming the
1266
+ * very callback its own gate will run. A per-task face (`TaskSpec.hooks`) is a different function in
1267
+ * the descendant (or absent), so it folds and travels.
1268
+ *
1269
+ * Identity is the only sound test here, and it is deliberately the CONSERVATIVE one: an assembly that
1270
+ * hands each task a freshly bound wrapper over one underlying callback (the `runSpec` mux does this)
1271
+ * produces two distinct function objects, so the descendant both folds the ancestor's entry and runs
1272
+ * its own — the callback is consulted twice rather than skipped. Erring toward a second screening,
1273
+ * never toward a missed one, is what makes an identity miss a cost rather than a hole.
1274
+ */
1275
+ preToolUse?: Hooks["preToolUse"];
1276
+ /**
1277
+ * The environment this screening face was installed against — the source of the `HookEnvCapabilities`
1278
+ * handed to it, compared BY REFERENCE, `undefined` when the installation had no env face. Part of the
1279
+ * installation's identity for the same reason the frozen approver is (HIGH): a face that
1280
+ * resolves paths through `ctx.env` answers a different question in a different environment, so an
1281
+ * ancestor running against the deployment's tree and a descendant running in an isolated worktree are
1282
+ * two screenings, not one. A deployment with a per-task `executionEnvFactory` therefore has its face
1283
+ * consulted once per environment on the chain rather than once overall — which is the point: the
1284
+ * ancestor's environment is the only place the ancestor's verdict can be reproduced.
1285
+ *
1286
+ * ⚠️ RECORDED BOUNDARY (delegation provenance): the approver half of the key compares
1287
+ * through {@link askApproverIdentity}, which by its own contract answers "the same decision-maker",
1288
+ * collapsing a `withDelegationProvenance` wrapper onto the approver it forwards to. Two installations
1289
+ * whose approvers differ ONLY in the provenance they attach therefore count as one. Raw reference
1290
+ * equality is not an available alternative: a delegated child's approver is ALWAYS a fresh wrapper
1291
+ * over its parent's, so raw equality would collapse nothing and a deployment-level face would be
1292
+ * consulted once per ancestor level on every leaf call. The exposure is bounded on the side that
1293
+ * matters — the pass-through arm hands the frame to the DESCENDANT's own gate, whose approver carries
1294
+ * the descendant's own provenance (strictly more context, never less). What a chain-assembly collapse
1295
+ * can drop is one intermediate installation's provenance on an ask: an approver that DECIDES on
1296
+ * `req.delegation` would see the surviving installation's rather than both.
1297
+ */
1298
+ hookEnv?: unknown;
1299
+ }>;
1300
+ }
1301
+ /**
1302
+ * design/78 Slice-1 (MAJOR-3 wiring): a TRUSTED, run-scoped internal channel into {@link prepareTask}, set
1303
+ * ONLY by a trusted CORE caller (`runRepairLoop` via the Runner's internal `runTaskStream` arg) — NEVER from
1304
+ * a {@link TaskSpec} field (the untrusted-caller surface, design/44 §7 Q4). It is the live-state counterpart
1305
+ * of {@link PrepareResume.seed}: where `resume.seed` re-seeds correctness state RESTORED from a checkpoint,
1306
+ * this carries the LIVE per-task state the Runner cannot otherwise see (it lives in the caller's closure).
1307
+ *
1308
+ * Originally it carried only the repair loop's live {@link RepairBundle}: `runRepairLoop` is a thin composition
1309
+ * OVER `runner.runTask`, so when an orthogonal durable suspend (resource/HITL) interleaves a repair attempt,
1310
+ * the bundle (failureTrace/diagnostics/attemptCount/oracleTier) sits in the loop's closure and was being lost
1311
+ * — the minted checkpoint serialized `repairBundle: undefined`. Threading it here lets
1312
+ * {@link prepareTask}'s `serializeCheckpointState` source the LIVE bundle so a resume re-seeds `attemptCount`
1313
+ * MONOTONICALLY (design/76 §2.2#1 r4 MAJOR-A). Mirrors how `nestedStats`/`resume.seed` thread trusted
1314
+ * run-scoped internals through the Runner without touching `TaskSpec`.
1315
+ *
1316
+ * @contract prepare.deps-read-stable — the `RunnerDeps`, `RunInternals` and `ExecutionEnv` handles a host
1317
+ * passes into {@link prepareTask} are READ-STABLE for the duration of the call: prepare reads them at the
1318
+ * points its phases need them, and a host that mutates them between microtasks while prepare is in flight
1319
+ * is outside the contract (the Runner is constructed over its deps; a mid-prepare rewrite is a race the host
1320
+ * made). Phase boundaries are scheduling points — an `await` on a phase that carries its own awaits adds a
1321
+ * microtask between that phase's last continuation and the driver's next read — and such a host can observe
1322
+ * them; the engine does not defend against it. The untrusted surface is {@link TaskSpec}, whose pre-first-
1323
+ * await latch is a separate, pinned guarantee (prepare-task-phase-pins T1).
1324
+ */
1325
+ /** The runtime feature flags the stable prompt's harness-context block gates its sections on
1326
+ * (design/64 §6.3: claim only what the task has). Spread into the assembly's StablePromptContext
1327
+ * by the prompt-assembly phase, which re-derives the two orchestration flags against the post-exclusion roster. */
1328
+ export interface PromptFeatureFlags {
1329
+ policyEnabled: boolean;
1330
+ hooksEnabled: boolean;
1331
+ isolationEnabled: boolean;
1332
+ reminderMark: string;
1333
+ readFaceOpen: boolean;
1334
+ orchestrationEnabled: boolean;
1335
+ orchestrationDeferred: boolean;
1336
+ promptProfile: "simple" | "classic";
1337
+ fableMitigations: boolean;
1338
+ goalEnabled: boolean;
1339
+ awarenessEnabled: boolean;
1340
+ worktreeIsolated: boolean;
1341
+ withinTaskCompactionEnabled: boolean;
1342
+ isSubagent: boolean;
1343
+ }
1344
+ export interface RunInternals {
1345
+ /** The live repair bundle from a `runRepairLoop` attempt in flight (attemptCount>0). Serialized onto a
1346
+ * checkpoint minted MID-attempt so a resume re-seeds it; undefined for any non-repair run. */
1347
+ repairBundle?: RepairBundle;
1348
+ /**
1349
+ * design/173 §8.2 — the ENGINE deliberately stripped the spawn turn's per-request `onQuestion`
1350
+ * face from this leg's spec (a long-lived background/retained/revived child must not hold a
1351
+ * callback torn down with the turn that spawned it). Minted ONLY by the subagent lanes'
1352
+ * `stripSpawnTurnQuestionFace` helper, PAIR-PRODUCED with the strip itself — never inferred from
1353
+ * spec shape. Consumed by the wiring manifest (`question.wired: "stripped_bg_lane"`) and by the
1354
+ * interaction-posture door (the strip is core's correct design, not a configuration lie, so an
1355
+ * `"interactive"` tree's engine-stripped legs are exempt). TRUST POSTURE (ruled 2026-08-05):
1356
+ * RunInternals is a public trusted-caller parameter, so this flag is an honesty channel, not a
1357
+ * security gate — a caller forging it is a deployment lying to itself; resource-face safety
1358
+ * stays with its own fail-closed mechanisms.
1359
+ */
1360
+ questionFaceStripped?: true;
1361
+ /**
1362
+ * design/173 §8.3 (review fold r2-F1) — the SPAWNING run's resolved interaction posture, carried
1363
+ * into engine-built children over the trusted internals channel (never copied onto the child
1364
+ * SPEC — the §8.3 rule). The child's door resolves `spec ?? THIS ?? deps`, so a root's per-run
1365
+ * posture override governs its whole engine-built tree instead of every child falling back to
1366
+ * the deps-level default. Filled by the delegation lanes' `childInternals` and the workflow
1367
+ * spawn attribution; rides `internalsSnapshot`, so retained/revived legs keep it.
1368
+ */
1369
+ parentInteractionPosture?: "interactive" | "headless";
1370
+ /**
1371
+ * design/153 §7.2c (件3c, r6 H-1) — the trusted post-consume hook for the PARKED-RESUME drive:
1372
+ * called by `resumeStream` after its resolve CAS WON (the token is consumed — the master
1373
+ * arbitration is decided) and BEFORE the resumed leg starts. The parked-resume caller uses it to
1374
+ * flip the reserved row `parked→running` (guarded CAS) + adopt the live handle/lane — the ONLY
1375
+ * legal site for that flip (a pre-consume flip would let TaskStop hit the plain running arm and
1376
+ * circumvent the checkpoint arbitration entirely). A THROW here aborts the resume (propagates out of
1377
+ * `resumeStream`): the checkpoint is already consumed, so the caller's compensation
1378
+ * (`rollbackParkedClaim`) reads `resolved` and settles the honest failed/outcome-unknown terminal
1379
+ * — never a silent run without an adopted row. Deployment/trusted-caller channel only, mirroring
1380
+ * every other RunInternals field.
1381
+ */
1382
+ afterCheckpointResolve?: () => Promise<void>;
1383
+ /**
1384
+ * Parent effective-policy inheritance (tighten-only): the spawning parent's already-evaluated FINAL
1385
+ * gate, threaded into a child task so the child inherits it as ADDITIONAL constraint layers — a child
1386
+ * can only ever be narrowed by this, never widened (its own session rules / skill scope / caller policy
1387
+ * still apply in full). Filled ONLY by core delegation callers (`createSubagentTool`'s execute via
1388
+ * `ToolExecuteContext.inheritedGateForChildren`, the workflow spawn legs) — NEVER a {@link TaskSpec}
1389
+ * field (the untrusted-caller surface), mirroring `inheritedManifestScope`'s ctx-injection posture.
1390
+ * Absent ⇒ no inheritance (a top-level task; fully backward-compatible).
1391
+ */
1392
+ inheritedGate?: InheritedGate;
1393
+ /**
1394
+ * design/180 half A — the delegation RUNTIME-PROVENANCE channel. Minted by the spawning delegation
1395
+ * tool when the parent chain is armed (the parent mounts a memory session, or is itself recording
1396
+ * for ITS parent): `ref` is the child's monotonic aggregate — the child's recorder writes into it
1397
+ * as the run progresses (live faces read the current bits; the terminal attestation reduces from
1398
+ * it); `contentSafety` is the chain's FROZEN classification snapshot — the child may narrow it
1399
+ * with its own config, never widen (design/180 A-2). Trusted internals chain only, same posture as
1400
+ * {@link inheritedGate}. Absent ⇒ the child records nothing (its deliveries then read `unknown`,
1401
+ * and every judgment falls back to the static floor — fail-closed by construction; whether the
1402
+ * floor's verdict MARKS the judging session follows that run's deployment evidence standard,
1403
+ * {@link RunnerDeps.memoryDelegationEvidence}).
1404
+ */
1405
+ delegationProvenance?: {
1406
+ ref: {
1407
+ current: import("../memory-engine/delegation-provenance.js").DelegationProvenanceAggregate;
1408
+ };
1409
+ contentSafety: import("../memory-engine/delegation-provenance.js").DelegationContentSafety;
1410
+ };
1411
+ /**
1412
+ * #22 (ruled 2026-08-05) — the SESSION-scoped org-admission freeze for a SAME-SESSION continuation
1413
+ * that is NOT a checkpoint resume: a retained background child revived through the in-process resume
1414
+ * leg. The checkpoint plane already freezes the session's own verdict
1415
+ * ({@link InheritedGate.ownAdmittedOrgScopes}); this leg has no checkpoint, so without a carrier it
1416
+ * re-adjudicated from scratch and a resolver whose answer WIDENED between the two legs remounted a
1417
+ * tenant layer the session had already lost.
1418
+ *
1419
+ * A REF, not a value: the revival replays a spread COPY of the spawn-time internals, so a plain field
1420
+ * could only ever carry the value that existed at spawn (always `undefined`). The prepare reads
1421
+ * `current` as its `priorOwnVerdict` — intersected with any checkpoint seed, so the fold can only ever
1422
+ * narrow — and writes this leg's own verdict back, which is ⊆ the prior one by construction.
1423
+ *
1424
+ * TRUSTED internal, filled by `createSubagentTool`'s `childInternals` (one ref per spawned child, never
1425
+ * shared across generations — a child's own children build their own). Absent ⇒ no session freeze from
1426
+ * this channel, byte-identical to a deployment with no governance surface.
1427
+ */
1428
+ ownOrgAdmissionRef?: {
1429
+ current: import("../memory-admission.js").OwnOrgAdmissionVerdict | undefined;
1430
+ };
1431
+ /**
1432
+ * design/176 — this run's LATE-BOUND peer-identity carrier (a REF, same family and reason as
1433
+ * {@link ownOrgAdmissionRef}: revival replays a spread copy of spawn-time internals, and the axes
1434
+ * a run wears are born at different points — a* handle at registration, session/task at prepare's
1435
+ * session acquisition). Created at internals assembly (delegation lanes; runtask normalizes one
1436
+ * in for a top-level run); axes recorded through the single monotonic `addAxis`; the canonical
1437
+ * key freezes at the first recorded axis (h→s→t by call-site ordering). Read by the SendMessage
1438
+ * mount (sender key + hop token) and paired into children as {@link parentPeerRef}.
1439
+ */
1440
+ peerSelfRef?: import("../../agents/peer-admission.js").PeerSelfRef;
1441
+ /**
1442
+ * design/176 — this run's INBOUND peer-chain ref: overwritten at the harness consumption boundary
1443
+ * with the chain of the peer message the model just consumed (enqueue-time writes would leak a
1444
+ * not-yet-seen message's chain into outbound sends); seeded by the L3/L4 wake legs; empty
1445
+ * otherwise. Not checkpointed in v1 (recorded honest boundary: a cross-process resume forwards
1446
+ * from an empty chain — fail-open on loop suppression only).
1447
+ */
1448
+ peerInboundChainRef?: import("../../agents/peer-admission.js").PeerInboundChainRef;
1449
+ /**
1450
+ * design/176 — the PARENT run's peer-identity ref, PAIR-MINTED with {@link parentNotify} at every
1451
+ * trust point that binds the uplink callback (spawn assembly, the resume face's replacement): the
1452
+ * callback is opaque and the parent AXES deliberately keep the original spawner on the revive arm
1453
+ * while the callback points at the WAKER — so the uplink's admission identity can only travel
1454
+ * with the binding itself. Consumed by the SendMessage mount as `uplinkRecipient`.
1455
+ */
1456
+ parentPeerRef?: import("../../agents/peer-admission.js").PeerSelfRef;
1457
+ /**
1458
+ * 🔴 design/97 §H.1 / design/98 §0.1 (BLOCKER3) — the workflow **nesting depth** for this run, a TRUSTED
1459
+ * cross-process channel (worker/script can NEVER set it — it is not a {@link TaskSpec} field nor a
1460
+ * `run_workflow` tool param). When a deployment initiates a workflow on behalf of a parent run that is
1461
+ * itself inside a workflow (e.g. service's `/v1/workflows`), it threads `workflowDepth = parentDepth + 1`
1462
+ * into `startWorkflow`/`runWorkflow` so the one-level nesting guard fires across the process boundary.
1463
+ * In-process nesting needs nothing here — the engine's `AsyncLocalStorage` propagates depth automatically.
1464
+ * Mirrors how `repairBundle`/`inheritedManifestScope` thread trusted run-scoped internals the Runner cannot
1465
+ * see from `spec`. Consumed by the `run_workflow` tool wiring (S8c), not by `prepareTask` itself.
1466
+ */
1467
+ workflowDepth?: number;
1468
+ /**
1469
+ * design/110 — set ONLY by the Agent tool's fork route (`Agent(subagent_type:"fork")`, a core caller) on the
1470
+ * child it spawns: this run IS a forked child. `prepareTask` threads it to tool ctx as `insideFork` so the
1471
+ * child's own Agent tool refuses a nested fork (nesting guard — mirrors CC's "fork is not available inside a
1472
+ * forked worker"; a fork can still delegate via `Agent`, just not fork again). TRUSTED internal (NOT a
1473
+ * `TaskSpec` field — the untrusted-caller surface), mirrors `inheritedManifestScope`.
1474
+ */
1475
+ insideFork?: boolean;
1476
+ /**
1477
+ * design/319 (A ticket) — the PARENT's reminder provenance mark, set ONLY by the Agent tool's
1478
+ * fork route on the child it spawns ("one declaration, one mark": a fork runs under the parent's
1479
+ * byte-identical system-prompt declaration, so its own engine mints must carry the PARENT's mark;
1480
+ * a spawn/clone context mints its own). Verified through the mint home's verify port at adoption
1481
+ * (`isValidReminderMark` — an unrecognized value re-mints, fail-safe); the forked SESSION's own
1482
+ * `reminder_mark` entry is the primary carrier (a store fork copies committed history), this
1483
+ * channel is the in-process belt over it. TRUSTED run-scoped channel (NOT a {@link TaskSpec}
1484
+ * field), mirroring `insideFork`.
1485
+ */
1486
+ reminderMark?: string;
1487
+ /**
1488
+ * RB-204 P1 — set UNCONDITIONALLY by every core spawn path (`createSubagentTool`'s
1489
+ * `childInternals` — shared by all four spawn legs sync/steer/background/fork, its persisted
1490
+ * `internalsSnapshot` for revive, and the workflow orchestrator's `spawnAttribution`), regardless
1491
+ * of whether a NAMEABLE `parentTaskId`/`parentToolCallId` exists. A directly-started workflow (no
1492
+ * launching tool call, e.g. cron-triggered) has neither of those — "no id is ever fabricated" for
1493
+ * attribution — but its spawned agents are still delegated children for consent-notice purposes.
1494
+ * Drives `isSubagent` below: do NOT use `parentTaskId` presence alone as the child-ness signal,
1495
+ * that under-covers exactly this case. TRUSTED run-scoped channel (NOT a {@link TaskSpec} field),
1496
+ * mirroring `insideFork`.
1497
+ */
1498
+ isDelegatedChild?: boolean;
1499
+ /**
1500
+ * Subagent transcript persistence — the child transcript session's PLACEMENT declaration, minted
1501
+ * by the background delegation lane (the trusted spawner: it knows the a* handle, scope and root)
1502
+ * and forwarded verbatim by this prepare's session acquire, so the session store CREATES the
1503
+ * child's transcript into its declared subagent partition (see {@link SessionStore.placements}).
1504
+ * Deliberately a TRUSTED internals seat and never a {@link TaskSpec} key: a public key would let
1505
+ * any caller push arbitrary sessions into the partition and poison store-side retention/
1506
+ * enumeration. Absent (sync children, forks, observers, every non-delegated run) ⇒ the acquire
1507
+ * carries no placement — byte-identical to before.
1508
+ */
1509
+ sessionPlacement?: import("../session.js").SessionPlacement;
1510
+ /**
1511
+ * G1+G2 合车复审修② (1.259.0) — the DEFAULT role-base persona for a DELEGATED child, threaded by
1512
+ * `createSubagentTool`'s execute (a core caller) when neither an agent-definition `systemPrompt` nor the
1513
+ * delegation tool's `opts.systemPrompt` names one. It sits at the BOTTOM of the role-base chain —
1514
+ * `spec.systemPrompt ?? resolvedRole.systemPrompt ?? internals.defaultSystemPrompt` — so a deployment's
1515
+ * `roles.subagent.systemPrompt` / `roles.default.systemPrompt` preset still wins (pre-G1 semantics: an
1516
+ * unset child systemPrompt let the role preset apply; G1's first cut put SUBAGENT_PROMPT at spec level
1517
+ * and silently shadowed the preset). Only when NO preset resolves does the lean SUBAGENT_PROMPT (CC 198
1518
+ * general-purpose persona, pretty.js:419977) replace the full DEFAULT_SYSTEM_PROMPT constitution base.
1519
+ * TRUSTED run-scoped channel (NOT a {@link TaskSpec} field), mirroring `insideFork`.
1520
+ */
1521
+ defaultSystemPrompt?: string;
1522
+ /**
1523
+ * design/96 §C (S2) — GOAL MODE flag, a TRUSTED internal channel set ONLY by `runGoal` (a core caller),
1524
+ * NEVER a {@link TaskSpec} field. It drives `featureFlags.goalEnabled` → injects `GOAL_COMPLETION_GUIDANCE`.
1525
+ * Why internal (not a public `TaskSpec.goalMode`): the guidance promises "declaring done STOPS iteration and
1526
+ * surfaces" — a promise only `runGoal`'s loop makes real. A public field would let a caller inject that
1527
+ * prompt with no loop behind it (§6.3 honesty violation). `runGoal` injects the `declare_done` tool itself;
1528
+ * this flag only governs the PROMPT (injection-ownership split).
1529
+ */
1530
+ goalMode?: boolean;
1531
+ /**
1532
+ * 🔴 design/77 §3 / §7 (ON-前必关) — skill→subagent manifest-scope PROPAGATION. The parent task's
1533
+ * ACTIVE skill-manifest frames, snapshotted at the moment a subagent was spawned WHILE a manifest scope
1534
+ * was live on the parent. The child's {@link prepareTask} seeds its own {@link ActiveSkillScope} from
1535
+ * these so the child inherits the parent skill's deny-narrowing — fail-closed and MONOTONIC: a child of
1536
+ * a manifested skill is AT MOST as capable as the manifest (its own manifests can only narrow further,
1537
+ * never re-grant a tool/path the parent removed).
1538
+ *
1539
+ * This is a TRUSTED, run-scoped channel filled ONLY by `createSubagentTool`'s `execute` (a core caller),
1540
+ * NEVER a {@link TaskSpec} field (TaskSpec is the untrusted-caller surface — design/44 §7 Q4). It mirrors
1541
+ * how `repairBundle`/`resume.seed` thread live per-task state the Runner cannot see from `spec`.
1542
+ *
1543
+ * Fail-closed: when the parent HAD an active manifest at spawn but the precise frames cannot be
1544
+ * snapshotted, the subagent tool threads a single DENY-ALL `unresolved` frame here rather than letting the
1545
+ * child run unmanifested — the safe path is the default. An empty/absent value = no inheritance (a
1546
+ * subagent spawned with no active parent manifest behaves exactly as before, backward-compatible).
1547
+ */
1548
+ inheritedManifestScope?: readonly ActiveSkillFrame[];
1549
+ /**
1550
+ * design/99 §E2 — when this task runs as a SUB-AGENT spawned under a parent task's
1551
+ * tool call, the spawning tool's `ToolExecuteContext.toolCallId`. The Runner stamps it onto this task's
1552
+ * stream content events as {@link TaskEvent.parentToolCallId} so a consumer can attribute the child's live
1553
+ * content to the delegation subtree WITHOUT core merging the child stream into the parent (lightweight
1554
+ * message-identity, not stream-merge). A TRUSTED, run-scoped channel filled by a core caller
1555
+ * (`createSubagentTool`'s `execute`) — NEVER a {@link TaskSpec} field (the untrusted-caller surface),
1556
+ * mirroring `inheritedManifestScope`/`workflowDepth`. Absent for a top-level (non-delegated) task.
1557
+ */
1558
+ parentToolCallId?: string;
1559
+ /**
1560
+ * design/99 MF-10 / BC-2 (Service AI [§I 1.5.1]) — a SUBAGENT's human display NAME, threaded at spawn so the
1561
+ * child's `task_progress` ticks carry a readable label (a Fleet child row otherwise shows the raw `taskId`).
1562
+ * Filled by `createSubagentTool`'s `execute` = the explicit `taskName`, else the selected agent-type
1563
+ * (`AgentDefinition.name`). TRUSTED run-scoped channel (NOT a {@link TaskSpec} field), mirroring
1564
+ * `parentToolCallId`. Absent for a top-level run / a bare delegation with neither label — the child's
1565
+ * `task_progress` then carries NO `name` (it keeps its taskId; it deliberately does NOT fall back to the raw
1566
+ * objective, which could leak a delegated secret — dual-review Q2). Untrusted (`taskName` is model-chosen) →
1567
+ * the consumer sanitizes via `inlineUntrusted` at emit.
1568
+ */
1569
+ agentName?: string;
1570
+ /**
1571
+ * design/147 S3 (label-vs-identity): the EXPLICIT `Agent({name})` spawn identity — set
1572
+ * ONLY when the spawn carried a `name` parameter, unlike {@link agentName} (a DISPLAY label:
1573
+ * description or agent-type, present on nearly every spawn). Teammate semantics (hierarchy clamp,
1574
+ * teammate addendum, uplink attribution) key on THIS field; keying on the display label made
1575
+ * every described child a "teammate" (clamp over-wide, addendum over-composed).
1576
+ */
1577
+ explicitAgentName?: string;
1578
+ /**
1579
+ * design/99 (nested-subagent live tree) — the SPAWNING run's taskId, threaded at spawn (from the parent's
1580
+ * `ToolExecuteContext.taskId`) so this child's `task_progress` ticks carry `parentTaskId`. Lets a UI build the
1581
+ * live nested-agent tree directly (child.parentTaskId === parent.taskId) at any depth. TRUSTED run-scoped
1582
+ * channel (NOT a {@link TaskSpec} field), mirroring `parentToolCallId`. Absent for a top-level run.
1583
+ */
1584
+ parentTaskId?: string;
1585
+ /** design/147 S2a — the spawning run's sessionId (paired with parentTaskId; see
1586
+ * ToolExecuteContext.parentSessionId). */
1587
+ parentSessionId?: string;
1588
+ /**
1589
+ * design/383 §2.5 — the memory-capture opt-out FLOOR: TRUE ⇔ the spawning session was under an
1590
+ * opt-out when this child spawned. The child then runs opted-out itself (its prepare mints its
1591
+ * own one-way record, reason naming the floor) — NOT re-adjudicated against the child's
1592
+ * entitlement (the floor is the parent's already-granted opt-out tightening the tree; a
1593
+ * re-adjudication that could answer "no" would be a loosening door). Trusted internals channel
1594
+ * on purpose (the parentInteractionPosture law): never a child-spec field, so no chosen
1595
+ * AgentDefinition and no spec surgery can shed it; rides `internalsSnapshot`, so retained
1596
+ * revivals keep it. Grandchildren inherit through each generation's own live seat (an opted-out
1597
+ * child forwards TRUE to its children in turn — monotone by construction).
1598
+ */
1599
+ memoryCaptureFloor?: true;
1600
+ /**
1601
+ * design/383 §2.5 (rescan post-6.0.0-RC) — the floor's THIRD state: the spawning session's
1602
+ * capture state was INDETERMINATE at spawn (its record store faulted at the getter read).
1603
+ * Neither boolean is honest there — no floor runs a possibly-recorded lineage captured, a coined
1604
+ * floor mints an IRREVERSIBLE record off an unreadable state — so the lane carries the fault
1605
+ * itself and the child's prepare resolves it against the live record query (found ⇒ floor;
1606
+ * still faulting ⇒ the child runs indeterminate — mechanical restrictions, no mint; readable
1607
+ * and clean ⇒ clean). Same trusted-channel law as {@link memoryCaptureFloor}; mutually
1608
+ * exclusive with it at the spawn site (the floor wins when the state IS known).
1609
+ */
1610
+ memoryCaptureFloorIndeterminate?: true;
1611
+ /** design/383 §2.5 — the spawning session's write-plane control dir (the coordinate its capture
1612
+ * opt-out record is keyed under), so a child on a DIFFERENT memory plane can still run the
1613
+ * record-query leg against the parent's own carrier. Trusted chain, rides internalsSnapshot. */
1614
+ memoryCaptureQueryDir?: string;
1615
+ /** design/383 §2.5 (codex round 3) — the ancestor chain's capture coordinates (root first, one
1616
+ * row per generation, appended by each spawner's ctx seat). The child's harvest closures walk
1617
+ * every row, so a mid-run flip ANYWHERE up the tree suppresses every in-flight descendant.
1618
+ * Trusted chain; rides internalsSnapshot. */
1619
+ memoryCaptureAncestors?: ReadonlyArray<{
1620
+ sessionId: string;
1621
+ controlDir?: string;
1622
+ }>;
1623
+ /**
1624
+ * The FLEET-task kind of this run, declared by the lane that spawned it and stamped onto every
1625
+ * `task_progress` tick the run mints (`TaskEvent`'s `taskType`). A consumer merging progress ticks
1626
+ * with task notifications into one ledger could otherwise only key on "it showed up on the fleet
1627
+ * stream, so it must be an agent" — an inference that has already produced a row for a task that
1628
+ * was never an agent. Same vocabulary as `TaskNotificationPayload.task_type`, so the merged ledger
1629
+ * has ONE type axis rather than two spellings of one.
1630
+ *
1631
+ * Set by the BACKGROUND delegation lanes (plain + fork), whose runs own a registry `a*` row, and by
1632
+ * both of the workflow orchestrator's spawn legs. A SYNCHRONOUS delegated child declares nothing —
1633
+ * it has no fleet row of any kind, so absence is a fact about the run rather than a gap in the
1634
+ * stamping. TRUSTED run-scoped channel (never a {@link TaskSpec} field).
1635
+ */
1636
+ delegationTaskType?: import("../types.js").DelegationTaskType;
1637
+ /**
1638
+ * #258 — the registry row's stop-cycle generation this run executes as (fresh spawn = 1, a
1639
+ * revival's bumped counter), threaded by the BACKGROUND delegation lanes from the registry's own
1640
+ * `cycleSeq` so every `task_progress` tick the run mints carries it as `seq` (same axis as
1641
+ * `TaskNotificationPayload.seq` / `BackgroundChildEvent.seq`). Absent for runs with no `a*` row
1642
+ * (sync children, workflow agents, top-level) — same absence-is-a-fact posture as
1643
+ * {@link delegationTaskType} above. TRUSTED run-scoped channel (never a TaskSpec field).
1644
+ */
1645
+ cycleSeq?: number;
1646
+ /** The ROOT host session of the whole delegation tree (fixed point: the
1647
+ * spawner passes its own `ctx.rootSessionId ?? ctx.sessionId`, so depth 1 gets the host session
1648
+ * and every deeper level inherits it verbatim). `parentSessionId` is the IMMEDIATE spawner —
1649
+ * after a restart those intermediate sessions are dead ends, and a recovery face enumerating
1650
+ * "everything under this host session" needs the root anchor, not an alias walk. */
1651
+ rootSessionId?: string;
1652
+ /**
1653
+ * design/380 O1② — the run tree's PLACEMENT root: the fixed point a target-bound env factory keys
1654
+ * its placement lookup on ({@link import("../remote-env.js").ExecutionEnvFactoryContext.placementRootSessionId}).
1655
+ * A SEPARATE axis from {@link rootSessionId} deliberately: that field means "member of this host
1656
+ * session's DELEGATION tree" and is consumed by the registry access/recovery faces — cascade rungs
1657
+ * and verification legs are intentionally NOT members of that tree (independent cold re-runs in
1658
+ * their own sessions), so widening `rootSessionId` to cover them would corrupt the recovery faces'
1659
+ * reading. This member says only "place me where this session was placed". Producers: the
1660
+ * orchestration entries (`runCascade` / `runWithVerification` family) after their first leg's
1661
+ * sessionId receipt, and — C12 — the delegation/workflow spawn chains, which re-thread a parent's
1662
+ * EXPLICIT value verbatim into child internals (ToolExecuteContext.placementRoot → childInternals;
1663
+ * workflow deps → shared internals base), so every descendant of a placed leg keeps the fixed
1664
+ * point; prepare's mint reads it first (`placementRoot ?? rootSessionId ?? sessionId`). Absent
1665
+ * everywhere else — the delegation lanes' `rootSessionId` fixed point then becomes the placement
1666
+ * root through the middle segment, unchanged. DURABLE since design/380 O1③ (the former C12
1667
+ * residual, fulfilled): the suspend mint stamps the resolved fixed point as
1668
+ * `CheckpointState.placementRootSessionId`, and a bare durable resume restores it into this
1669
+ * member (live internals win when re-supplied; a CONTRADICTING re-supply refuses pre-CAS,
1670
+ * `resume.placement_mismatch`). TRUSTED run-scoped channel (never a {@link TaskSpec} field).
1671
+ */
1672
+ placementRoot?: string;
1673
+ /**
1674
+ * RB-429 — the REGISTRY SCOPE this run's own background row lives in: the domain its registry-facing
1675
+ * tools (TaskOutput / TaskStop / SendMessage / AgentTranscript / Monitor, and the announce listing)
1676
+ * must mount in to see it. Filled by the delegation tool at spawn, which is the party that CHOSE the
1677
+ * domain when it registered the row — `ctx.principal` when the spawning run has one, else the
1678
+ * delegation mount's declared `background.scope`, and on a revival the claimed row's own scope.
1679
+ *
1680
+ * Why this is not just `principal`: a deployment may declare its domain at MOUNT time and run its
1681
+ * tasks without `TaskSpec.principal`. The row then lands in the declared domain while the child runs
1682
+ * with no principal at all, and `principal ?? "default"` sends every one of its registry-facing tools
1683
+ * to a domain the row is not in — scope is fail-closed on both access predicates, so such a child
1684
+ * cannot see its own row, its siblings, or the children it spawns. Carrying the domain as its own
1685
+ * trusted axis keeps `principal` the design/62 IDENTITY it is: the identity also keys the durable
1686
+ * approval / checkpoint namespace (`checkpointScopeOf`), the runtime-capability lookup and the MCP
1687
+ * principal header, and a mount's registry scope has no business moving any of those (an unattended
1688
+ * safety park must not migrate into the caller's opt-in approval bucket — design/153 §7.4).
1689
+ *
1690
+ * TRUSTED channel (never a {@link TaskSpec} field, never a model argument), like the parentage axes
1691
+ * above. When a deployment sets both, they agree by construction: with a principal present the
1692
+ * delegation tool resolves this axis TO that principal.
1693
+ */
1694
+ registryScope?: string;
1695
+ /** design/148 S1 — the spawning run's ADOPTED center artifact, threaded down the
1696
+ * trusted internals chain so every child in the tree composes the SAME closure (a child must
1697
+ * never spontaneously adopt the live candidate while its parent runs an older pin — that is the
1698
+ * exact mixed-version state the epoch exists to prevent). Resolved by-digest through the
1699
+ * verified store at child prepare; a miss is the same fail-loud `prompt.snapshot_unavailable`. */
1700
+ parentCenterArtifactDigest?: string;
1701
+ /** Publish provenance companion of {@link parentCenterArtifactDigest} (audit only). */
1702
+ parentCenterSourceRevision?: string;
1703
+ /** R2 双形轴 — parent's resolved prompt profile, inherited unless the child spec overrides. */
1704
+ promptProfile?: "simple" | "classic";
1705
+ /**
1706
+ * design/99 (nested-subagent live tree) — an OPT-IN, DISPLAY-ONLY event sink a deployment sets on the TOP run to
1707
+ * receive a subagent's live `task_progress` ticks (which otherwise stay in the child's ISOLATED stream). Threaded
1708
+ * recursively down the delegation tree (via `ctx.forwardEvent`), so every nested subagent's ticks bubble to the
1709
+ * SAME sink. The Runner's ctx wrapper forwards `task_progress` always; when the run's spec sets
1710
+ * `forwardSubagentEvents: true` it ALSO forwards the child's content events (`text_delta` / `text_end` (#447) /
1711
+ * `reasoning_delta` / `tool_start` / `tool_end` — the subagent viewing pane, carrying the same UNTRUSTED-RAW/consumer-must-redact
1712
+ * contract as the main stream's tool events). Either way the child stream is NEVER merged into the parent's
1713
+ * MODEL context (this is purely a render channel). Absent unless the deployment opted in.
1714
+ */
1715
+ onForwardEvent?: (event: TaskEvent) => void;
1716
+ /**
1717
+ * #253 — the run's OWN top-level `status` TaskEvent stream (brain liveness: rate-limit/retry/
1718
+ * reconnect/circuit-open), offered to the internals holder beside the queue. The queue alone was
1719
+ * enough for a direct `runTask` caller (the TaskStream carries these frames), but a COMPOSITION
1720
+ * entry (verify/cascade) drains its inner legs' queues itself — without this seat, an inner leg's
1721
+ * retry disclosure died inside the gate and the wire showed a silent stall. Fed the SAME frame
1722
+ * object the queue receives, at the same moment; contained by the run's safe notifier (#248 form:
1723
+ * a throwing sink is swallowed, first failure per site disclosed, never faults the leg). Subagent
1724
+ * frames still ride {@link onForwardEvent} — this seat is ONLY the run's own status type.
1725
+ */
1726
+ onStatusEvent?: (event: Extract<TaskEvent, {
1727
+ type: "status";
1728
+ }>) => void;
1729
+ /**
1730
+ * design/115 P2 core slice — trusted run-local system-injection sink. `Runner.runLocked` wires this to the
1731
+ * live TaskStream queue plus the current harness follow-up lane; it is not a public TaskSpec field.
1732
+ */
1733
+ /** design/116 detach: the run-local per-tool-call detach hub. runtask creates it and exposes
1734
+ * `TaskStream.detach(toolCallId)`; the hands Bash tool threads `signalFor(toolCallId)` into env.exec. */
1735
+ detachHub?: import("../tool-detach.js").ToolDetachHub;
1736
+ /**
1737
+ * #483 rung-1 — the Runner's per-session read-file-state seats (CC parity: readFileState is
1738
+ * session-scoped). Always set by the Runner's own prepare call (overriding any caller value, like
1739
+ * the peer refs beside it); absent on a standalone prepareTask, where the transcript-replay rung
1740
+ * covers alone. A CACHE, never an authority — see {@link SessionReadFileStates}. Trusted internals
1741
+ * channel, same posture as every other field here.
1742
+ */
1743
+ sessionReadStates?: SessionReadFileStates;
1744
+ onTaskNotification?: (notification: TaskNotificationPayload,
1745
+ /** Injection tier (design/373 — the ladder is LIVE): "next" = the running turn's next boundary
1746
+ * (arrival order, consecutive frames batch); "later" = the run's would-otherwise-stop seat
1747
+ * (never folded into work in progress); "now" = class-head + earliest natural boundary on this
1748
+ * lane (interrupt authority belongs to the steer face, never to notifications). Internal
1749
+ * producers declare their tier explicitly (§3.7 census — completion-class lanes are "next");
1750
+ * the parameterless default "later" serves the external verb's omitting callers only. */
1751
+ opts?: {
1752
+ priority?: import("../task-notification.js").SystemInjectionPriority;
1753
+ }) => void;
1754
+ /**
1755
+ * design/147 S1a — the PARENT run's notification injector (its runtask-wrapped
1756
+ * `injectTaskNotification`), threaded into a CHILD's internals at spawn time so the child's
1757
+ * SendMessage("main") uplink lands in the parent's queue at a turn boundary (the CC
1758
+ * "delivered automatically" parent half). DELIBERATELY a separate field from
1759
+ * {@link RunInternals.onTaskNotification}: that one is "inject into THIS run" (runtask wraps it
1760
+ * as upstream-observer + own-queue), and reusing it for the child would tee every internal child
1761
+ * notification (grandchild completions, monitor events) into the parent — double delivery.
1762
+ */
1763
+ parentNotify?: (notification: TaskNotificationPayload, opts?: {
1764
+ priority?: import("../task-notification.js").SystemInjectionPriority;
1765
+ }) => void;
1766
+ /**
1767
+ * design/147 S3a — the PARENT run's subagent-retain ledger, threaded to a CHILD so its
1768
+ * SendMessage can continue a RETAINED SIBLING (the sibling's retain entry lives on the parent's
1769
+ * ledger — without this, sibling resolution succeeds but delivery always reads not-retained).
1770
+ * TRUSTED chain; read-only use (the sibling leg resumes through the same fenced resume face).
1771
+ */
1772
+ parentRetainLedger?: import("../../agents/retain-ledger.js").SubagentRetainLedger;
1773
+ /**
1774
+ * design/147 S2a — hands THIS run's notification injector back to the SPAWNER once the lane is
1775
+ * live (runtask calls it with its wrapped `injectTaskNotification`). The spawner stores it on the
1776
+ * child's registry handle so a parent/sibling SendMessage can deliver TO the RUNNING child at its
1777
+ * next turn boundary (CC's in-memory `pendingMessages` pedestal, anchors/2.1.212
1778
+ * messaging-runtime.md §2.5). The injector is RUN-SCOPED but fail-safe after the run: the lane's
1779
+ * teardown branch parks late payloads per session (PendingSessionNotifications), which is exactly
1780
+ * CC's durable-mailbox posture for an idle teammate (§2.4) — no separate file mailbox needed.
1781
+ * TRUSTED chain (core spawner only); never reachable from TaskSpec.
1782
+ */
1783
+ onNotifyInjectorReady?: (inject: (notification: TaskNotificationPayload, opts?: {
1784
+ priority?: import("../task-notification.js").SystemInjectionPriority;
1785
+ }) => Promise<"queued" | "parked" | "dropped_duplicate">) => void;
1786
+ /**
1787
+ * design/97 CORE-6 — per-task ISOLATION hint, a TRUSTED run-scoped channel filled ONLY by a core caller
1788
+ * (the workflow's `ctx.agent` when the SCRIPT passed `{ isolation: "worktree" }` as an OPTION) — NEVER a
1789
+ * {@link TaskSpec} field (the untrusted-caller surface, design/44 §7 Q4). Forwarded to
1790
+ * {@link ExecutionEnvFactory} via {@link ExecutionEnvFactoryContext.isolation} so the trusted control-plane
1791
+ * factory mints a git-worktree-rooted env for this agent; and it makes root resolution use the worktree
1792
+ * env's own cwd (the worktree dir), bypassing `deps.rootPath`. Isolate-ONLY: the runtime never merges
1793
+ * — the orchestrator script reads each worktree's result and decides verify/merge in userland.
1794
+ * FAIL-CLOSED: a request the deployment cannot honor (no factory, or an observably non-isolated env)
1795
+ * throws at prepare time — the child never starts; there is no silent fallback to the shared tree.
1796
+ */
1797
+ isolation?: "worktree";
1798
+ /**
1799
+ * Sub-agent cwd inheritance (CC parity, 2026-07-03): the PARENT task's effective working root,
1800
+ * filled ONLY by core delegation callers (the workflow's `ctx.agent` / `createSubagentTool`'s execute —
1801
+ * NEVER a {@link TaskSpec} field). Forwarded to {@link ExecutionEnvFactory} via
1802
+ * {@link ExecutionEnvFactoryContext.parentCwd} so a single-user/TOC factory can root the child env at the
1803
+ * parent's cwd instead of an empty per-task sandbox. `isolation: "worktree"` wins over this when both set.
1804
+ */
1805
+ parentCwd?: string;
1806
+ /**
1807
+ * The spawning run's file-history LINEAGE — the scope it records first-touch edits into and the
1808
+ * TREE those records' keys are minted against (the canonical root spelling + the filesystem
1809
+ * identity of {@link fileHistoryFilesystemIdentity}) — threaded VERBATIM by core delegation
1810
+ * callers from {@link import("../types.js").ToolExecuteContext.fileHistoryLineage} (NEVER a
1811
+ * {@link TaskSpec} field). {@link resolveFileHistoryScope} is the ONE reading: this run records
1812
+ * into the lineage's scope iff its own tree coordinates BOTH equal the lineage's, and then
1813
+ * re-exposes the SAME triple on its own ctx, so every same-tree descendant of a root session — at
1814
+ * any depth — lands in the root session's scope (the fixed point), while a descendant on another
1815
+ * tree (worktree isolation, explicit `cwd`, a fresh per-task sandbox) becomes the root of its own
1816
+ * subtree's history. Absent on a top-level run, on a run with no live history store, and on a
1817
+ * tier-3 revival (the reviver's lineage says nothing about the revived row's tree).
1818
+ */
1819
+ fileHistoryLineage?: {
1820
+ scope: string;
1821
+ root: string;
1822
+ fs: string;
1823
+ };
1824
+ /**
1825
+ * [c209-D] — the EXPLICIT Agent.cwd request, distinct from the best-effort `parentCwd`
1826
+ * inheritance hint above: inheritance may be silently ignored by a factory (or absent without one),
1827
+ * but an explicit cwd the model asked for MUST either take effect or fail loud. prepareTask enforces
1828
+ * the contract: no `executionEnvFactory` ⇒ throw `config.cwd_unsupported`; after env creation the
1829
+ * env's actual cwd must canonically equal this path or the task fails `config.cwd_not_honored`; the
1830
+ * task root follows the env's cwd (never `deps.rootPath`) when set. Filled ONLY by core delegation
1831
+ * callers (ctx-injection posture, same as `parentCwd`).
1832
+ */
1833
+ requestedCwd?: string;
1834
+ /**
1835
+ * Subagent steer verb (dogfood finding 2026-07-03, "中途插话"): the host run's opt-in
1836
+ * SUBAGENT-STEER-HANDLE sink. When set, `createSubagentTool` runs each child via `runTaskStream`
1837
+ * and emits a steer handle here (the model never sees the handle — same host-context-isolation
1838
+ * posture as `onWorkflowAgentSpawn`). A deployment registers it by `taskId` to route a human steer
1839
+ * into the running child (fenced-marker semantics matching the workflow agent handle). Threaded to
1840
+ * the tool ctx as {@link ToolExecuteContext.onSubagentSpawn} and recursively down the delegation
1841
+ * tree. Absent ⇒ children run non-steerable (prior behavior, zero overhead).
1842
+ * SCOPE (fable impl-review F3, recorded): only SYNC delegations emit a handle — a
1843
+ * `run_in_background` child does not (poll/stop it via TaskOutput/TaskStop); wiring the background
1844
+ * lane is a recorded follow-up, not an oversight a deployment should discover at runtime.
1845
+ */
1846
+ onSubagentSpawn?: (handle: import("../../agents/subagent.js").SubagentSteerHandle) => void;
1847
+ /**
1848
+ * design/97 CORE-8 (③) — a TRUSTED run-scoped tool-ACTIVITY sink, filled ONLY by a core caller (the workflow's
1849
+ * `ctx.agent`, to render a per-agent "last N tool calls" drill-down). Called synchronously at each tool start +
1850
+ * end with structural data (name/phase/ids) — NEVER args/output (those carry untrusted/host data). NEVER a
1851
+ * {@link TaskSpec} field. Absent ⇒ no activity capture (default).
1852
+ *
1853
+ * Reaches activity on FRESH and RESUMED runs alike — the durable-resume entry (`resumeStream`) threads
1854
+ * `internals` too (see its parent-constraint re-supply snapshot), so a resumed leg's SUBSEQUENT tool calls
1855
+ * hit this sink. One real boundary remains (#249): the resume's already-approved pending call itself is
1856
+ * executed by `applyResumeDecision`'s own callback, outside the frame-minting harness, so THAT one call
1857
+ * emits no activity.
1858
+ */
1859
+ onActivity?: (activity: ToolActivity) => void;
1860
+ /**
1861
+ * RB-393① — a TRUSTED run-scoped WORKSPACE-observation sink, filled ONLY by a core caller
1862
+ * (the workflow's `ctx.agent` / `ctx.agentStream`, to record an isolated agent's worktree directory on the
1863
+ * persisted run record). NEVER a {@link TaskSpec} field — same posture as {@link onActivity}.
1864
+ *
1865
+ * WHY the engine must hand this out: for `isolation: "worktree"` the worktree path is minted INSIDE
1866
+ * {@link RunnerDeps.executionEnvFactory} and lands only on the per-task env's `cwd`; no runner-outward face
1867
+ * (TaskEvent union / TaskStream / TaskResult) carries it back. An orchestrator therefore could not record
1868
+ * WHERE its isolated agent worked — the recovery path after an interrupted run had to enumerate the
1869
+ * worktrees directory and guess, which is exactly the contradiction recorded against the
1870
+ * "isolate-only, userland decides verify/merge" intent.
1871
+ *
1872
+ * Called at most ONCE per prepared run with the task's FINAL working root (see {@link ResolvedWorkspace}),
1873
+ * after the durable-resume restore may have re-rooted it. Observe-only: a throwing sink is swallowed (an
1874
+ * observation must never fault a prepare that already minted a workspace).
1875
+ *
1876
+ * Like {@link onActivity}, this seat rides `internals` on FRESH and RESUMED runs alike (`resumeStream`
1877
+ * threads it too) — a resumed leg's restore re-fires the observation with the settled root.
1878
+ */
1879
+ onWorkspaceResolved?: (workspace: ResolvedWorkspace) => void;
1880
+ }
1881
+ /**
1882
+ * RB-393① — the payload of {@link RunInternals.onWorkspaceResolved}: the working root this task actually
1883
+ * runs on, plus whether that root is the task's OWN isolated workspace.
1884
+ *
1885
+ * `isolated: true` means "`cwd` is this agent's own git worktree": it is reported only when
1886
+ * {@link RunInternals.isolation} was requested AND the fail-closed worktree enforcement accepted the env, so a
1887
+ * consumer may treat the path as private to this agent (safe to diff / merge / remove in userland). A
1888
+ * non-isolated run reports its plain root with `isolated: false` — the observation face stays complete, while
1889
+ * the honest non-claim keeps a consumer from mistaking a SHARED tree for its own worktree.
1890
+ */
1891
+ export interface ResolvedWorkspace {
1892
+ /** The task's effective working root — the same value every fence / LSP / prompt consumer uses. */
1893
+ cwd: string;
1894
+ /** True only for an accepted `isolation: "worktree"` request (⇒ `cwd` is this agent's own worktree). */
1895
+ isolated: boolean;
1896
+ /** True when the task's execution env is REMOTE (#197 BGW-7): `cwd` then names a path INSIDE the remote
1897
+ * target (a per-task sandbox on the shape-(d) exemption leg, e.g. `/workspace`), which does not exist —
1898
+ * or names an unrelated directory — on the host. `isolated && !remote` is the only combination under
1899
+ * which `cwd` is a host path a consumer may diff / merge / remove. */
1900
+ remote: boolean;
1901
+ }
1902
+ /**
1903
+ * #457 ② — the resolver's answer, with the WITHHELD cause beside the value.
1904
+ *
1905
+ * The old signature returned a bare `unknown`, which collapsed three different worlds into one
1906
+ * `undefined`: "this tool declares no preview at all", "the projection threw / could not be
1907
+ * serialized", and "the projection declined to speak for these args". The middle one is the case an
1908
+ * approval surface must be told about — a person is being asked to approve something whose display
1909
+ * projection could NOT be produced — and it was indistinguishable from the other two.
1910
+ *
1911
+ * `withheld` names the cause; it is ORTHOGONAL to `preview` presence, deliberately: the oversize arm
1912
+ * still ships its truncation stub (a surface that renders it tells the person the size, which is more
1913
+ * useful than nothing), and the stub alone never carried the fact that the real projection is missing.
1914
+ */
1915
+ export interface ResolvedApprovalPreview {
1916
+ /** The display projection, when one could be produced (or the oversize truncation stub). */
1917
+ preview?: unknown;
1918
+ /** Present ⇔ the tool DECLARED a preview and the gate could not present a usable one:
1919
+ * `"oversize"` — produced but past the 16KiB display bound (the stub rides `preview`);
1920
+ * `"unavailable"` — the projection threw, or its value has no JSON serialization.
1921
+ * ABSENT covers both "no preview declared" and "the projection returned nothing to show" — neither
1922
+ * is a withholding, and claiming one would make every preview-less tool look suppressed. */
1923
+ withheld?: "oversize" | "unavailable";
1924
+ }
1925
+ /** The in-stream ask lane: the six closures the park closure and the gate station consume. Built as ONE value so
1926
+ * "the lane exists" is one fact, not six independently-undefined seats. */
1927
+ export interface AskLane {
1928
+ /** The shared run+call signal composition, bound to this task's run signal once. */
1929
+ composedCallSignal: (callSignal: AbortSignal | undefined) => AbortSignal;
1930
+ /** The abort-bound policy check, or undefined when no policy is wired (→ the gate reads allow). */
1931
+ adjudicate: ((req: ToolCallRequest, callSignal?: AbortSignal) => Promise<PermissionResult>) | undefined;
1932
+ /** The approval display projection over the live roster (alias-aware; oversize/unavailable named). */
1933
+ approvalPreviewOf: (toolName: string, args: unknown) => ResolvedApprovalPreview;
1934
+ /** THE synchronous ask mint: resolves a surviving `ask` through the live seat, books the ledger. */
1935
+ resolveAskBound: (decision: PermissionResult, req: ToolCallRequest, callSignal?: AbortSignal) => Promise<ResolvedAsk>;
1936
+ /** The pre-wrapped deny observer, or undefined when the deployment wired no `permissionDenied` hook. */
1937
+ notifyPermissionDenied: ((payload: PermissionDeniedPayload) => Promise<void>) | undefined;
1938
+ /** The deployment-facing half of a crashing PreToolUse hook (swallow-guarded). */
1939
+ notifyHookError: (err: unknown) => void;
1940
+ }
1941
+ /** How the put-commit + put-failure saga ended (see `commitSuspendSaga` inside the phase for each arm's meaning). */
1942
+ export type SuspendSagaOutcome = {
1943
+ tag: "committed";
1944
+ } | {
1945
+ tag: "cut";
1946
+ } | {
1947
+ tag: "absent";
1948
+ reason?: string;
1949
+ } | {
1950
+ tag: "unknown";
1951
+ reason: string;
1952
+ } | {
1953
+ tag: "compensation_failed";
1954
+ reason: string;
1955
+ };
1956
+ /** The durable settlement machinery the boundary parks and the park closure consume. Built as ONE value so "the saga
1957
+ * exists" is one fact, not eight independently-undefined seats. */
1958
+ export interface SuspendSaga {
1959
+ /** THIS leg's spend so far in micro-USD (own + nested delta), read at mint time. */
1960
+ inFlightSpendMicroUsd: () => number;
1961
+ /** The §4.bis correctness-state whitelist, serialized from the live values at suspend. */
1962
+ serializeCheckpointState: (workspaceHandle: WorkspaceHandle | undefined, parkedSpendMicroUsd?: number) => SerializedCheckpointState;
1963
+ /** The shared paused-VM compensation, bound to this task's failure ledger and error face. */
1964
+ compensatePausedVM: (remoteEnv: RemoteExecutionEnv, snapshotId: SnapshotId) => Promise<{
1965
+ ok: true;
1966
+ } | {
1967
+ ok: false;
1968
+ reason: string;
1969
+ }>;
1970
+ /** The put-commit + put-failure split — the point of no return, tagged. */
1971
+ commitSuspendSaga: (token: CheckpointToken, cp: Checkpoint, remoteEnv: RemoteExecutionEnv | undefined, remoteHandle: WorkspaceHandle | undefined, cutSignal?: AbortSignal) => Promise<SuspendSagaOutcome>;
1972
+ /** The shared suspend-loop-cap guard (safety state first, diagnostic second). */
1973
+ suspendLoopCapHit: (count: number, cap: number | undefined, detail: string) => boolean;
1974
+ /** The `suspendVM` target by CAPABILITY, or undefined. */
1975
+ suspendableEnv: RemoteExecutionEnv | undefined;
1976
+ /** The park-only remote target (non-suspendable, externally durable), or undefined. */
1977
+ parkOnlyRemoteEnv: RemoteExecutionEnv | undefined;
1978
+ /** The park-only identity capture (snapshotId stripped, `restoreMode: "park_only"`). */
1979
+ parkOnlyHandle: (env: RemoteExecutionEnv) => WorkspaceHandle;
1980
+ }
1981
+ /** The park closure and the content-ask routing closure the gate station hands to `runToolGate`. Built as ONE value so
1982
+ * "the park lane's closures exist" is one fact; `suspendAsk` stays optional INSIDE it because the park predicate (a store,
1983
+ * and something to park for) is a narrower condition than the gate machinery's activation. */
1984
+ export interface ParkAsk {
1985
+ /** design/174 — the gate's content-ask routing closure (total by construction; answers `unavailable` with no live face). */
1986
+ resolveContentAsk: NonNullable<ToolGateInput["resolveContentAsk"]>;
1987
+ /** design/45 — the durable park closure (twelve positional seats then the structural carry), or undefined when the park
1988
+ * lane is not armed (the gate then keeps the synchronous onAsk path). */
1989
+ suspendAsk: ToolGateInput["suspendAsk"];
1990
+ }