@sema-agent/core 7.4.0 → 7.5.1

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