@sema-agent/core 7.57.0 → 7.58.0

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 (198) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/dist/agents/subagent-steps.js +2 -4
  3. package/dist/brain/route-adjudicator.js +2 -1
  4. package/dist/core/a2a.d.ts +2 -1
  5. package/dist/core/a2a.js +23 -10
  6. package/dist/core/allow-entry.d.ts +2 -1
  7. package/dist/core/allow-entry.js +2 -1
  8. package/dist/core/ask-origin.d.ts +21 -2
  9. package/dist/core/ask-origin.js +5 -1
  10. package/dist/core/auto-compaction.d.ts +4 -0
  11. package/dist/core/auto-compaction.js +1 -1
  12. package/dist/core/auto-mode-directive.d.ts +29 -5
  13. package/dist/core/auto-mode-directive.js +38 -8
  14. package/dist/core/checkpoint-requirements.d.ts +7 -1
  15. package/dist/core/checkpoint-requirements.js +2 -0
  16. package/dist/core/checkpoint-store.d.ts +27 -11
  17. package/dist/core/checkpoint-store.js +13 -3
  18. package/dist/core/engine-notice.d.ts +1 -1
  19. package/dist/core/fs-write-gate-policy.d.ts +4 -2
  20. package/dist/core/fs-write-gate-policy.js +7 -3
  21. package/dist/core/gate-fold.js +6 -3
  22. package/dist/core/gate-lanes.js +11 -2
  23. package/dist/core/git-worktree-env.d.ts +53 -11
  24. package/dist/core/git-worktree-env.js +96 -12
  25. package/dist/core/hooks.d.ts +4 -1
  26. package/dist/core/hooks.js +12 -5
  27. package/dist/core/human-input-projection.d.ts +1 -0
  28. package/dist/core/human-input-projection.js +3 -0
  29. package/dist/core/locked-config.d.ts +15 -1
  30. package/dist/core/locked-config.js +38 -2
  31. package/dist/core/mcp-call-meta.d.ts +66 -0
  32. package/dist/core/mcp-call-meta.js +103 -0
  33. package/dist/core/mcp-connection-pool.d.ts +3 -1
  34. package/dist/core/mcp-connection-pool.js +3 -1
  35. package/dist/core/mcp-failure.d.ts +7 -1
  36. package/dist/core/mcp-failure.js +10 -0
  37. package/dist/core/mcp-probe.d.ts +4 -0
  38. package/dist/core/mcp-probe.js +1 -1
  39. package/dist/core/mcp-server-link.d.ts +5 -2
  40. package/dist/core/mcp-server-spec.d.ts +46 -18
  41. package/dist/core/mcp-server-spec.js +1 -18
  42. package/dist/core/mcp.d.ts +6 -14
  43. package/dist/core/mcp.js +77 -37
  44. package/dist/core/memory-engine/scope-contract.d.ts +45 -4
  45. package/dist/core/memory-engine/scope-contract.js +80 -11
  46. package/dist/core/mode-policy.d.ts +8 -5
  47. package/dist/core/mode-policy.js +5 -4
  48. package/dist/core/mods/host.js +1 -1
  49. package/dist/core/mods/kernel/dispatch.d.ts +3 -0
  50. package/dist/core/mods/kernel/dispatch.js +10 -8
  51. package/dist/core/mods/kernel/events.d.ts +5 -1
  52. package/dist/core/mods/kernel/events.js +1 -1
  53. package/dist/core/mods/kernel/registration.d.ts +5 -1
  54. package/dist/core/mods/kernel/site-rules.d.ts +3 -0
  55. package/dist/core/mods/kernel/site-rules.js +10 -0
  56. package/dist/core/mods/package.d.ts +23 -0
  57. package/dist/core/mods/package.js +118 -0
  58. package/dist/core/mods/stations.d.ts +2 -2
  59. package/dist/core/mods/stations.js +1 -1
  60. package/dist/core/mods/tool-call.d.ts +5 -1
  61. package/dist/core/mods/tool-call.js +12 -3
  62. package/dist/core/path-guard-rows.d.ts +20 -0
  63. package/dist/core/path-guard-rows.js +11 -0
  64. package/dist/core/peer-seat.d.ts +186 -0
  65. package/dist/core/peer-seat.js +307 -0
  66. package/dist/core/present-plan-tool.d.ts +10 -1
  67. package/dist/core/present-plan-tool.js +46 -2
  68. package/dist/core/protocol-http-auth.d.ts +40 -29
  69. package/dist/core/protocol-http-auth.js +30 -32
  70. package/dist/core/redaction-marks.d.ts +16 -0
  71. package/dist/core/redaction-marks.js +16 -0
  72. package/dist/core/redaction-passes.js +8 -9
  73. package/dist/core/retention.d.ts +41 -15
  74. package/dist/core/retention.js +59 -12
  75. package/dist/core/rewrite-rejudge.d.ts +37 -0
  76. package/dist/core/rewrite-rejudge.js +40 -0
  77. package/dist/core/run-origin.d.ts +40 -0
  78. package/dist/core/run-origin.js +37 -0
  79. package/dist/core/runner/advertised-writable-dirs.d.ts +57 -38
  80. package/dist/core/runner/advertised-writable-dirs.js +126 -0
  81. package/dist/core/runner/compaction-restate.d.ts +15 -6
  82. package/dist/core/runner/compaction-restate.js +28 -2
  83. package/dist/core/runner/contracts.d.ts +13 -5
  84. package/dist/core/runner/gate-exit.d.ts +18 -4
  85. package/dist/core/runner/gate-exit.js +5 -1
  86. package/dist/core/runner/prepare-caps-and-workflow.d.ts +2 -0
  87. package/dist/core/runner/prepare-caps-and-workflow.js +1 -1
  88. package/dist/core/runner/prepare-config-doors.d.ts +8 -5
  89. package/dist/core/runner/prepare-config-doors.js +12 -10
  90. package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
  91. package/dist/core/runner/prepare-delegation-surface.js +15 -18
  92. package/dist/core/runner/prepare-gate-stations.js +1 -1
  93. package/dist/core/runner/prepare-hands-readface.d.ts +7 -3
  94. package/dist/core/runner/prepare-hands-readface.js +4 -1
  95. package/dist/core/runner/prepare-memory.d.ts +3 -0
  96. package/dist/core/runner/prepare-memory.js +19 -23
  97. package/dist/core/runner/prepare-policy-chain.d.ts +4 -4
  98. package/dist/core/runner/prepare-policy-chain.js +2 -2
  99. package/dist/core/runner/prepare-protocol-tools.d.ts +4 -2
  100. package/dist/core/runner/prepare-protocol-tools.js +3 -3
  101. package/dist/core/runner/prepare-suspend-saga.d.ts +2 -0
  102. package/dist/core/runner/prepare-suspend-saga.js +2 -1
  103. package/dist/core/runner/prepare-task.js +25 -12
  104. package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -0
  105. package/dist/core/runner/prepare-wiring-manifest.js +2 -2
  106. package/dist/core/runner/prepare-workspace-restore.d.ts +3 -0
  107. package/dist/core/runner/prepare-workspace-restore.js +4 -4
  108. package/dist/core/runner/resume-admission.js +1 -1
  109. package/dist/core/runner/resume-checkpoint-screen.js +2 -0
  110. package/dist/core/runner/run-harness-handlers.d.ts +3 -4
  111. package/dist/core/runner/run-harness-handlers.js +1 -8
  112. package/dist/core/runner/run-identity-wiring.js +1 -0
  113. package/dist/core/runner/run-leg.js +5 -1
  114. package/dist/core/runner/run-notification-lane.js +3 -0
  115. package/dist/core/runner/terminal-account.js +3 -3
  116. package/dist/core/runner/tool-end-body.js +1 -0
  117. package/dist/core/runner/tool-occurrence.d.ts +4 -1
  118. package/dist/core/runner/tool-occurrence.js +2 -1
  119. package/dist/core/runner/write-protection-station.d.ts +8 -2
  120. package/dist/core/runner/write-protection-station.js +2 -0
  121. package/dist/core/runner-deps.d.ts +2 -2
  122. package/dist/core/sensitive-path-policy.js +6 -7
  123. package/dist/core/session-log-transfer.d.ts +24 -0
  124. package/dist/core/session-log-transfer.js +166 -0
  125. package/dist/core/session-store.d.ts +84 -19
  126. package/dist/core/session-store.js +162 -24
  127. package/dist/core/session.d.ts +92 -1
  128. package/dist/core/shell-read-silence.js +1 -0
  129. package/dist/core/steer-replay.d.ts +4 -2
  130. package/dist/core/steer-replay.js +2 -1
  131. package/dist/core/store-contracts/checkpoint-store-contract.js +17 -0
  132. package/dist/core/store-contracts/session-repo-contract.js +112 -5
  133. package/dist/core/store-contracts/session-store-contract.d.ts +4 -1
  134. package/dist/core/store-contracts/session-store-contract.js +236 -2
  135. package/dist/core/task-event.d.ts +68 -8
  136. package/dist/core/task-registry-shared.d.ts +2 -1
  137. package/dist/core/task-spec.d.ts +37 -0
  138. package/dist/core/task-stream.d.ts +2 -1
  139. package/dist/core/terminal-cause.d.ts +1 -1
  140. package/dist/core/tool-catalog-entries.js +1 -0
  141. package/dist/core/tool-result-store.d.ts +17 -10
  142. package/dist/core/tool-result-store.js +3 -1
  143. package/dist/core/types.d.ts +1 -1
  144. package/dist/core/untrusted-egress.d.ts +0 -2
  145. package/dist/core/untrusted-egress.js +10 -14
  146. package/dist/core/wiring-manifest.d.ts +12 -3
  147. package/dist/core/wiring-manifest.js +4 -3
  148. package/dist/core/workspace-snapshot.d.ts +44 -0
  149. package/dist/core/workspace-snapshot.js +34 -0
  150. package/dist/core/write-protect.d.ts +43 -3
  151. package/dist/core/write-protect.js +43 -16
  152. package/dist/engine/execution-env/node-execution-env.js +15 -11
  153. package/dist/engine/execution-env/symlink-chain.d.ts +7 -5
  154. package/dist/engine/harness/agent-harness.d.ts +5 -0
  155. package/dist/engine/harness/agent-harness.js +2 -0
  156. package/dist/engine/harness/types.d.ts +48 -7
  157. package/dist/engine/harness/types.js +5 -1
  158. package/dist/engine/llm/types.d.ts +12 -3
  159. package/dist/engine/llm/types.js +1 -1
  160. package/dist/engine/session/import-validate.js +3 -0
  161. package/dist/engine/session/memory-repo.d.ts +17 -9
  162. package/dist/engine/session/memory-repo.js +44 -34
  163. package/dist/engine/session/repo-utils.d.ts +22 -4
  164. package/dist/engine/session/repo-utils.js +49 -1
  165. package/dist/engine/session/storage-base.d.ts +10 -1
  166. package/dist/engine/session/storage-base.js +7 -1
  167. package/dist/index.d.ts +13 -6
  168. package/dist/index.js +10 -4
  169. package/dist/internal/harness-types.d.ts +1 -1
  170. package/dist/internal/harness.d.ts +2 -2
  171. package/dist/internal/harness.js +2 -2
  172. package/dist/stores/file/index.d.ts +4 -1
  173. package/dist/stores/file/index.js +4 -1
  174. package/dist/stores/file/session-store.d.ts +15 -8
  175. package/dist/stores/file/session-store.js +28 -13
  176. package/dist/tools/fs/fs-write.d.ts +6 -3
  177. package/dist/tools/fs/fs-write.js +8 -7
  178. package/dist/tools/fs/index.d.ts +3 -0
  179. package/dist/tools/fs/index.js +1 -1
  180. package/dist/tools/fs/safety.js +40 -8
  181. package/dist/tools/fs/search.js +6 -24
  182. package/dist/tools/fs/shell-read-check.d.ts +8 -1
  183. package/dist/tools/fs/shell-read-check.js +59 -15
  184. package/dist/tools/fs/shell-read-establish.js +2 -1
  185. package/dist/tools/fs/shell-read-identity.js +1 -1
  186. package/dist/tools/fs/shell-read-judge.d.ts +10 -1
  187. package/dist/tools/worktree.d.ts +42 -15
  188. package/dist/tools/worktree.js +60 -32
  189. package/package.json +4 -2
  190. package/test/export-surface.snapshot.json +63 -1
  191. package/wire-changes/core-stores-sql@7.58.0.json +29 -0
  192. package/wire-changes/core@7.58.0.json +2188 -0
  193. package/wire-changes/mods-kernel@7.58.0.json +81 -0
  194. package/wire-changes/primitives@7.58.0.json +29 -0
  195. package/dist/primitives/credential-ref.d.ts +0 -89
  196. package/dist/primitives/credential-ref.js +0 -125
  197. package/dist/primitives/index.d.ts +0 -2
  198. package/dist/primitives/index.js +0 -1
@@ -36,6 +36,10 @@ export interface PrepareHandsReadFaceInput {
36
36
  * resolver at the driver's root receiving point ({@link import("./task-root-canonical.js").resolveTaskRootCanonical}):
37
37
  * taken as an input, never re-canonicalized here, so the fence and the root notice cannot disagree. */
38
38
  taskRootCanonical: string;
39
+ /** borrowed-readonly — the leg's ONE write-location reader (prepare-task's `currentCheckoutOf` over the worktree seat): the
40
+ * primary WRITE root of the structured write tools and of the shell's write targets, read per call — it is the task root
41
+ * until EnterWorktree switches it, and moves back on ExitWorktree. The READ roots never read it. */
42
+ writeLocation: () => string;
39
43
  /** borrowed-readonly — B-4's checkpoint-path rebaser (T7): identity unless a divergent restore
40
44
  * armed it; applied to the readFileState seed keys and the handsCwd seed. */
41
45
  rebaseRestoredPath: (p: string) => string;
@@ -86,9 +90,9 @@ export interface PrepareHandsReadFaceInput {
86
90
  * (the Read tool's document-degradation fork). */
87
91
  model: Model;
88
92
  /** borrowed-readonly — the task-spec seats this phase reads, as a Pick over the SAME spec object
89
- * (R-4). `tools` feeds only the band shadow check; `envFacts` only the advertised scratchpad;
90
- * `retainBackgroundProcesses` only the band's retain lane (Bash's lifetime sentence + row stamp). */
91
- spec: Pick<TaskSpec, "additionalDirectories" | "additionalReadDirectories" | "envFacts" | "handsReadOnly" | "readDenyPatterns" | "readFace" | "writeFace" | "oneShot" | "resumeAt" | "retainBackgroundProcesses" | "sessionId" | "tools" | "excludeAllTools">;
93
+ * (R-4). `tools` feeds only the band shadow check; `envFacts` only the advertised scratchpad; `planFile` only the
94
+ * advertised session plan file; `retainBackgroundProcesses` only the band's retain lane (Bash's lifetime sentence + row stamp). */
95
+ spec: Pick<TaskSpec, "additionalDirectories" | "additionalReadDirectories" | "envFacts" | "planFile" | "handsReadOnly" | "readDenyPatterns" | "readFace" | "writeFace" | "oneShot" | "resumeAt" | "retainBackgroundProcesses" | "sessionId" | "tools" | "excludeAllTools">;
92
96
  /** borrowed-readonly — the deployment seats this phase reads, as a Pick over the SAME deps
93
97
  * object (R-4: `deps.onError?.()` keeps its receiver; a new deps read must widen this Pick).
94
98
  * `readDenyBuiltinTiers`/`readDenyBuiltinExclude` are SNAPSHOTTED before the first await that
@@ -172,6 +172,8 @@ export async function prepareHandsMount(input) {
172
172
  if (advertisedWritableDirs !== undefined) {
173
173
  if (spec.envFacts?.scratchpadDir)
174
174
  await advertisedWritableDirs.admit({ path: spec.envFacts.scratchpadDir, advertiser: "scratchpad", materializeMarker: ".sema-scratchpad" });
175
+ if (spec.planFile !== undefined)
176
+ await advertisedWritableDirs.admitPlanFile(spec.planFile);
175
177
  additionalRootsCanonical.push(...advertisedWritableDirs.roots);
176
178
  }
177
179
  for (const a of [additionalRootsCanonical, additionalReadRootsCanonical])
@@ -294,7 +296,7 @@ export async function prepareHandsMount(input) {
294
296
  ...denySeat,
295
297
  ...writeDenySeat,
296
298
  ...(input.personRows.unreadFor(toolCallId) ? { unreadPartitions: true } : {}),
297
- writeRoots: [rootCanonical, ...additionalRootsCanonical],
299
+ writeRoots: [input.writeLocation(), ...additionalRootsCanonical],
298
300
  ...(resolvedWriteFace !== undefined ? { writeFace: resolvedWriteFace.inForce() } : {}),
299
301
  ...((judge) => (judge !== undefined ? { writeTargetJudge: judge } : {}))(input.writeTargetJudge?.()),
300
302
  ...(resolvedReadFace !== undefined ? { face: resolvedReadFace } : {}),
@@ -334,6 +336,7 @@ export async function prepareHandsMount(input) {
334
336
  }
335
337
  const band = createHandsToolkit(executionEnv, readFileState, rootCanonical, {
336
338
  ...(additionalRootsCanonical.length > 0 ? { additionalRoots: additionalRootsCanonical } : {}),
339
+ writeRoot: input.writeLocation,
337
340
  readDenyHomes: carryReadFace([], { readDeny: tables.readDeny, writeDeny: tables.writeDeny, readRoots }),
338
341
  readFace: liveReadFace,
339
342
  writeFaceLive: resolvedWriteFace.inForce,
@@ -1,5 +1,6 @@
1
1
  import type { BeforeWriteHook, EffectiveMemoryScopes, RunnerDeps, TaskSpec, ToolSpec } from "../types.js";
2
2
  import { type CaptureEntitlementInput, type MemoryCapturePosture } from "./memory-capture-optout.js";
3
+ import { type SessionProjectVerdict } from "../memory-engine/scope-contract.js";
3
4
  import type { Prepared } from "./contracts.js";
4
5
  import type { AdvertisedWritableDirs } from "./advertised-writable-dirs.js";
5
6
  export interface PrepareMemoryInput {
@@ -18,6 +19,8 @@ export interface PrepareMemoryInput {
18
19
  /** borrowed-readonly — the resolved task root: the containment boundary every derived memory dir
19
20
  * is checked against, and the repo-root fallback when `deps.rootPath` is unset. */
20
21
  taskRootPath: string;
22
+ /** borrowed-readonly — the leg's ONE project verdict (`resolveSessionProject`, read here, never re-resolved). */
23
+ sessionProject: SessionProjectVerdict;
21
24
  /**
22
25
  * borrowed-readonly — #181-F5: whether a tool NAMED `Write` (the tool the CC `# Memory` instruction names) is on the
23
26
  * ASSEMBLED roster this run, not excluded, AND can actually REACH the host-side memory root:
@@ -1,7 +1,7 @@
1
1
  import { isAbsolute, sep } from "node:path";
2
2
  import { deliverEngineNotice } from "../types.js";
3
3
  import { admitMemoryScopes } from "../memory-admission.js";
4
- import { adoptLegacyRepoDirs, canonicalize, deriveRepoControlPlaneDir, deriveProjectControlDir, deriveProjectMemoryDir, deriveRepoMemoryDir, drainMemoryAnnouncements, effectiveControlRootOf, enqueueMemoryAnnouncement, isContainedIn, lookupProjectIdHint, recordProjectIdHint, resolveMemoryEngineRoot } from "../memory-engine/layout.js";
4
+ import { adoptLegacyRepoDirs, canonicalize, deriveRepoControlPlaneDir, deriveProjectControlDir, deriveProjectMemoryDir, deriveRepoKey, deriveRepoMemoryDir, drainMemoryAnnouncements, effectiveControlRootOf, enqueueMemoryAnnouncement, isContainedIn, lookupProjectIdHint, recordProjectIdHint, resolveMemoryEngineRoot } from "../memory-engine/layout.js";
5
5
  import { classifyScopePlanes, derivePersonalControlDir, derivePersonalMemoryDir, mergeHarvestReports, mergeInjections, needsDualRoots, parsedProjectPlane } from "../memory-engine/dual-root.js";
6
6
  import { memoryProjectScopeAbsentNotice, normalizeMemorySpec } from "../memory.js";
7
7
  import { deriveSupersededSet } from "../memory-engine/consolidation.js";
@@ -11,7 +11,7 @@ import { adjudicateCaptureOptOut, captureOptOutDeniedError, captureOptOutUnpersi
11
11
  import { readSessionCaptureOptOut } from "../memory-engine/layout.js";
12
12
  import { sessionIncarnationResolver } from "../memory-engine/session-incarnation.js";
13
13
  import { createMemoryEngineTools } from "../memory-engine/tools.js";
14
- import { assertScopeContractPlacement, parseScopeKey, resolveProjectId } from "../memory-engine/scope-contract.js";
14
+ import { assertScopeContractPlacement, parseScopeKey } from "../memory-engine/scope-contract.js";
15
15
  import { FileMemoryEngineBackend } from "../memory-engine/file-backend.js";
16
16
  import { writableRootOf } from "../memory-engine/types.js";
17
17
  import { catalogText } from "../../prompt-assembly/catalog/index.js";
@@ -112,19 +112,24 @@ export async function prepareMemory(input) {
112
112
  const consumesProjectIdentity = [...memorySpec.scopes, ...(memorySpec.writeScope !== null ? [memorySpec.writeScope] : [])]
113
113
  .map(parseScopeKey)
114
114
  .some((k) => k.kind === "proj" || k.kind === "userproj");
115
- let marker = null;
116
- try {
117
- marker = resolveProjectId(repoRoot);
118
- }
119
- catch (err) {
120
- if (consumesProjectIdentity)
121
- throw err;
122
- deps.onError?.(asThrownError(err), { phase: "config", sessionId });
123
- }
115
+ if (input.sessionProject.markerFault !== undefined && consumesProjectIdentity)
116
+ throw input.sessionProject.markerFault;
117
+ const marker = input.sessionProject.project?.source === "marker" ? { projectId: input.sessionProject.project.id } : undefined;
118
+ const verdictOnPartitionRoot = deriveRepoKey(input.sessionProject.root) === deriveRepoKey(repoRoot);
124
119
  if (marker) {
125
120
  identityKey = marker.projectId;
126
- const firstSwitch = lookupProjectIdHint(engineRoot, repoRoot) !== marker.projectId;
127
- recordProjectIdHint(engineRoot, repoRoot, marker.projectId);
121
+ if (memorySpec.writeScope !== null) {
122
+ const w = parseScopeKey(memorySpec.writeScope);
123
+ if ((w.kind === "proj" || w.kind === "userproj") && w.projectId !== marker.projectId) {
124
+ const e = new Error(`memory scope contract v2: writeScope ${memorySpec.writeScope} targets projectId ${w.projectId}, ` +
125
+ `but this checkout's marker (.sema/project) declares ${marker.projectId} — refusing a mis-addressed write.`);
126
+ e.code = "config.memory_project_identity";
127
+ throw e;
128
+ }
129
+ }
130
+ const firstSwitch = verdictOnPartitionRoot && lookupProjectIdHint(engineRoot, repoRoot) !== marker.projectId;
131
+ if (verdictOnPartitionRoot)
132
+ recordProjectIdHint(engineRoot, repoRoot, marker.projectId);
128
133
  if (firstSwitch) {
129
134
  try {
130
135
  const oldCtl = deriveRepoControlPlaneDir(engineRoot, repoRoot);
@@ -136,17 +141,8 @@ export async function prepareMemory(input) {
136
141
  catch {
137
142
  }
138
143
  }
139
- if (memorySpec.writeScope !== null) {
140
- const w = parseScopeKey(memorySpec.writeScope);
141
- if ((w.kind === "proj" || w.kind === "userproj") && w.projectId !== marker.projectId) {
142
- const e = new Error(`memory scope contract v2: writeScope ${memorySpec.writeScope} targets projectId ${w.projectId}, ` +
143
- `but this checkout's marker (.sema/project) declares ${marker.projectId} — refusing a mis-addressed write.`);
144
- e.code = "config.memory_project_identity";
145
- throw e;
146
- }
147
- }
148
144
  }
149
- else {
145
+ else if (verdictOnPartitionRoot) {
150
146
  const hint = lookupProjectIdHint(engineRoot, repoRoot);
151
147
  if (hint !== undefined) {
152
148
  deps.onError?.(new Error(`memory project marker missing but recoverable: ${repoRoot} previously carried projectId ${hint} ` +
@@ -66,9 +66,11 @@ export interface PreparePolicyChainInput {
66
66
  hostTaskId: string;
67
67
  /** borrowed-readonly — the FINAL task root (path rules resolve against it; the lanes' and the offers' root). */
68
68
  taskRootFinal: string;
69
- /** borrowed-readonly — the leg's canonical write roots beyond the task root (`additionalDirectories` + advertised writable
70
- * dirs): the `acceptEdits` mode gate allows writes inside the root and these, and asks outside them all. */
69
+ /** borrowed-readonly — the leg's canonical write roots beyond its write location (`additionalDirectories` + advertised writable
70
+ * dirs): the `acceptEdits` mode gate allows writes inside the write location and these, and asks outside them all. */
71
71
  additionalRootsCanonical: readonly string[];
72
+ /** borrowed-readonly — the leg's ONE write-location reader (`writeLocationOf`), read per call by the `acceptEdits` gate. */
73
+ writeLocation: () => string;
72
74
  /** borrowed-readonly — the run's resolved env (path rules resolve in it; the sandbox declaration is read off it). */
73
75
  executionEnv: ExecutionEnv;
74
76
  /** borrowed-readonly — the frozen preflight as installed on this leg: `toolPolicy` (the caller slot) and
@@ -166,8 +168,6 @@ export interface PreparePolicyChainInput {
166
168
  /** borrowed-readonly — the leg's live permission-mode seat: the mode gate policy layer and the inherited stations' arbitration
167
169
  * read `current` per call. */
168
170
  permissionMode: PermissionModeController;
169
- /** borrowed-readonly — the task's scratchpad directory (the mode write gate's one exemption), or undefined. */
170
- scratchpadDir: string | undefined;
171
171
  /** borrowed-readonly — the leg's live roster seat; the mode write gate reads `current` per call. */ toolRosterDeltas: NonNullable<ModeGateSeats["roster"]>;
172
172
  /** borrowed-readonly — the run's ONE typed stop for a denial-limit bound (the fallback settlements call it). */
173
173
  stopForDenialLimit: StopForDenialLimit;
@@ -32,7 +32,7 @@ import { policyThrowLine, reportPolicyThrow } from "./policy-throw.js";
32
32
  import { heldBy, heldValues, seatOf, wireOf } from "../tool-name-readings.js";
33
33
  import { hostFloorPolicy } from "../host-floor.js";
34
34
  export async function preparePolicyChain(input) {
35
- const { spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, executionEnv, lockedPreflight, pathRuleAnchors, headLeads, tools, harnessTools, selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus, ownModChain, autoModeDecider, readFace, permissionMode, scratchpadDir, toolRosterDeltas, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef, hostFloor } = input;
35
+ const { spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, writeLocation, executionEnv, lockedPreflight, pathRuleAnchors, headLeads, tools, harnessTools, selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus, ownModChain, autoModeDecider, readFace, permissionMode, toolRosterDeltas, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef, hostFloor } = input;
36
36
  const ancestorArbitrations = new Map();
37
37
  const arbitrateInherited = (ask, toolCallId, judged) => {
38
38
  const verdict = arbitrateByMode(permissionMode.current, judged.classification, { origin: judged.origin, ...askMandateMember(ancestorFacts(judged.ask.action === "ask" ? judged.ask : undefined)) });
@@ -609,7 +609,7 @@ export async function preparePolicyChain(input) {
609
609
  }
610
610
  return d;
611
611
  }));
612
- const modeGateLayer = createModeGatePolicy(permissionMode, { env: executionEnv, rootPath: taskRootFinal, acceptDirs: [taskRootFinal, ...additionalRootsCanonical], roster: toolRosterDeltas, readOnlyDeclared: (name) => mountedToolDeclaresReadOnly(tools, name), ...(scratchpadDir !== undefined ? { exemptDirs: [scratchpadDir] } : {}) });
612
+ const modeGateLayer = createModeGatePolicy(permissionMode, { env: executionEnv, rootPath: taskRootFinal, acceptDirs: () => [writeLocation(), ...additionalRootsCanonical], roster: toolRosterDeltas, readOnlyDeclared: (name) => mountedToolDeclaresReadOnly(tools, name) });
613
613
  const policyLayers = [...narrowingLayers, ...instrumentedChain, ...(rewriteCapableChain.length > 0 ? narrowingLayers : [])];
614
614
  const integrityGuardLayers = [createTranscriptIntegrityPolicy(), createUnverifiableDeletePolicy({ removalSeat: { env: executionEnv, additionalRoots: () => additionalRootsCanonical } })];
615
615
  const guardedPolicyLayers = [...integrityGuardLayers, ...policyLayers, modeGateLayer];
@@ -44,8 +44,8 @@ export interface PrepareProtocolToolsInput {
44
44
  spec: Pick<TaskSpec, "principal" | "tools" | "excludeAllTools" | "signal">;
45
45
  /** borrowed-readonly — the deployment seats the materializers and their operator faces read: `onElicit`
46
46
  * and `mcpImageResizer` ride into the MCP intake; `onError` takes the A2A warnings (no ledger — a peer is
47
- * re-read every prepare); `mcpRevocations` + `onNotice` make the revocation wiring. */
48
- deps: Pick<RunnerDeps, "onElicit" | "mcpImageResizer" | "onError" | "mcpRevocations" | "onNotice">;
47
+ * re-read every prepare); `mcpRevocations` + `onNotice` make the revocation wiring; `peerSeat` answers what each MCP / A2A request carries. */
48
+ deps: Pick<RunnerDeps, "onElicit" | "mcpImageResizer" | "onError" | "mcpRevocations" | "onNotice" | "peerSeat">;
49
49
  /** borrowed-readonly — the leg's mods bus: its `prompt.section` station disposes of each server's instructions at the dial. */
50
50
  modBus: LegModBus;
51
51
  /** borrowed-readonly — the run tree's MCP connection pool (the leg leases its connections from it) and whether THIS leg created it
@@ -59,6 +59,8 @@ export interface PrepareProtocolToolsInput {
59
59
  /** borrowed-mutable — the reminder-disclosure counters: the MCP intake's bounding writes them here, and
60
60
  * the run loop's attachment lanes keep writing the same object (`Prepared.reminderDisclosureCounts`). */
61
61
  reminderDisclosureCounts: Prepared["reminderDisclosureCounts"];
62
+ /** borrowed-readonly — the leg's request-meta seat: every minted MCP tool reads what stands for its call, and the leg's session id (`_meta`). */
63
+ mcpRequestMeta: import("../mcp-call-meta.js").McpLegMetaReader;
62
64
  /** borrowed-readonly — the run's invocation id (the revocation probe-failure notice names it). */
63
65
  runId: string;
64
66
  /** borrowed-readonly — the acquired session id (operator-line context). */
@@ -1,5 +1,5 @@
1
1
  import { Type } from "typebox";
2
- import { materializeMcpTools } from "../mcp.js";
2
+ import { materializeLegMcpTools } from "../mcp.js";
3
3
  import { applyMcpRosterDelta, commitMcpRosterChanges, redialMcpServer, rosterHolding, settledOnRoster } from "./mcp-redial.js";
4
4
  import { valveLeaves, valveLeavesPeer } from "../../agents/tool-filter.js";
5
5
  import { resourceFacesLeft } from "../mounted-mcp.js";
@@ -30,7 +30,7 @@ export async function prepareProtocolTools(input) {
30
30
  const leaves = valveLeaves(spec, toolFaceSnapshot.selector);
31
31
  const resourcesReached = resourceFacesLeft(leaves);
32
32
  const mcp = lockedPreflight.mcp?.length
33
- ? await materializeMcpTools(lockedPreflight.mcp, spec.principal, deps.onElicit, deps.mcpImageResizer, { reminderMark, counts: reminderDisclosureCounts }, mcpRevocationWiring(deps, runId), mcpPool === undefined ? undefined : { pool: mcpPool.pool, ownsPool: mcpPool.owned }, sectionDisposerOf(input.modBus, abortController.signal), (entry) => resourcesReached || serverReached(mintNamespacePrefix(MCP_NAMESPACE, entry.name)), AbortSignal.any([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]), hostFloor)
33
+ ? await materializeLegMcpTools(input.mcpRequestMeta, lockedPreflight.mcp, spec.principal, deps.onElicit, deps.mcpImageResizer, { reminderMark, counts: reminderDisclosureCounts }, mcpRevocationWiring(deps, runId), mcpPool === undefined ? undefined : { pool: mcpPool.pool, ownsPool: mcpPool.owned }, sectionDisposerOf(input.modBus, abortController.signal), (entry) => resourcesReached || serverReached(mintNamespacePrefix(MCP_NAMESPACE, entry.name)), AbortSignal.any([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]), hostFloor, deps.peerSeat)
34
34
  :
35
35
  { tools: [], toolAxes: [], warnings: [], serverInstructions: [], instructionsDelta: { pendingAdds: [], pendingRemovals: [] }, droppedTools: [], statuses: [], refresh: async () => [], reconnect: async (server) => ({ server, prefix: mintNamespacePrefix(MCP_NAMESPACE, server), outcome: "not_declared", reason: "this task declared no MCP servers", toolCount: 0, added: [], removed: [] }), dispose: async () => { } };
36
36
  if (lockedPreflight.mcp?.length)
@@ -167,7 +167,7 @@ export async function prepareProtocolTools(input) {
167
167
  foldProtocolAxes(mcp.toolAxes, "MCP");
168
168
  const a2aDeclared = lockedPreflight.a2a;
169
169
  const a2a = a2aDeclared
170
- ? await materializeA2aTools(a2aDeclared, spec.principal, abortController.signal, hostFloor)
170
+ ? await materializeA2aTools(a2aDeclared, spec.principal, abortController.signal, hostFloor, deps.peerSeat)
171
171
  : { tools: [], toolAxes: [], warnings: [], statuses: [], refresh: async () => [], dispose: async () => { } };
172
172
  if (a2aDeclared)
173
173
  rollback.push(function a2aDispose() { return a2a.dispose(); });
@@ -169,6 +169,8 @@ export interface PrepareSuspendSagaInput {
169
169
  placementRootResolved: string;
170
170
  /** borrowed-readonly — this leg's checkpoint scope (the driver's one `checkpointScopeOf` derivation; the row's `legScope` stamp). */
171
171
  checkpointScope: string;
172
+ /** borrowed-readonly — the config doors' one reading of the leg's run origin (the row's `runOrigin` stamp; absent ⇒ the host said nothing). */
173
+ runOrigin: SerializedCheckpointState["runOrigin"];
172
174
  /** borrowed-readonly — the tool-selector layers this leg was spawned under (the live seat, else the resumed row's), the row's `toolCeiling` stamp. */
173
175
  toolCeiling: readonly import("../tool-face.js").ToolSelectorLayer[] | undefined;
174
176
  /** borrowed-readonly — the spawning run's judgment of this leg's own lists, while it is bound to them (`boundToolListsJudgment`), the row's `toolListsJudged` stamp. */
@@ -82,7 +82,7 @@ function stampPlacementRootSessionId(placementRootResolved) {
82
82
  return placementValueOrAbsent(placementRootResolved);
83
83
  }
84
84
  export function prepareSuspendSaga(input) {
85
- const { gateMachineryActive, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection, reminderMark, handsCwdRef, handsRoot, handsHome, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors, inheritedPathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, toolCeiling, toolListsJudged, ownToolLists, externalContentTargetActive, crossBoundary, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter } = input;
85
+ const { gateMachineryActive, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection, reminderMark, handsCwdRef, handsRoot, handsHome, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors, inheritedPathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, runOrigin, toolCeiling, toolListsJudged, ownToolLists, externalContentTargetActive, crossBoundary, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter } = input;
86
86
  if (!gateMachineryActive)
87
87
  return { saga: undefined };
88
88
  const taskAccess = { owner: hostTaskId, scope: taskScope, sessionId };
@@ -178,6 +178,7 @@ export function prepareSuspendSaga(input) {
178
178
  placementRootSessionId: stampPlacementRootSessionId(placementRootResolved),
179
179
  externalContentTarget: externalContentTargetActive ? true : undefined,
180
180
  legScope: checkpointScope,
181
+ runOrigin,
181
182
  toolCeiling: toolCeiling !== undefined ? toolCeiling.map((l) => ({ ...(l.allow !== undefined ? { allow: persistedToolNameList(l.allow, "allowed") } : {}), deny: persistedToolNameList(l.deny, "denied") })) : undefined,
182
183
  toolListsJudged,
183
184
  ownToolLists: ownToolLists !== undefined ? { toolName: ownToolLists.toolName, ...(ownToolLists.definition !== undefined ? { definition: ownToolLists.definition } : {}), lists: ownToolLists.lists } : undefined,
@@ -11,6 +11,7 @@ import { callerToolMembership } from "../../agents/inherited-tool-pool.js";
11
11
  import { refuseLateRosterChanges, snapshotCallerRoster } from "./caller-roster.js";
12
12
  import { toolPolicyPathRules, toolPolicyWriteGuardRows } from "../tool-policy.js";
13
13
  import { dataRootSpellings } from "../sensitive-path-policy.js";
14
+ import { writeLocationOf } from "../../tools/worktree.js";
14
15
  import { bindPathRules, createHeadLeads } from "../path-rule-binding.js";
15
16
  import { whereItsAnsweredPrefixLeads } from "../../tools/fs/read-deny-home.js";
16
17
  import { loadAnnounceOnceLedger } from "./announce-once-ledger.js";
@@ -99,13 +100,16 @@ import { handsWriteHalfMounts } from "../../tools/fs/index.js";
99
100
  import { askSeatEffective } from "../wiring-manifest.js";
100
101
  import { durableParkGapFor } from "../park-selfcheck.js";
101
102
  import { createToolCallEntry, createToolCallStation } from "../mods/tool-call.js";
103
+ import { createMcpRequestMetaSeat } from "../mcp-call-meta.js";
102
104
  import { deliverEngineNotice } from "../types.js";
103
105
  import { toolCallFaceOf, ToolRosterDeltaSeat } from "../tool-roster.js";
104
106
  import { mountedMcpOf } from "../mounted-mcp.js";
105
107
  import { McpConnectionPool } from "../mcp-connection-pool.js";
106
108
  import { rosterCanPersistMemory } from "../tool-registry.js";
107
- import { AdvertisedWritableDirs } from "./advertised-writable-dirs.js";
109
+ import { AdvertisedWritableDirs, checkedPlanFileShape, planFileInvalid, planFileShown } from "./advertised-writable-dirs.js";
108
110
  import { resolveTaskRootCanonical } from "./task-root-canonical.js";
111
+ import { projectMarkerFsOf, resolveSessionProject } from "../memory-engine/scope-contract.js";
112
+ import { createWorkspaceFrameSeat } from "../workspace-snapshot.js";
109
113
  import { createStructuredProjector } from "./tool-output-projection.js";
110
114
  import { toolResultMediaRefusedSeat } from "./tool-result-media-seat.js";
111
115
  import { asThrownError, thrownText } from "../thrown-value.js";
@@ -309,6 +313,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
309
313
  })();
310
314
  if (modePolicyOf(declaredModeAtDoor).enablePlanMode)
311
315
  spec = { ...spec, enablePlanMode: true };
316
+ checkedPlanFileShape(spec.planFile);
312
317
  const { toolFaceLists, promptLean, promptTraits, promptHost, promptBinding, lockedPreflight, resolvedInteractionPosture, microCompactKnob, resolvedRole, model, thinking, compModel, memoryDelegationEvidence, memoryProvenance, memoryCapturePolicy, usageWindows, brainCallGuardrailRef, brainCallGuardrailMs } = doors;
313
318
  announceToolModelGate(deps.onNotice, model.id, doors.modelGate);
314
319
  const modelGateManifest = toolModelGateManifest(doors.modelGate);
@@ -439,7 +444,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
439
444
  }
440
445
  }
441
446
  const ownedEnv = ownedEnvSeat.current;
442
- const { taskRootFinal, rebaseRestoredPath } = await prepareWorkspaceRestore({ ownedEnv, deps, spec, internals, resume, taskRootInitial, placement, abortController, sessionId });
447
+ const { taskRootFinal, rebaseRestoredPath, remote: workspaceRemote } = await prepareWorkspaceRestore({ ownedEnv, deps, spec, internals, resume, taskRootInitial, placement, abortController, sessionId });
443
448
  const { canonical: taskRootCanonical } = await resolveTaskRootCanonical({ env: executionEnv, given: taskRootFinal, onNotice: deps.onNotice, sessionId, runId });
444
449
  const legHome = validatePath(executionEnv.homeDir, { intent: "validate-coordinate" });
445
450
  const legAnchors = { root: taskRootCanonical, ...(legHome !== undefined ? { home: legHome } : {}) };
@@ -476,11 +481,15 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
476
481
  const effectivePathDenyRules = policyDenyRows.filter((r) => r.unanchored === undefined);
477
482
  const writeTargetJudgeRef = {};
478
483
  const legExemptRoots = Object.freeze(dataRootSpellings(deps.memoryEngineDir));
479
- const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]) };
484
+ const { seat: worktreeSeat, writeLocation, checkout } = writeLocationOf({ spelled: taskRootFinal, canonical: taskRootCanonical });
485
+ const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]), checkout };
480
486
  const sideCallBookRef = {};
481
- const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, enterPlanMode, permissionMode, readDenyEntries: () => personRows.tablesReady().then(() => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: pathTables?.ruleRows() ?? effectivePathDenyRules })), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
487
+ const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, requestReview, ...(spec.planFile !== undefined ? { planFileSource: { path: spec.planFile, shown: planFileShown(spec.planFile), read: (signal) => advertisedWritableDirs?.readPlanFile(signal) ?? Promise.resolve({ ok: false, reason: "this run admitted no plan file" }) } } : {}), enterPlanMode, permissionMode, readDenyEntries: () => personRows.tablesReady().then(() => ({ entries: readDenyMatcher?.entries ?? [], ruleRows: pathTables?.ruleRows() ?? effectivePathDenyRules })), peerLaneActive, peerSendMessageBuiltIn, runnerSelf, memoryEngineSession: () => memoryEngineSession, centerAdoption: () => centerAdoptionRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
482
488
  const tools = roster.tools;
483
489
  const crossBoundary = await prepareCrossBoundaryLane({ token: crossBoundaryTree, posture: doors.crossBoundaryPosture, externalContentTargetActive, env: executionEnv, session, resumeLeg: resume !== undefined, sessionId, runId, hostTaskId, deps });
490
+ const sessionProject = await resolveSessionProject(projectMarkerFsOf(executionEnv), taskRootCanonical, spec.projectId);
491
+ if (sessionProject.markerFault !== undefined)
492
+ deps.onError?.(sessionProject.markerFault, { phase: "config", sessionId });
484
493
  const pausedRef = {};
485
494
  const undeliveredContinuationRef = { current: { parkedSteers: [], orphanTasks: [] } };
486
495
  const remoteEnvFailures = [];
@@ -540,9 +549,12 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
540
549
  roster.mount(createOutputTool(outputRef, spec.outputSchema, compiled.strict ? compiled.modelSchema : undefined), { source: "synthetic", mountedBy: "optional" });
541
550
  }
542
551
  const rosterSeat = new ToolRosterDeltaSeat();
543
- const { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, mcpRedial } = await prepareProtocolTools({ lockedPreflight, hostFloor: doors.hostFloor, spec, deps, modBus: legMods.bus, ...(mcpPool !== undefined ? { mcpPool } : {}), reminderMark, reminderDisclosureCounts, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback });
552
+ const mcpRequestMeta = createMcpRequestMetaSeat(sessionId);
553
+ const { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, mcpRedial } = await prepareProtocolTools({ lockedPreflight, hostFloor: doors.hostFloor, spec, deps, modBus: legMods.bus, ...(mcpPool !== undefined ? { mcpPool } : {}), reminderMark, reminderDisclosureCounts, mcpRequestMeta, runId, sessionId, onceLedger, roster, rosterSeat, remoteToolOffload, toolFaceSnapshot, toolEffects, axisExplicitNegatives, irreversibilityTier, irreversibleTools, egressTools, toolMarkSources, abortController, rollback });
544
554
  const callIssuedAtRef = {};
545
555
  const workCutRef = { continuation: false, abortedBeforeTurnEnd: false };
556
+ if (spec.planFile !== undefined && (!handsEnabled || spec.handsReadOnly === true))
557
+ throw planFileInvalid(spec.planFile, handsEnabled ? "is declared on a leg whose hands are read-only (handsReadOnly), so no file tool can write it" : "is declared on a leg with no execution environment, so no file tool can write it");
546
558
  const advertisedWritableDirs = handsEnabled
547
559
  ? new AdvertisedWritableDirs(executionEnv, (dir, reason) => deps.onError?.(new Error(`${dir.advertiser} advertised writable directory skipped: ${dir.path} — ${reason}`), { phase: "config", sessionId }), taskRootCanonical, [...(spec.additionalDirectories ?? []), ...(spec.additionalReadDirectories ?? [])])
548
560
  : undefined;
@@ -571,6 +583,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
571
583
  sessionId,
572
584
  ...(captureLineage.own !== undefined ? { sessionIncarnation: captureLineage.own } : {}),
573
585
  taskRootPath: taskRootFinal,
586
+ sessionProject,
574
587
  reminderMark,
575
588
  writeToolsMounted: (handsWriteHalfPlanned || tools.some((t) => t.name === "Write")) &&
576
589
  valveLeaves(spec, toolFaceSnapshot.selector)({ name: "Write" }) &&
@@ -619,7 +632,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
619
632
  internals.ownOrgAdmissionRef.current = ownOrgVerdictRef.current;
620
633
  }
621
634
  const modelFileReaderSeat = {};
622
- const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences };
635
+ const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences, writeLocation };
623
636
  const handsReadFace = handsEnabled ? await prepareHandsMount(handsReadFaceInput) : resolveHandsLessReadFace(handsReadFaceInput);
624
637
  const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, shellReadLandings, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, envHandToolNames, sealReadStateSeat } = handsReadFace;
625
638
  resolvedReadFace = handsReadFace.resolvedReadFace;
@@ -629,7 +642,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
629
642
  handsLessResolvedWriteFace = handsReadFace.handsLessResolvedWriteFace;
630
643
  shellGatedTools = handsReadFace.shellGatedTools;
631
644
  await armAutoMode();
632
- const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle });
645
+ const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
633
646
  const { liveQuestionFace, contentAskBindings, contentAskRoutable, lateStrandedAnswers, discloseStrandedAnswers, settleContentAskBindings, durableQuestionFace, questionToolMounted, mountedQuestionTool } = prepareQuestionFace({ frozenOnQuestion, spec, deps, checkpointStore, runtimeCaps, resolvedInteractionPosture, resume, sessionId, roster, toolFaceSnapshot, inheritedUnavailableAsks: () => inheritedUnavailableAsks });
634
647
  if (spec.handsReadOnly !== true) {
635
648
  const sessionScope = sessionId ?? spec.principal ?? spec.taskId ?? "default";
@@ -789,9 +802,9 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
789
802
  releaseSignal = () => sig.removeEventListener("abort", onExternalAbort);
790
803
  }
791
804
  }
792
- const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedToolChecks } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, readFace: () => resolvedReadFace, permissionMode, scratchpadDir: spec.envFacts?.scratchpadDir, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
793
- const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, harness, pausedRef, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest });
794
- toolCallStationRef.current = createToolCallStation({ bus: legMods.bus, occurrences: toolOccurrences, blockedToolCalls, identity: hookIdentity, reminderMark });
805
+ const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, askSourceIdentity, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedToolChecks } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, internals, sessionId, runId, hostTaskId, taskRootFinal, additionalRootsCanonical, writeLocation, executionEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { leg: legAnchors, chainTop }, headLeads, tools, harnessTools, selector: toolFaceSnapshot.selector, toolEffects, egressTools, irreversibilityTier, axisExplicitNegatives, shellGatedTools, toolMarkSources, envHandToolNames, handsCwdRef, readDenyMatcher, personRows, questionToolMounted, runtimeCaps, inheritedAncestorRules, ancestorSessionRulesRef, inheritedParentConstraints, seedInheritedGate, skillGrants, skillSpecs, allowedToolTables, frozenOnAsk, hookEnvSource, notifyOwnHookCrash, modBus: legMods.bus, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, readFace: () => resolvedReadFace, permissionMode, toolRosterDeltas: rosterSeat, stopForDenialLimit, delegation, abortController, now, ownSessionRulesRef });
806
+ const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, incompleteSuspendAdapter, durableSuspendInfraReady, resourceSuspendEligible, usageGovernance, durableApproval, wiringManifest, writeProtection, parkLaneArmed, gateMachineryActive, hookIdentity, hookEnvFace, sessionBoxBound } = prepareWiringManifest({ spec, deps, askSeat: doors.askSeat, hostFloorPosture: doors.hostFloor?.posture, crossBoundaryStationEngaged: crossBoundary.stationEngaged, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus: legMods.bus, standingModBus: legMods.standing, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard: advertisedWritableDirs?.planFile !== undefined ? { ...legWriteGuard, exemptFiles: [advertisedWritableDirs.planFile] } : legWriteGuard, mcp, irreversibleTools, egressTools, shellReadStationArmed: handsReadFace.shellReadStationArmed, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, harness, pausedRef, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest, runOrigin: doors.runOrigin });
807
+ toolCallStationRef.current = createToolCallStation({ bus: legMods.bus, occurrences: toolOccurrences, blockedToolCalls, identity: hookIdentity, reminderMark, requestMeta: mcpRequestMeta });
795
808
  const writeProtectionCheck = writeProtection.mount?.check;
796
809
  writeTargetJudgeRef.current = writeProtection.judgeWriteTarget;
797
810
  if (fileHistoryBoundary !== undefined) {
@@ -804,7 +817,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
804
817
  const stampCallTarget = attachmentRootCanonical === undefined ? undefined : legCallTargetStamp({ env: executionEnv, root: attachmentRootCanonical, cwd: () => handsCwdRef?.current, judgesPaths: () => parkLaneArmed || effectivePolicy?.pathRules !== undefined || basePolicyForResumeEdit?.pathRules !== undefined || permissionRuleLane !== undefined || skillSpecs.some((s) => compileSkillGrant(s, "model").rows.some((r) => r.compiled.kind === "path")) || allowedToolTables.request.holdsPathRows() || allowedToolTables.deployment.holdsPathRows(), leads: () => headLeads.resolve([...toolPolicyPathRules([effectivePolicy, basePolicyForResumeEdit, ...(inheritedParentConstraints ?? []).map((c) => c.policy)], legAnchors), ...bindPathRules(listPathRows().map((rule) => ({ parsed: rule, ruleText: rule.rule })), legAnchors)]) });
805
818
  const { askLane } = prepareAskLane({ gateMachineryActive, abortController, effectivePolicy, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, advertisedWritableDirs, exemptRoots: legExemptRoots, tools, inheritedUnavailableAsks, inheritedAskGrants, onAsk, humanReviewRef, now, ruleOffersOf, grantBindingOf, askSourceIdentity, riskAxesOf, autoModeDenialTracking: autoModeDenialTrackingRef, spec, deps, sessionId, runId, modBus: legMods.bus, notifyOwnHookCrash, grantReadRoot: handsReadFace.grantReadRoot });
806
819
  const inheritedAnchorRecords = chainAnchorRecords(chainTop, inheritedParentConstraints ?? []);
807
- const { saga } = prepareSuspendSaga({ gateMachineryActive, crossBoundary, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection: () => legMods.skillScopes.frozen(), reminderMark, handsCwdRef, handsRoot: attachmentRootCanonical, handsHome: attachmentRootCanonical !== undefined ? legAnchors.home : undefined, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors: chainTop !== legAnchors ? inheritedAnchorRecords.pathRuleAnchors : undefined, inheritedPathRuleInstallations: inheritedAnchorRecords.pathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, toolCeiling: toolCeilingRead, toolListsJudged, ownToolLists, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
820
+ const { saga } = prepareSuspendSaga({ gateMachineryActive, crossBoundary, abortController, harness, checkpointStore, deps, sessionId, hostTaskId, taskScope, liveSpendRef, resume, nestedStats, internals, activeTools, outputRef, readFileStateForCheckpoint, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, skillScopesCheckpointSection: () => legMods.skillScopes.frozen(), reminderMark, handsCwdRef, handsRoot: attachmentRootCanonical, handsHome: attachmentRootCanonical !== undefined ? legAnchors.home : undefined, worktreeSessionRef, undeliveredContinuationRef, inheritedParentConstraints, seedInheritedGate, ancestorRulesNow, inheritedShellGate, permissionMode, inheritedAdmittedOrgScopes, inheritedPathRuleAnchors: chainTop !== legAnchors ? inheritedAnchorRecords.pathRuleAnchors : undefined, inheritedPathRuleInstallations: inheritedAnchorRecords.pathRuleInstallations, ownOrgVerdictRef, orgGovernedProvenance, announcedListingsRef, gitStatusRef, hookIdentity, placementRootResolved, checkpointScope, runOrigin: doors.runOrigin, toolCeiling: toolCeilingRead, toolListsJudged, ownToolLists, externalContentTargetActive, remoteEnvFailures, memoryEngineSession, suspendLoopRef, ownedEnv, incompleteSuspendAdapter });
808
821
  const { suspendForResource, suspendForPlatformLimit, suspendForReview } = prepareBoundaryParks({ saga, spec, checkpointStore, checkpointScope, abortController, harness, session, sessions, sessionId, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, incompleteSuspendAdapter });
809
822
  const { parkAsk } = prepareParkAsk({ askLane, saga, spec, deps, sessionId, checkpointStore, checkpointScope, toolRosterDeltas: rosterSeat, parkLaneArmed, contentAskRoutable, liveQuestionFace, mountedQuestionTool, contentAskBindings, lateStrandedAnswers, discloseStrandedAnswers, onAsk, runtimeCaps, inheritedUnavailableAsks, basePolicyForResumeEdit, budgetSnapshot, handsCwdRef, handsRoot: attachmentRootCanonical, stampCallTarget, shellReadLandings, advertisedWritableDirs, exemptRoots: legExemptRoots, offloadStore, ownedEnv, incompleteSuspendAdapter, session, sessions, suspendChainBase, maxSuspends, remoteEnvFailures, shellGatedTools, irreversibilityTier, toolMarkSources, effectiveShellGate, durableApproval, priorLedger, liveSpendRef, resourceTotal, ruleOffersOf, grantBindingOf, now, humanReviewRef, abortController, harness, pausedRef });
810
823
  const seatInputsFor = skillGateWiring({ tools, skillToolName: SKILL_TOOL_NAME, seatOf: skillSeatOf, mode: () => permissionMode.current, lane: skillGrantLane, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.skill_allowed", version: 1, taskId: hostTaskId, ...info, entries: [...info.entries], ts: Date.now() })), allowEntries: { deploymentAllows: { ...allowEntryLanes.deployment, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "deployment", ...info, entries: [...info.entries], ts: Date.now() })) }, requestAllows: { ...allowEntryLanes.request, onAllowed: (info) => emitTrace(deps.tracer, () => ({ kind: "permission.allowed_tools_allowed", version: 1, taskId: hostTaskId, source: "request", ...info, entries: [...info.entries], ts: Date.now() })) } } });
@@ -814,7 +827,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
814
827
  const preparedHolder = {};
815
828
  const { cacheBreakDetector, cacheFingerprint, promptOverheadTokens, compactionRestore, normalizeAttachmentPath, isDedupStubResult, recentlyReadFiles, onCompactionApplied, detectExternalChanges, syntheticReadVerdict, consolidationWriteJudge, listBackgroundTasks, centerCompactionCandidate, effectiveReadFaceObserved, effectiveWriteFaceObserved, effectiveReadDenyObserved } = prepareTurnWiring({ deps, systemPromptSeat, harnessTools, fpRef, model, promptIdentityDigest: promptManifest.identity.artifact, systemBlocks, thinking, spec, sessionId, turnSnapshotRef, promptManifest, charsPerToken, handsEnabled, executionEnv, attachmentRootCanonical, readRoots, modelFileReader: modelFileReaderSeat.current, reminderMark, reminderDisclosureCounts, resolvedReadFace, handsCwdRef, readFileStateForCheckpoint, denyNarrowingPolicy, skillGrants: skillGrantLane, callerPolicy: installedToolPolicy, inheritedPolicies: (inheritedParentConstraints ?? []).map((c) => c.policy), persistedRuleLane: permissionRuleLane, ruleLaneFacts, personRowsBeyondRun, orgRuleLane: permissionRuleOrgLane, stampCallTarget, abortController, hostTaskId, taskScope, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef, harnessRef, carrierReadFace, carrierWriteFace, readDenyAdditionsNormalized, preparedHolder });
816
829
  await onceLedger.settle(session, announcedListingsRef);
817
- const buildPrepared = () => ({ harness, session, sessionId, runId, crossBoundary, ...(doors.hostFloor !== undefined ? { hostFloor: doors.hostFloor } : {}), registryAccess: { owner: hostTaskId, scope: taskScope }, reminderMark, reminderDisclosureCounts, fullShellReachable, approvalPosture: { get mode() { return permissionMode.current; }, askEffective: askSeatEffective(wiringManifest) }, ...(outputStyleFrame !== undefined ? { outputStyleFrame } : {}), permissionMode, editedFilesSnapshot, taskRootPath: taskRootFinal, model, thinking, compModel: effectiveCompModel, mcp, ...(mcpRedial !== undefined ? { mcpRedial } : {}), ...(a2a.tools.length > 0 ? { a2a } : {}), blockedRef, outputRef, abortController, conflictRef, blockedToolCalls, toolOccurrences, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, ...(attachmentRootCanonical !== undefined ? { handsRoot: attachmentRootCanonical } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), exemptRoots: legExemptRoots, ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), consolidationWriteJudge, ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, promptIdentity, activeTools, ...(deferred.size > 0 ? { deferredToolNames: deferred } : {}), toolMaterializeStatic, deferDirectCall, ...(staticFaceForRef.current !== undefined ? { staticFaceFor: staticFaceForRef.current } : {}), ownedEnv, pausedRef, undeliveredContinuationRef, suspendProgressRef, remoteEnvFailures, reviewRequestRef, suspendLoopRef, suspendForResource, ...(suspendForPlatformLimit !== undefined ? { suspendForPlatformLimit } : {}), ...(envLifetimeSuspendAt !== undefined ? { envLifetimeSuspendAt } : {}), ...(usageGovernance !== undefined ? { usageGovernance } : {}), callIssuedAtRef, workCutRef, brainCallGuardrailRef, gateStopRef, stopForDenialLimit, suspendForReview, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}), resourceLedger: priorLedger, liveSpendRef, humanReviewRef, now, tools, toolRoster, toolRosterDeltas: rosterSeat, structuredProjector, toolEffects, wakeRecovered, promptOverheadTokens, lastBrainContext, lastSentRequest: () => lastBrainContextRef.current, ...(advisor.instruction !== undefined ? { advisorInstruction: advisor.instruction } : {}), ...(compactionRestore !== undefined ? { compactionRestore } : {}), recentlyReadFiles, normalizeAttachmentPath, isDedupStubResult, ...(onCompactionApplied ? { onCompactionApplied } : {}), compactionReuseRef, trimPressureRef, microCompact, ...(memoryEngineSession ? { memoryEngineSession } : {}), ...(subagentRetain ? { subagentRetain } : {}), ...(lspDiagnostics && nudgeLspOnEdit && withheldDiagnosticsOf ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent, withheldOf: withheldDiagnosticsOf } } : {}), stopRequestedRef, announcedSnapshotRecovered: onceLedger.recovered, ...(dateChange ? { dateChange } : {}), ...(instructionSources ? { instructionSources } : {}), ...(projectInstructionContent !== undefined ? { projectInstructionContent } : {}), ...(workflowSizeGuideline ? { workflowSizeGuideline } : {}), ...(detectExternalChanges ? { detectExternalChanges } : {}), ...(toolsDeltaRef ? { toolsDeltaRef } : {}), ...(mcpUnavailable ? { mcpUnavailable } : {}), ...(agentListing ? { agentListing } : {}), ...(skillsListing ? { skillsListing } : {}), announcedListingsRef, frameReceipts: { pending: [], listingSnapshotOwed: false }, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, modBus: legMods.bus, sideCallBookRef, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(shellReadLandings !== undefined ? { shellReadLandings } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}), ...(toolCallStationRef.current !== undefined ? { toolCallStation: toolCallStationRef.current } : {}) });
830
+ const buildPrepared = () => ({ harness, session, sessionId, runId, crossBoundary, ...(doors.hostFloor !== undefined ? { hostFloor: doors.hostFloor } : {}), registryAccess: { owner: hostTaskId, scope: taskScope }, reminderMark, reminderDisclosureCounts, fullShellReachable, approvalPosture: { get mode() { return permissionMode.current; }, askEffective: askSeatEffective(wiringManifest) }, ...(outputStyleFrame !== undefined ? { outputStyleFrame } : {}), permissionMode, editedFilesSnapshot, taskRootPath: taskRootFinal, model, thinking, compModel: effectiveCompModel, mcp, ...(mcpRedial !== undefined ? { mcpRedial } : {}), ...(a2a.tools.length > 0 ? { a2a } : {}), blockedRef, outputRef, abortController, conflictRef, blockedToolCalls, toolOccurrences, batchHaltRef, nestedStats, ...(rewindNotes.length > 0 ? { rewindNotes } : {}), ...(fileHistoryBoundary !== undefined ? { fileHistoryBoundary } : {}), ...(effectiveReadFaceObserved !== undefined ? { effectiveReadFace: effectiveReadFaceObserved, effectiveWriteFace: effectiveWriteFaceObserved } : {}), ...(effectiveReadDenyObserved !== undefined ? { effectiveReadDenyPatterns: effectiveReadDenyObserved } : {}), effectiveMemoryScopes: memoryEffectiveScopes, cwdRef: handsCwdRef, ...(attachmentRootCanonical !== undefined ? { handsRoot: attachmentRootCanonical } : {}), ...(stampCallTarget !== undefined ? { stampCallTarget } : {}), toolProgressRef, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), exemptRoots: legExemptRoots, ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), workspaceFrame: createWorkspaceFrameSeat({ root: taskRootCanonical, ...(handsCwdRef !== undefined ? { cwdRef: handsCwdRef } : {}), ...(worktreeSessionRef !== undefined ? { worktreeSessionRef } : {}), ...(sessionProject.project !== undefined ? { project: sessionProject.project } : {}), remote: workspaceRemote }), ...(workspaceStateSettle !== undefined ? { workspaceStateSettle } : {}), ...(sealReadStateSeat !== undefined ? { sealReadStateSeat } : {}), denyNarrowingPolicy, skillGrants: skillGrantLane, skillSpecs, ...(permissionRuleLane !== undefined ? { persistedRuleLane: permissionRuleLane } : {}), ...(basePolicyForResumeEdit !== undefined ? { basePolicyForResumeEdit } : {}), consolidationWriteJudge, ...(permissionRuleOrgLane !== undefined ? { permissionRuleOrg: permissionRuleOrgLane } : {}), releaseSignal, endModeCeiling, settleContentAskBindings, cacheBreakDetector, cacheFingerprint, wiringManifest, promptManifest, promptIdentity, activeTools, ...(deferred.size > 0 ? { deferredToolNames: deferred } : {}), toolMaterializeStatic, deferDirectCall, ...(staticFaceForRef.current !== undefined ? { staticFaceFor: staticFaceForRef.current } : {}), ownedEnv, pausedRef, undeliveredContinuationRef, suspendProgressRef, remoteEnvFailures, reviewRequestRef, suspendLoopRef, suspendForResource, ...(suspendForPlatformLimit !== undefined ? { suspendForPlatformLimit } : {}), ...(envLifetimeSuspendAt !== undefined ? { envLifetimeSuspendAt } : {}), ...(usageGovernance !== undefined ? { usageGovernance } : {}), callIssuedAtRef, workCutRef, brainCallGuardrailRef, gateStopRef, stopForDenialLimit, suspendForReview, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}), resourceLedger: priorLedger, liveSpendRef, humanReviewRef, now, tools, toolRoster, toolRosterDeltas: rosterSeat, structuredProjector, toolEffects, wakeRecovered, promptOverheadTokens, lastBrainContext, lastSentRequest: () => lastBrainContextRef.current, ...(advisor.instruction !== undefined ? { advisorInstruction: advisor.instruction } : {}), ...(compactionRestore !== undefined ? { compactionRestore } : {}), recentlyReadFiles, normalizeAttachmentPath, isDedupStubResult, ...(onCompactionApplied ? { onCompactionApplied } : {}), compactionReuseRef, trimPressureRef, microCompact, ...(memoryEngineSession ? { memoryEngineSession } : {}), ...(subagentRetain ? { subagentRetain } : {}), ...(lspDiagnostics && nudgeLspOnEdit && withheldDiagnosticsOf ? { lspDiagnostics: { registry: lspDiagnostics, nudge: nudgeLspOnEdit, runIdent: lspRunIdent, withheldOf: withheldDiagnosticsOf } } : {}), stopRequestedRef, announcedSnapshotRecovered: onceLedger.recovered, ...(dateChange ? { dateChange } : {}), ...(instructionSources ? { instructionSources } : {}), ...(projectInstructionContent !== undefined ? { projectInstructionContent } : {}), ...(workflowSizeGuideline ? { workflowSizeGuideline } : {}), ...(detectExternalChanges ? { detectExternalChanges } : {}), ...(toolsDeltaRef ? { toolsDeltaRef } : {}), ...(mcpUnavailable ? { mcpUnavailable } : {}), ...(agentListing ? { agentListing } : {}), ...(skillsListing ? { skillsListing } : {}), announcedListingsRef, frameReceipts: { pending: [], listingSnapshotOwed: false }, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, hookIdentity, modBus: legMods.bus, sideCallBookRef, ...(sessionBoxBound !== undefined ? { sessionBox: sessionBoxBound } : {}), ...(turnSnapshotRef.current !== undefined ? { turnSnapshot: turnSnapshotRef.current } : {}), ...(centerCompactionCandidate !== undefined ? { centerCompactionCandidate } : {}), ...(shellReadCheck !== undefined ? { shellReadCheck } : {}), ...(shellReadLandings !== undefined ? { shellReadLandings } : {}), ...(toolDisclosureSeat !== undefined ? { toolDisclosure: toolDisclosureSeat } : {}), ...(approvedCallScreen !== undefined ? { approvedCallScreen } : {}), ...(toolCallStationRef.current !== undefined ? { toolCallStation: toolCallStationRef.current } : {}) });
818
831
  refuseLateRosterChanges(callerRoster.roster);
819
832
  rollback.commit();
820
833
  commitModeSeats(abortController.signal);
@@ -129,6 +129,7 @@ export interface PrepareWiringManifestInput {
129
129
  /** borrowed-readonly — from the file-history phase's one fold of the two off switches: the manifest's word, relayed. */ fileHistoryFact: NonNullable<WiringManifest["fileHistory"]>; /** borrowed-readonly — from the project-context phase: did it call the deployment's seam (the arm's own predicate), relayed. */
130
130
  projectMemoryFact: NonNullable<WiringManifest["projectMemory"]>;
131
131
  /** borrowed-readonly — from the policy-chain phase: this leg's own session-rule layer published its key for the children's chain (`ownSessionRulesRef.current !== undefined`), relayed as `sessionRules.childrenReadLive`. */ sessionRulesChildrenReadLive: boolean;
132
+ /** borrowed-readonly — the config doors' one reading of the leg's run origin, relayed into `leg` (absent ⇒ the host said nothing). */ runOrigin: NonNullable<WiringManifest["leg"]>["runOrigin"];
132
133
  /** borrowed-readonly — the advisor phase's answer, relayed. */ advisorFact?: WiringManifest["advisor"]; /** borrowed-readonly — the config doors' compiled host floor's posture, relayed (absent ⇒ none declared). */
133
134
  hostFloorPosture: WiringManifest["hostFloor"];
134
135
  /** borrowed-readonly — the arming outcome the caps phase reads live (the manifest's auto-mode face at this leg's start). */
@@ -117,7 +117,7 @@ function announceDurableGateUnavailable(args) {
117
117
  });
118
118
  }
119
119
  export function prepareWiringManifest(input) {
120
- const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, sessionBox, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture } = input;
120
+ const { spec, deps, internals, resume, sessionId, runId, hostTaskId, taskScope, modBus, standingModBus, checkpointScope, policyLayers, effectivePolicy, handsEnabled, taskRootFinal, legWriteGuard, mcp, irreversibleTools, egressTools, toolEffects, ownedEnv, executionEnv, offloadStore, onceLedger, usageWindows, envLifetimeSuspendAt, runtimeCaps, resolvedInteractionPosture, durableQuestionFace, liveQuestionFace, checkpointStore, sessions, modelGateManifest, autoModeArmReason, permissionMode, lockedPreflight, peerLaneRefs, frameSettlement, sessionBox, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin } = input;
121
121
  const onAsk = askSeat.value;
122
122
  const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name);
123
123
  const hasEffectAwareGate = policyLayers.length > 0 || chainJudges(standingModBus);
@@ -182,7 +182,7 @@ export function prepareWiringManifest(input) {
182
182
  const wiringQuestionStripped = internals?.questionFaceStripped === true;
183
183
  const wiringManifest = deriveWiringManifest({
184
184
  half: "effective",
185
- leg: resume !== undefined ? "resume" : internals?.isDelegatedChild === true ? "child" : "root",
185
+ leg: resume !== undefined ? "resume" : internals?.isDelegatedChild === true ? "child" : "root", ...(runOrigin !== undefined ? { runOrigin } : {}),
186
186
  teamRole: teamRoleOf({ isDelegatedChild: delegation.isDelegatedChild, ...(internals?.explicitAgentName !== undefined ? { spawnName: internals.explicitAgentName } : {}) }),
187
187
  ...(spec.peerPresence !== undefined ? { peerPresence: spec.peerPresence } : {}),
188
188
  askForm: askSeat.form,
@@ -52,6 +52,9 @@ export interface PrepareWorkspaceRestoreResult {
52
52
  * spelling of the old root); the identity function when no divergence was armed. Consumers (T7):
53
53
  * the readFileState checkpoint seed, the handsCwd seed, the activeWorktree restore. */
54
54
  rebaseRestoredPath: (p: string) => string;
55
+ /** owned — the leg's ONE remoteness reading: its paths name locations in a remote / non-host env (read by the
56
+ * observation sink below and the leg's `workspace_changed` frame alike). */
57
+ remote: boolean;
55
58
  }
56
59
  /** The B-4 phase body — the workspace-restore slice, verbatim (see the module header for the contract). */
57
60
  export declare function prepareWorkspaceRestore(input: PrepareWorkspaceRestoreInput): Promise<PrepareWorkspaceRestoreResult>;
@@ -107,19 +107,19 @@ export async function prepareWorkspaceRestore(input) {
107
107
  }
108
108
  }
109
109
  }
110
+ const workspaceEnv = ownedEnv ?? deps.executionEnv;
111
+ const remote = workspaceEnv !== undefined && workspaceEnv !== null && (isRemoteExecutionEnv(workspaceEnv) || workspaceEnv.hostLocalPaths === false);
110
112
  if (internals?.onWorkspaceResolved !== undefined) {
111
113
  try {
112
- const workspaceEnv = ownedEnv ?? deps.executionEnv;
113
114
  internals.onWorkspaceResolved({
114
115
  cwd: taskRootPath,
115
116
  isolated: internals.isolation === "worktree",
116
- remote: workspaceEnv !== undefined &&
117
- (isRemoteExecutionEnv(workspaceEnv) || workspaceEnv.hostLocalPaths === false),
117
+ remote,
118
118
  ...(input.placement !== undefined ? { placement: input.placement } : {}),
119
119
  });
120
120
  }
121
121
  catch {
122
122
  }
123
123
  }
124
- return { taskRootFinal: taskRootPath, rebaseRestoredPath };
124
+ return { taskRootFinal: taskRootPath, rebaseRestoredPath, remote };
125
125
  }
@@ -49,7 +49,7 @@ export async function resumeAdmission(input) {
49
49
  const resumeSignal = config.signal;
50
50
  let suppliedMessage;
51
51
  refuseRetiredModeSeed(cp.state);
52
- config = refuseResumeDoors(config, cp.state.inheritedGate, runner.deps, sessions, internals?.holder);
52
+ config = refuseResumeDoors(config, cp.state, runner.deps, sessions, internals?.holder);
53
53
  const parkedSteers = readPendingSteerQueue(cp.state);
54
54
  if (outcomeGate === "wake") {
55
55
  suppliedMessage = outcome.message;
@@ -10,6 +10,7 @@ import { chainInstallationGaps, chainInstallationRefusal } from "./child-tree.js
10
10
  import { screeningInstallationsOf, unraisableGuardsOf } from "../mods/stations.js";
11
11
  import { refusePersistedToolNames, refuseRenamedDelegationMounts } from "./sub-agent-deny-lists.js";
12
12
  import { asResumeConfigRefusal } from "../mode-policy.js";
13
+ import { screenRecordedRunOrigin } from "../run-origin.js";
13
14
  export function resumeCheckpointScreen(input) {
14
15
  const { cp, resumeSignal, internals, tools, runner } = input;
15
16
  const { realApproval: realApprovalRow, face: faceRow, f012: f012Row } = CHECKPOINT_FEATURES;
@@ -91,6 +92,7 @@ export function resumeCheckpointScreen(input) {
91
92
  "(the checkpoint stays pending and is resumable without it).");
92
93
  }
93
94
  asResumeConfigRefusal("inheritedGate", () => refusePersistedToolNames((internals?.toolCeiling ?? undefined) === undefined ? cp.state.toolCeiling : undefined, cp.state.inheritedGate?.constraintChain, (internals?.ownToolLists ?? undefined) === undefined ? cp.state.ownToolLists : undefined));
95
+ asResumeConfigRefusal("inheritedGate", () => void screenRecordedRunOrigin(cp.state.runOrigin));
94
96
  asResumeConfigRefusal("taskConfig", () => refuseRenamedDelegationMounts(tools));
95
97
  if (cp.state.inheritedGate?.requiresParentConstraint === true) {
96
98
  const supplied = internals?.inheritedGate?.parentConstraints?.length ?? 0;
@@ -34,13 +34,12 @@ export interface RunHarnessHandlersResult {
34
34
  type: "tool_execution_end";
35
35
  }>) => void;
36
36
  onTurnEnd: () => void;
37
- /** The single workspace_changed mint (cwd diff vs the closure's dedupe state); the run body
37
+ /** The leg's workspace-frame observation (`Prepared.workspaceFrame.observe`); the run body
38
38
  * calls it after a resume's approved-call resolution, which bypasses onToolEnd. */
39
39
  announceWorkspaceMove: () => void;
40
40
  }
41
41
  /** R5 抽取:runLocked 的五个 harness 事件处理器(onMessageUpdate/onMessageEnd/
42
42
  * onToolStart/onToolEnd/onTurnEnd,~530 行)整块搬迁。正文逐字;唯一字面变化 = this.deps.onError →
43
- * deps.runnerHooks.onError(1 处)。`lastWorkspaceCwd` 是纯 R5 局部(读写全在 onToolEnd 内,零段外
44
- * 读者),声明随迁进工厂体——调用点放在原声明位之后,初值 `prepared.cwdRef?.current` 的求值时机不变
45
- * (中间只有声明无执行)。*/
43
+ * deps.runnerHooks.onError(1 处)。工作区帧的去重状态住在腿的帧座(`Prepared.workspaceFrame`),
44
+ * 工厂体不持有、也不在调用时读 cwd。*/
46
45
  export declare function createHarnessHandlers(input: RunHarnessHandlersInput): RunHarnessHandlersResult;
@@ -33,14 +33,7 @@ export function createHarnessHandlers(input) {
33
33
  const label = toolLabels.get(e.toolName);
34
34
  return { toolCallId: e.toolCallId, spelledName: e.toolName, wireName: rosterToolName(prepared.toolRosterDeltas.current, e.toolName), ...(label !== undefined ? { label } : {}), args: e.args, ...requesterOf(prepared.modBus, e.toolCallId) };
35
35
  };
36
- let lastWorkspaceCwd = prepared.cwdRef?.current;
37
- const announceWorkspaceMove = () => {
38
- const cwdNow = prepared.cwdRef?.current;
39
- if (cwdNow !== undefined && cwdNow !== lastWorkspaceCwd) {
40
- lastWorkspaceCwd = cwdNow;
41
- queue.push({ type: "workspace_changed", cwd: cwdNow, ...ident() });
42
- }
43
- };
36
+ const announceWorkspaceMove = () => prepared.workspaceFrame.observe();
44
37
  const onMessageUpdate = (event) => {
45
38
  const ev = event.assistantMessageEvent;
46
39
  if (rs.turn.callStartAt === undefined)