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