@sema-agent/core 7.63.0 → 7.64.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 (204) hide show
  1. package/CHANGELOG.md +408 -0
  2. package/dist/agents/cc-peer-directory.js +1 -0
  3. package/dist/agents/cc-peer-wire.d.ts +4 -0
  4. package/dist/agents/cc-peer-wire.js +1 -0
  5. package/dist/agents/cc-uds-peer-channel.js +5 -0
  6. package/dist/agents/cross-session-judge.d.ts +3 -1
  7. package/dist/agents/cross-session-judge.js +4 -1
  8. package/dist/agents/peer-directory.d.ts +8 -0
  9. package/dist/agents/peer-directory.js +4 -0
  10. package/dist/agents/peer-held-queue.d.ts +9 -3
  11. package/dist/agents/peer-held-queue.js +12 -9
  12. package/dist/agents/peer-idle.d.ts +20 -1
  13. package/dist/agents/peer-idle.js +23 -12
  14. package/dist/agents/peer-notice-route.d.ts +16 -5
  15. package/dist/agents/peer-notice-route.js +11 -9
  16. package/dist/agents/peer-notices.d.ts +25 -8
  17. package/dist/agents/peer-notices.js +6 -1
  18. package/dist/agents/peer-session-drain.d.ts +32 -6
  19. package/dist/agents/peer-session-drain.js +100 -26
  20. package/dist/agents/send-message-tool.d.ts +7 -0
  21. package/dist/agents/send-message-tool.js +18 -6
  22. package/dist/agents/subagent.js +20 -3
  23. package/dist/core/allow-entry.d.ts +4 -0
  24. package/dist/core/ask-origin.d.ts +1 -1
  25. package/dist/core/ask-origin.js +2 -2
  26. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  27. package/dist/core/ask-unresolvable-notice.js +10 -3
  28. package/dist/core/auto-compaction.d.ts +7 -5
  29. package/dist/core/background-agent-store.d.ts +7 -0
  30. package/dist/core/background-agent-store.js +3 -0
  31. package/dist/core/checkpoint-queries.d.ts +9 -6
  32. package/dist/core/checkpoint-queries.js +8 -3
  33. package/dist/core/checkpoint-store.d.ts +5 -1
  34. package/dist/core/context-settings.d.ts +40 -9
  35. package/dist/core/context-settings.js +32 -10
  36. package/dist/core/engine-attestation.d.ts +26 -6
  37. package/dist/core/engine-attestation.js +5 -1
  38. package/dist/core/engine-notice.d.ts +24 -1
  39. package/dist/core/extension-requester.d.ts +9 -0
  40. package/dist/core/extension-requester.js +7 -0
  41. package/dist/core/file-history-store.d.ts +28 -0
  42. package/dist/core/file-history-store.js +48 -5
  43. package/dist/core/fs-write-gate-policy.js +1 -1
  44. package/dist/core/gate-fold.js +2 -0
  45. package/dist/core/gate-lanes.js +2 -0
  46. package/dist/core/gate-outcome.d.ts +39 -2
  47. package/dist/core/gate-outcome.js +20 -1
  48. package/dist/core/governance-codes.d.ts +3 -1
  49. package/dist/core/governance-codes.js +4 -0
  50. package/dist/core/leg-identity.d.ts +19 -1
  51. package/dist/core/leg-identity.js +12 -0
  52. package/dist/core/mailbox-store.d.ts +39 -4
  53. package/dist/core/mailbox-store.js +14 -2
  54. package/dist/core/memory-engine/consolidation.d.ts +3 -2
  55. package/dist/core/memory-engine/consolidation.js +16 -0
  56. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  57. package/dist/core/memory-engine/control-objects.js +151 -0
  58. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  59. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  60. package/dist/core/memory-engine/delegation-settlement.d.ts +21 -5
  61. package/dist/core/memory-engine/delegation-settlement.js +217 -26
  62. package/dist/core/memory-engine/dual-root.js +2 -2
  63. package/dist/core/memory-engine/engine.d.ts +38 -23
  64. package/dist/core/memory-engine/engine.js +14 -14
  65. package/dist/core/memory-engine/file-backend.d.ts +41 -65
  66. package/dist/core/memory-engine/file-backend.js +59 -166
  67. package/dist/core/memory-engine/index.d.ts +3 -2
  68. package/dist/core/memory-engine/index.js +2 -1
  69. package/dist/core/memory-engine/layout.d.ts +6 -1
  70. package/dist/core/memory-engine/layout.js +12 -7
  71. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  72. package/dist/core/memory-engine/memory-backend-contract.js +158 -2
  73. package/dist/core/memory-engine/memory-deployment.d.ts +11 -3
  74. package/dist/core/memory-engine/memory-deployment.js +31 -6
  75. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  76. package/dist/core/memory-engine/origin-clearance.js +68 -9
  77. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  78. package/dist/core/memory-engine/session-write-home.js +37 -10
  79. package/dist/core/memory-engine/types.d.ts +44 -7
  80. package/dist/core/memory-engine/types.js +2 -1
  81. package/dist/core/mode-policy.js +3 -3
  82. package/dist/core/mods/agent-stations.d.ts +18 -0
  83. package/dist/core/mods/agent-stations.js +8 -6
  84. package/dist/core/mods/extension-call.d.ts +4 -0
  85. package/dist/core/mods/extension-call.js +8 -0
  86. package/dist/core/mods/tool-call.js +3 -4
  87. package/dist/core/parent-spec-seat.d.ts +2 -2
  88. package/dist/core/peer-channel.d.ts +5 -0
  89. package/dist/core/permission-rule-consent.d.ts +21 -10
  90. package/dist/core/permission-rule-consent.js +50 -23
  91. package/dist/core/permission-rule-store.d.ts +41 -16
  92. package/dist/core/permission-rule-store.js +2 -0
  93. package/dist/core/refusal-echo.d.ts +20 -0
  94. package/dist/core/refusal-echo.js +33 -0
  95. package/dist/core/retention.d.ts +180 -10
  96. package/dist/core/retention.js +45 -0
  97. package/dist/core/retired-keys.d.ts +5 -0
  98. package/dist/core/retired-keys.js +3 -0
  99. package/dist/core/rule-offer-read.d.ts +0 -4
  100. package/dist/core/rule-offer-read.js +2 -18
  101. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  102. package/dist/core/runner/classifier-ladder.js +4 -2
  103. package/dist/core/runner/compact-session.js +10 -7
  104. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  105. package/dist/core/runner/compaction-call-options.js +3 -2
  106. package/dist/core/runner/contracts.d.ts +21 -2
  107. package/dist/core/runner/delegation-owner.d.ts +10 -3
  108. package/dist/core/runner/delegation-owner.js +4 -1
  109. package/dist/core/runner/gate-exit.d.ts +6 -0
  110. package/dist/core/runner/gate-exit.js +11 -2
  111. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  112. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  113. package/dist/core/runner/prepare-ask-lane.js +3 -3
  114. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  115. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  116. package/dist/core/runner/prepare-config-doors.js +4 -0
  117. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  118. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  119. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  120. package/dist/core/runner/prepare-gate-stations.js +5 -5
  121. package/dist/core/runner/prepare-hands-readface.js +1 -1
  122. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  123. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  124. package/dist/core/runner/prepare-memory.d.ts +4 -0
  125. package/dist/core/runner/prepare-memory.js +14 -20
  126. package/dist/core/runner/prepare-policy-chain.js +7 -7
  127. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  128. package/dist/core/runner/prepare-task.js +15 -10
  129. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  130. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  131. package/dist/core/runner/resume-admission.d.ts +2 -2
  132. package/dist/core/runner/resume-admission.js +2 -23
  133. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  134. package/dist/core/runner/role-resolution-table.js +62 -0
  135. package/dist/core/runner/run-compaction-machinery.js +2 -2
  136. package/dist/core/runner/run-identity-wiring.js +12 -9
  137. package/dist/core/runner/run-leg.js +8 -4
  138. package/dist/core/runner/run-notification-lane.js +22 -22
  139. package/dist/core/runner/run-recovery-lanes.js +3 -3
  140. package/dist/core/runner/run-terminal-adoption.js +1 -1
  141. package/dist/core/runner/run-turn-boundary.js +14 -15
  142. package/dist/core/runner/runtask.js +1 -1
  143. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  144. package/dist/core/runner/tool-occurrence.js +2 -2
  145. package/dist/core/runner-deps.d.ts +1 -1
  146. package/dist/core/session-checkout.d.ts +63 -3
  147. package/dist/core/session-checkout.js +152 -58
  148. package/dist/core/shell-read-silence.js +8 -0
  149. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  150. package/dist/core/task-event.d.ts +9 -5
  151. package/dist/core/task-notification.d.ts +110 -31
  152. package/dist/core/task-notification.js +180 -100
  153. package/dist/core/task-registry-agent.d.ts +11 -0
  154. package/dist/core/task-registry-agent.js +11 -3
  155. package/dist/core/task-registry-shared.d.ts +7 -0
  156. package/dist/core/task-registry.d.ts +18 -0
  157. package/dist/core/task-registry.js +27 -8
  158. package/dist/core/task-spec.d.ts +7 -2
  159. package/dist/core/tool-errors.d.ts +14 -6
  160. package/dist/core/tool-errors.js +1 -1
  161. package/dist/core/tool-policy.d.ts +18 -1
  162. package/dist/core/tool-policy.js +16 -7
  163. package/dist/core/tool-result-store.d.ts +20 -0
  164. package/dist/core/tool-spec.d.ts +4 -0
  165. package/dist/core/trace.d.ts +3 -2
  166. package/dist/core/workflow-journal-store.d.ts +11 -0
  167. package/dist/core/workflow-journal-store.js +7 -0
  168. package/dist/core/workflow-run-store.d.ts +9 -0
  169. package/dist/core/workflow-run-store.js +6 -0
  170. package/dist/engine/compaction/compaction.d.ts +2 -1
  171. package/dist/engine/harness/types.d.ts +1 -0
  172. package/dist/engine/session/session.d.ts +7 -1
  173. package/dist/engine/session/session.js +5 -2
  174. package/dist/index.d.ts +7 -5
  175. package/dist/index.js +7 -5
  176. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  177. package/dist/orchestration/run-workflow-tool.js +7 -0
  178. package/dist/orchestration/workflow-types.d.ts +2 -1
  179. package/dist/orchestration/workflow.d.ts +3 -0
  180. package/dist/orchestration/workflow.js +2 -1
  181. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  182. package/dist/stores/file/checkpoint-store.js +4 -1
  183. package/dist/stores/file/file-history-store.d.ts +13 -0
  184. package/dist/stores/file/file-history-store.js +75 -13
  185. package/dist/stores/file/index.d.ts +11 -1
  186. package/dist/stores/file/index.js +7 -11
  187. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  188. package/dist/stores/file/permission-rule-store.js +75 -7
  189. package/dist/stores/file/tool-result-store.d.ts +14 -0
  190. package/dist/stores/file/tool-result-store.js +39 -2
  191. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  192. package/dist/stores/file/workflow-journal-store.js +17 -0
  193. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  194. package/dist/stores/file/workflow-run-store.js +15 -0
  195. package/dist/tools/fs/read-deny.d.ts +15 -2
  196. package/dist/tools/fs/read-deny.js +10 -2
  197. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  198. package/dist/tools/fs/shell-read-check.js +7 -7
  199. package/package.json +2 -2
  200. package/test/export-surface.snapshot.json +63 -1
  201. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  202. package/wire-changes/core@7.64.0.json +2653 -0
  203. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  204. package/wire-changes/primitives@7.64.0.json +30 -0
@@ -92,6 +92,7 @@ import { declaredHostLocalPaths, isDeclaredSandboxOffHost, pathsAreHostLocal, ta
92
92
  import { settleTeardownLeg } from "./teardown-bounded.js";
93
93
  import { defaultTaskRegistry } from "../task-registry.js";
94
94
  import { announcePeerLaneMount, judgeSessionBoxDrain } from "../../agents/peer-session-drain.js";
95
+ import { sessionAddressOf } from "../task-notification.js";
95
96
  import { createFrameSettlement } from "../frame-settlement.js";
96
97
  import { createSchedulerTools } from "../../tools/scheduler-tools.js";
97
98
  import { selfOrchestrationFailClosedReason } from "../../orchestration/workflow-script-runner.js";
@@ -125,7 +126,7 @@ import { asThrownError, thrownText } from "../thrown-value.js";
125
126
  import { createAttachmentDelivery, refuseUserAttachmentPathsWithoutWorkspace, screenUserAttachments } from "../user-attachment.js";
126
127
  import { screenReadDenySeat } from "../read-face-seats.js";
127
128
  import { admitLegMods, legFacadeSeats } from "../mods/stations.js";
128
- import { agentIdOf, legTaskIdOf, mintAskSourceIdentity } from "../leg-identity.js";
129
+ import { agentIdOf, legTaskIdOf, mintAskSourceIdentity, noticeAddressOf } from "../leg-identity.js";
129
130
  import { frozenSkillScopesOf } from "../mods/spec-seats.js";
130
131
  function warnCompactionWindowHazard(tracer, spec, model, compModel, hostTaskId, overlay) {
131
132
  if (compModel === undefined)
@@ -367,6 +368,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
367
368
  internals = restoreRowTaskId(internals, resume?.seed.rowTaskId);
368
369
  const hostTaskId = legTaskIdOf(spec, internals, sessionId);
369
370
  const askSource = mintAskSourceIdentity({ principal: spec.principal, sessionId, taskId: hostTaskId, isDelegatedChild: delegation.isDelegatedChild, internals });
371
+ const noticeAddress = noticeAddressOf(askSource, internals?.rootSessionId);
370
372
  announceRoleSeatsDefaulted({ spec, deps, onceLedger, rootLeg: !delegation.isDelegatedChild, sessionId, runId });
371
373
  const placementRootResolved = (internals = restorePlacementRoot(internals, resume?.seed.placementRootSessionId))?.placementRoot ?? internals?.rootSessionId ?? sessionId;
372
374
  const compositionLegResolved = compositionLegRecord(internals?.compositionLeg ?? resume?.seed.compositionLeg);
@@ -376,8 +378,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
376
378
  const checkpointScope = checkpointScopeOf(spec, internals?.checkpointScope || resume?.seed.legScope);
377
379
  internals?.peerSelfRef?.addAxis("s", sessionId);
378
380
  internals?.peerSelfRef?.addAxis("t", hostTaskId);
379
- const peerLaneActive = announcePeerLaneMount(deps, { sessionId, runId });
380
- const sessionBox = judgeSessionBoxDrain(deps, { sessionId, scope: taskScope, isDelegatedChild: delegation.isDelegatedChild });
381
+ const peerLaneActive = announcePeerLaneMount(deps, { sessionId, runId, sessions });
381
382
  const peerLaneRefs = {};
382
383
  const frameSettlement = createFrameSettlement();
383
384
  const peerSendMessageBuiltIn = runnerSelf !== undefined && valveLeaves(spec, toolFaceSnapshot.selector)({ name: SEND_MESSAGE_TOOL_NAME }) && !(spec.tools ?? []).some((t) => t.name === SEND_MESSAGE_TOOL_NAME);
@@ -490,13 +491,14 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
490
491
  const legContextOverlay = () => runnerSelf?.contextOverlayOf?.(harnessRef.current?.getModelRef() ?? resolvedRole.modelRef);
491
492
  let resolvedReadFace;
492
493
  let resolvedWriteFace;
494
+ let sessionIncarnation;
493
495
  let readDenyAdditionsNormalized = [];
494
496
  let handsLessResolvedFace;
495
497
  let handsLessResolvedWriteFace;
496
498
  const mcpPool = installedPreflight.mcp?.length ? { pool: internals?.mcpPool ?? new McpConnectionPool(), owned: internals?.mcpPool === undefined } : undefined;
497
499
  const mcpHostSeats = internals?.mcpHostSeats;
498
500
  const mountedMcpNow = mcpPool !== undefined ? () => mountedMcpOf({ declared: installedPreflight.mcp, roster: roster.tools, aggregateNames: new Set(mcp.tools.filter((t) => t.mcpRemoteName === undefined).map((t) => t.name)), pool: mcpPool.pool, ...(mcpHostSeats !== undefined ? { hostSeats: mcpHostSeats } : {}) }) : undefined;
499
- const { liveInheritedGate, seedInheritedGate, inheritedAncestorRules, inheritedShellGate, inheritedParentConstraints, permissionMode, commitModeSeats, endModeCeiling, inheritedAdmittedOrgScopes, priorOwnOrgVerdict, orgGovernedProvenance, effectiveShellGate, ownSessionRulesRef, ancestorSessionRulesRef, ancestorRulesNow, memoryAdmittedOrgScopesRef, ownOrgVerdictRef, runClampSource, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, frozenOnAsk, hookEnvSource, frozenOnQuestion, parentSpecSeat, provenanceForChildrenRef, delegationSettlementRef, inheritedGateForChildren, carrierReadFace, carrierWriteFace, fullShellReachable, gateStopRef, stopForDenialLimit, enrichSpecToolCtx } = prepareInheritedGate({ spec, deps, delegationOwner, askSeat: doors.askSeat, hostFloor: doors.hostFloor, crossBoundaryTree, internals, resume, sessions, sessionId, runId, hostTaskId, taskRootFinal, delegationCwd, ownTarget, executionEnv, ownedEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { chainTop, onLeg: onLeg.chained }, checkpointSeat, checkpointScope, toolFaceSnapshot, mountsCallerTool, ...(mountedMcpNow !== undefined ? { mountedMcp: mountedMcpNow } : {}), promptLean, resolvedInteractionPosture, permissionModeSeat, handsEnabled, reportUsage, harnessRef, skillGrants, requestAllowedTools: allowedToolTables.request, forwardEvent, subagentRetain, taskArtifacts, worktreeIsolation, requestReview, requestStopAfterTurn, enterPlanMode, reminderMark, reminderDisclosureCounts, fileHistoryEnabled, historyScope, historyRoot, historyFs, abortRun: () => { abortController.abort(); void harness.abort(); }, runtimeCaps: () => runtimeCaps, modBus: legMods.standing, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, autoModeDenialTracking: () => autoModeDenialTrackingRef.current, autoModeArming: () => autoModeArmingRef.current, agentForkDenial: () => agentForkDenial, agentStations: () => agentStationsRef.current, sendStation: () => sendStationRef.current, observersActive: () => observersActive, resolvedReadFace: () => resolvedReadFace, resolvedWriteFace: () => resolvedWriteFace, readDenyAdditionsNormalized: () => readDenyAdditionsNormalized, handsLessResolvedFace: () => handsLessResolvedFace, handsLessResolvedWriteFace: () => handsLessResolvedWriteFace, centerAdoption: () => centerAdoptionRef.current, memoryEngineSession: () => memoryEngineSession });
501
+ const { liveInheritedGate, seedInheritedGate, inheritedAncestorRules, inheritedShellGate, inheritedParentConstraints, permissionMode, commitModeSeats, endModeCeiling, inheritedAdmittedOrgScopes, priorOwnOrgVerdict, orgGovernedProvenance, effectiveShellGate, ownSessionRulesRef, ancestorSessionRulesRef, ancestorRulesNow, memoryAdmittedOrgScopesRef, ownOrgVerdictRef, runClampSource, faceCheckpointSection, writeFaceCheckpointSection, skillGrantCheckpointSection, frozenOnAsk, hookEnvSource, frozenOnQuestion, parentSpecSeat, provenanceForChildrenRef, delegationSettlementRef, inheritedGateForChildren, carrierReadFace, carrierWriteFace, fullShellReachable, gateStopRef, stopForDenialLimit, enrichSpecToolCtx } = prepareInheritedGate({ spec, deps, delegationOwner, askSeat: doors.askSeat, hostFloor: doors.hostFloor, crossBoundaryTree, internals, resume, sessions, sessionId, runId, hostTaskId, taskRootFinal, delegationCwd, ownTarget, executionEnv, ownedEnv, lockedPreflight: installedPreflight, pathRuleAnchors: { chainTop, onLeg: onLeg.chained }, checkpointSeat, checkpointScope, toolFaceSnapshot, mountsCallerTool, ...(mountedMcpNow !== undefined ? { mountedMcp: mountedMcpNow } : {}), promptLean, resolvedInteractionPosture, permissionModeSeat, handsEnabled, reportUsage, harnessRef, skillGrants, requestAllowedTools: allowedToolTables.request, forwardEvent, subagentRetain, taskArtifacts, worktreeIsolation, requestReview, requestStopAfterTurn, enterPlanMode, reminderMark, reminderDisclosureCounts, fileHistoryEnabled, historyScope, historyRoot, historyFs, abortRun: () => { abortController.abort(); void harness.abort(); }, runtimeCaps: () => runtimeCaps, modBus: legMods.standing, ownModChain, autoModeDecider: () => autoModeDeciderRef.current, autoModeDenialTracking: () => autoModeDenialTrackingRef.current, autoModeArming: () => autoModeArmingRef.current, agentForkDenial: () => agentForkDenial, agentStations: () => agentStationsRef.current, sendStation: () => sendStationRef.current, observersActive: () => observersActive, resolvedReadFace: () => resolvedReadFace, resolvedWriteFace: () => resolvedWriteFace, readDenyAdditionsNormalized: () => readDenyAdditionsNormalized, handsLessResolvedFace: () => handsLessResolvedFace, handsLessResolvedWriteFace: () => handsLessResolvedWriteFace, centerAdoption: () => centerAdoptionRef.current, memoryEngineSession: () => memoryEngineSession, sessionIncarnation: () => sessionIncarnation });
500
502
  bindPermissionModeSeat(permissionMode);
501
503
  const personRowNotices = { onUnread: ruleStoreUnreadableNotice(deps.onNotice, { sessionId, runId }), onRowsDropped: ruleRowsDroppedNotice(deps.onNotice, { sessionId, runId }) };
502
504
  const readerOf = (signals) => personPathRowsOfTask({ deps, notices: personRowNotices, principal: spec.principal, ids: { sessionId, runId, taskId: hostTaskId }, root: taskRootFinal, rootCanonical: taskRootCanonical, leads: headLeads, chainTop, occurrences: toolOccurrences, signals });
@@ -514,7 +516,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
514
516
  const legExemptRoots = Object.freeze(dataRootSpellings(deps.memoryEngineDir));
515
517
  const legWriteGuard = { exemptRoots: legExemptRoots, rows: toolPolicyWriteGuardRows([installedToolPolicy, ...(inheritedParentConstraints ?? []).map((c) => c.policy)]), checkout };
516
518
  const sideCallBookRef = {};
517
- const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, delegationOwner, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, delegationCwd, ownTarget, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, taskArtifacts, 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, agentStations: () => agentStationsRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
519
+ const { roster, blockedRef, runtimeCaps, runtimeCapsFaulted, complianceDenies, complianceDegraded, agentForkDenial, observersActive, autoModeArmReason, autoModeDeciderRef, autoModeDenialTrackingRef, autoModeArmingRef, armAutoMode, selfOrchestrationActive, workflowToolsActive, workflowSizeGuideline } = await prepareCapsAndWorkflow({ spec, deps, delegationOwner, askSeat: doors.askSeat, internals, crossBoundaryTree, session, sessionId, runId, hostTaskId, taskScope, taskRootFinal, delegationCwd, ownTarget, model, thinking, lockedPreflight, checkpointSeat, toolEffects, toolFaceSnapshot, promptLean, resolvedInteractionPosture, harnessRef, parentSpecSeat, runClampSource, forwardEvent, inheritedGateForChildren, enrichSpecToolCtx, maybeOffload, taskArtifacts, 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, sessionIncarnation: () => sessionIncarnation, centerAdoption: () => centerAdoptionRef.current, agentStations: () => agentStationsRef.current, delegated: delegation.isDelegatedChild, sideCallBookRef });
518
520
  const tools = roster.tools;
519
521
  const crossBoundary = await prepareCrossBoundaryLane({ token: crossBoundaryTree, posture: doors.crossBoundaryPosture, externalContentTargetActive, env: executionEnv, session, resumeLeg: resume !== undefined, sessionId, runId, hostTaskId, deps });
520
522
  const sessionProject = await resolveSessionProject(projectMarkerFsOf(executionEnv), taskRootCanonical, spec.projectId);
@@ -608,6 +610,9 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
608
610
  return { fault: true };
609
611
  }
610
612
  })();
613
+ sessionIncarnation = captureLineage.own;
614
+ const sessionAddress = sessionAddressOf({ sessionId, ...(captureLineage.own !== undefined ? { sessionIncarnation: captureLineage.own } : {}), ...(captureLineage.fault ? { sessionIncarnationUnread: true } : {}) });
615
+ const sessionBox = judgeSessionBoxDrain(deps, { sessionId, scope: taskScope, isDelegatedChild: delegation.isDelegatedChild, ...(sessionAddress.unread === true ? { unread: true } : {}), sessions });
611
616
  const { memoryEngineSession, memoryTools, memoryWriteGate, composeInjection: composeMemoryInjection, admittedOrgScopes: memoryAdmittedOrgScopes, ownOrgVerdict: memoryOwnOrgVerdict, effectiveMemoryScopes: memoryEffectiveScopes, } = await prepareMemory({
612
617
  spec,
613
618
  deps,
@@ -675,7 +680,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
675
680
  handsLessResolvedWriteFace = handsReadFace.handsLessResolvedWriteFace;
676
681
  shellGatedTools = handsReadFace.shellGatedTools;
677
682
  await armAutoMode();
678
- const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, runReadFloor: runFloor, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, taskArtifacts, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
683
+ const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, sessionAddress, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, runReadFloor: runFloor, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, taskArtifacts, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
679
684
  const { liveQuestionFace, contentAskBindings, contentAskRoutable, lateStrandedAnswers, discloseStrandedAnswers, settleContentAskBindings, durableQuestionFace, questionToolMounted, mountedQuestionTool } = prepareQuestionFace({ frozenOnQuestion, spec, askSource, deps, checkpointStore, runtimeCaps, resolvedInteractionPosture, resume, sessionId, roster, toolFaceSnapshot, inheritedUnavailableAsks: () => inheritedUnavailableAsks });
680
685
  if (spec.handsReadOnly !== true) {
681
686
  const sessionScope = sessionId ?? spec.principal ?? spec.taskId ?? "default";
@@ -710,7 +715,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
710
715
  }
711
716
  }
712
717
  const rosterCanPersist = rosterCanPersistMemory(tools.filter(valveLeaves(spec, toolFaceSnapshot.selector)), { effects: toolEffects, handsOffHost: handsEnabled && !pathsAreHostLocal(executionEnv) }, spec.memoryPersistenceCapable);
713
- const { memoryBlock: memoryBlockFromEngine, recallDisciplineSegment: memoryRecallSegment, seedFiles: memorySeedFiles } = await composeMemoryInjection({ rosterCanPersist, isSubagent: delegation.isNonForkChild });
718
+ const { memoryBlock: memoryBlockFromEngine, recallDisciplineSegment: memoryRecallSegment, seedFiles: memorySeedFiles, noticesFrame: memoryNoticesFrame } = await composeMemoryInjection({ rosterCanPersist, isSubagent: delegation.isNonForkChild });
714
719
  if (memorySeedFiles?.length && seedContextFiles) {
715
720
  try {
716
721
  await seedContextFiles(memorySeedFiles);
@@ -846,7 +851,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
846
851
  }
847
852
  const { basePolicyForResumeEdit, denyNarrowingPolicy, skillGrantLane, allowEntryLanes, policyLayers, effectivePolicy, inheritedUnavailableAsks, inheritedAskGrants, riskAxesOf, ruleOffersOf, grantBindingOf, permissionRuleLane, ruleLaneFacts, permissionRuleOrgLane, storedRuleWholeToolRefusals, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, foldAskClasses, ancestorSandboxAdmissions, ancestorArbitrations, inheritedInstallations } = await preparePolicyChain({ hostFloor: doors.hostFloor, spec, deps, 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, askSource, abortController, now, ownSessionRulesRef });
848
853
  toolTableViewRef.current = createToolTableView({ policy: effectivePolicy, stored: { wholeToolRefusals: storedRuleWholeToolRefusals }, roster: rosterSeat, fpRef, turnSnapshotRef });
849
- const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, suspendTargetGap, 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, receiveSeat, 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 });
854
+ const { onAsk, preToolContexts, blockedToolCalls, batchHaltRef, blockedTracked, suspendTargetGap, 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, receiveSeat, harness, pausedRef, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive: handsReadFace.readDenyBuiltinTiersActive, lspManagerWired, lspDiagnosticsLive: lspDiagnostics !== undefined, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive: ownSessionRulesRef.current !== undefined, sessionBox, sessionAddress, checkpointScope, memoryPollution: () => memoryEngineSession?.pollution, advisorFact: advisor.manifest, runOrigin: doors.runOrigin });
850
855
  agentStationsRef.current = createAgentStations({ bus: legMods.bus, identity: hookIdentity, permissionMode: () => permissionMode.observed });
851
856
  sendStationRef.current = createSessionSendStation({ bus: legMods.bus, identity: hookIdentity });
852
857
  toolCallStationRef.current = createToolCallStation({ bus: legMods.bus, occurrences: toolOccurrences, blockedToolCalls, identity: hookIdentity, reminderMark, requestMeta: mcpRequestMeta, frameSettlement });
@@ -869,14 +874,14 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
869
874
  const { suspendForResource, suspendForPlatformLimit, suspendForReview } = prepareBoundaryParks({ saga, spec, checkpointStore, checkpointScope, abortController, harness, session, sessions, sessionId, askSource, deps, priorLedger, maxSlices, maxSuspends, resourceTotal, priorSuspendCount, suspendChainBase, humanReviewRef, liveSpendRef, now, pausedRef, remoteEnvFailures, resourceSuspendEligible, durableSuspendInfraReady, suspendTargetGap });
870
875
  const { parkAsk } = prepareParkAsk({ askLane, saga, spec, deps, sessionId, askSource, 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, suspendTargetGap, session, sessions, suspendChainBase, maxSuspends, remoteEnvFailures, shellGatedTools, irreversibilityTier, toolMarkSources, effectiveShellGate, durableApproval, priorLedger, liveSpendRef, resourceTotal, ruleOffersOf, grantBindingOf, now, humanReviewRef, abortController, harness, pausedRef });
871
876
  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() })) } } });
872
- const { approvedCallScreen } = prepareGateStations({ askLane, parkAsk, tools, toolRosterDeltas: rosterSeat, crossBoundaryCheck: crossBoundary.seat({ tools, roster: rosterSeat }), deps, toolCallGateArmedRef, effectivePolicy, modBus: legMods.bus, inheritedInstallations, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, handsCwdRef, stampCallTarget, readDenyInForce: (toolCallId) => ({ tiers: handsReadFace.readDenyBuiltinTiersActive, rows: [...readDenyAdditionsNormalized.map((e) => e.pattern), ...(pathTables?.forCall(toolCallId).ruleRows ?? handsReadFaceInput.denyRuleRows).filter((r) => r.faces.includes("read")).map((r) => r.rule)] }), hookEnvFace, writeProtectionCheck, shellReadCheck, readFace: () => resolvedReadFace, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider: autoModeDeciderRef, autoModeDenialTracking: autoModeDenialTrackingRef, askRoute: { ...wiringManifest.ask, effective: askSeatEffective(wiringManifest) }, permissionMode, toolMarkSources, ...(deps.a2a?.isolatePeers === true ? { a2aIsolatePeers: true } : {}), ancestorArbitrations, runId, stopForDenialLimit, permissionRuleLane, seatInputsFor, permissionRuleOrgLane, questionToolMounted, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, frameSettlement });
877
+ const { approvedCallScreen } = prepareGateStations({ askLane, parkAsk, tools, toolRosterDeltas: rosterSeat, crossBoundaryCheck: crossBoundary.seat({ tools, roster: rosterSeat }), deps, toolCallGateArmedRef, effectivePolicy, modBus: legMods.bus, inheritedInstallations, egressTools, irreversibleTools, spec, complianceDenies, harness, blockedToolCalls, inheritedAskGrants, inheritedUnavailableAsks, foldAskClasses, ancestorSandboxAdmissions, preToolContexts, toolOccurrences, batchHaltRef, blockedTracked, hookIdentity, reminderMark, hostTaskId, sessionId, noticeAddress, handsCwdRef, stampCallTarget, readDenyInForce: (toolCallId) => ({ tiers: handsReadFace.readDenyBuiltinTiersActive, rows: [...readDenyAdditionsNormalized.map((e) => e.pattern), ...(pathTables?.forCall(toolCallId).ruleRows ?? handsReadFaceInput.denyRuleRows).filter((r) => r.faces.includes("read")).map((r) => r.rule)] }), hookEnvFace, writeProtectionCheck, shellReadCheck, readFace: () => resolvedReadFace, irreversibilityTier, reversibilityProbes, abortController, shellGatedTools, autoModeDecider: autoModeDeciderRef, autoModeDenialTracking: autoModeDenialTrackingRef, askRoute: { ...wiringManifest.ask, effective: askSeatEffective(wiringManifest) }, permissionMode, toolMarkSources, ...(deps.a2a?.isolatePeers === true ? { a2aIsolatePeers: true } : {}), ancestorArbitrations, runId, stopForDenialLimit, permissionRuleLane, seatInputsFor, permissionRuleOrgLane, questionToolMounted, sandboxAdmissionArmed, sandboxBoundaryCapable, emitSandboxAdmitted, delegation, frameSettlement });
873
878
  const postureFrameRef = { report: (err) => deps.onError?.(err, { phase: "degraded", sessionId }) };
874
879
  const frameReceipts = { pending: [], listingSnapshotOwed: false };
875
880
  const { microCompact, charsPerToken } = prepareContextLane({ model, deps, announced: { announcedListingsRef, frameReceipts }, sessionId, runId, hostTaskId, offloadStore, toolRosterDeltas: rosterSeat, microCompactKnob, harness, batchHaltRef, gitStatusRef, postureFrameRef, requestLossyRef, trimPressureRef, contextOverlay: legContextOverlay, ...(readFileStateForCheckpoint !== undefined ? { readFileState: readFileStateForCheckpoint } : {}) });
876
881
  const preparedHolder = {};
877
882
  const { cacheBreakDetector, cacheFingerprint, promptOverheadTokens, compactionRestore, normalizeAttachmentPath, isDedupStubResult, recentlyReadFiles, onCompactionApplied, detectExternalChanges, syntheticReadVerdict, consolidationWriteJudge, listBackgroundTasks, taskReadHandleOf, 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 ?? []).flatMap((c) => (c.policy !== undefined ? [c.policy] : [])), persistedRuleLane: permissionRuleLane, ruleLaneFacts, personRowsBeyondRun, orgRuleLane: permissionRuleOrgLane, stampCallTarget, abortController, hostTaskId, taskScope, buildAssembleInputs, identityFor, adoptsCandidates, centerAdoptionRef, harnessRef, carrierReadFace, carrierWriteFace, readDenyAdditionsNormalized, preparedHolder });
878
883
  await onceLedger.settle(session, announcedListingsRef);
879
- const buildPrepared = () => ({ harness, session, sessionId, taskId: hostTaskId, 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, ...(placementValueOrAbsent(placementRootResolved) !== undefined ? { placementRoot: placementRootResolved } : {}), 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 } : {}), ...(() => { const s = sessionFrameOf(sessionCheckout.record); return s !== undefined ? { session: s } : {}; })(), ...(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, loopTerminalRef, 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, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), imageUnprocessed, ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, taskReadHandleOf, hookIdentity, modBus: legMods.bus, admitRows: rowSeat.admitRows, receiveSeat, turnOpenRedelivery: {}, compactStation, sessionMeasure, 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 } : {}) });
884
+ const buildPrepared = () => ({ harness, session, sessionId, ...(captureLineage.own !== undefined ? { sessionIncarnation: captureLineage.own } : {}), ...(captureLineage.fault ? { sessionIncarnationUnread: true } : {}), taskId: hostTaskId, 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, ...(placementValueOrAbsent(placementRootResolved) !== undefined ? { placementRoot: placementRootResolved } : {}), 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 } : {}), ...(() => { const s = sessionFrameOf(sessionCheckout.record); return s !== undefined ? { session: s } : {}; })(), ...(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, loopTerminalRef, 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 } : {}), ...(memoryNoticesFrame !== undefined ? { memoryNoticesFrame } : {}), ...(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, frameSettlement, ...(userAttachmentsSeat !== undefined ? { userAttachments: userAttachmentsSeat } : {}), attachmentDelivery: createAttachmentDelivery(), imageUnprocessed, ...(modelFileReaderSeat.current !== undefined ? { modelFileReader: modelFileReaderSeat.current } : {}), syntheticReadVerdict, ...(peerLaneRefs.boundaryRound !== undefined ? { peerBoundaryRound: peerLaneRefs.boundaryRound } : {}), gitStatusRef, postureFrameRef, listBackgroundTasks, taskReadHandleOf, hookIdentity, modBus: legMods.bus, admitRows: rowSeat.admitRows, receiveSeat, turnOpenRedelivery: {}, compactStation, sessionMeasure, 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 } : {}) });
880
885
  refuseLateRosterChanges(callerRoster.roster);
881
886
  rollback.commit();
882
887
  commitModeSeats(abortController.signal);
@@ -18,7 +18,7 @@
18
18
  */
19
19
  import type { AgentHarness, ExecutionEnv } from "../../internal/harness.js";
20
20
  import { type PeerLaneRefs } from "../../agents/peer-session-drain.js";
21
- import type { SessionBoxBinding } from "../task-notification.js";
21
+ import type { SessionAddress, SessionBoxBinding } from "../task-notification.js";
22
22
  import type { OnQuestion } from "../ask-question.js";
23
23
  import type { CheckpointStore } from "../checkpoint-store.js";
24
24
  import { type HookEnvCapabilities, type HookInvocationIdentity } from "../hooks.js";
@@ -152,6 +152,8 @@ export interface PrepareWiringManifestInput {
152
152
  receiveSeat: import("../task-notification.js").FrameReceiver;
153
153
  /** borrowed-readonly — the session-box drain's mount verdict (prepare-task's one judgment): present ⇒ this leg drains its own box. */
154
154
  sessionBox: SessionBoxBinding | undefined;
155
+ /** borrowed-readonly — the leg's own session address (`sessionAddressOf`): the box is drained for it. */
156
+ sessionAddress: SessionAddress;
155
157
  /** borrowed-readonly, read late — the memory session's one-way pollution face (absent with no memory session). The drain marks
156
158
  * it when it INJECTS a letter from another principal (the injection path; the tool path is accounted by `ReadInbox`'s class). */
157
159
  memoryPollution?: () => Pick<NonNullable<Prepared["memoryEngineSession"]>["pollution"], "markPolluted"> | undefined;
@@ -120,7 +120,7 @@ function announceDurableGateUnavailable(args) {
120
120
  });
121
121
  }
122
122
  export function prepareWiringManifest(input) {
123
- 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, receiveSeat, sessionBox, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin } = input;
123
+ 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, receiveSeat, sessionBox, sessionAddress, harness, pausedRef, askSeat, liveInheritedGate, delegation, toolRoster, readDenyBuiltinTiersActive, lspManagerWired, shellReadStationArmed, crossBoundaryStationEngaged, lspDiagnosticsLive, fileHistoryFact, projectMemoryFact, sessionRulesChildrenReadLive, memoryPollution, advisorFact, hostFloorPosture, runOrigin } = input;
124
124
  const onAsk = askSeat.value;
125
125
  const handWriteTools = toolRoster.entries.filter((e) => e.mountedBy === "hands" && (e.effect === "write" || e.effect === "idempotent")).map((e) => e.name);
126
126
  const hasEffectAwareGate = policyLayers.length > 0 || chainJudges(standingModBus);
@@ -246,7 +246,8 @@ export function prepareWiringManifest(input) {
246
246
  if (sessionBoxBound !== undefined && internals?.onTaskNotification !== undefined) {
247
247
  bindPeerLaneDrain(harness, {
248
248
  deps,
249
- sessionId,
249
+ address: sessionAddress,
250
+ sessions,
250
251
  runId,
251
252
  scope: taskScope,
252
253
  inject: internals.onTaskNotification,
@@ -2,8 +2,8 @@
2
2
  * The resume ladder's ADMISSION rung (E1) and the wake's shaping (E2), verbatim from
3
3
  * `Runner.resumeStream`: the outcome container's domain, the one-read snapshots of the caller's config and
4
4
  * the trusted internals bag, the store resolution, the row read and its terminal-status confirm, the row's own verdict,
5
- * the same-process parent-constraint re-supply, then the wake pre-ladder (gate purity, pendingAction purity,
6
- * the message's persist-time validation) and the one read of the outcome discriminant and the signal slot.
5
+ * the same-process parent-constraint re-supply, then the wake pre-ladder (gate purity, the message's persist-time validation)
6
+ * and the one read of the outcome discriminant and the signal slot.
7
7
  *
8
8
  * Async (two store reads); every refusal throws a typed `CheckpointError` pre-CAS. It ends by handing what it
9
9
  * admitted to the rung after it (`next`) in its LAST continuation — no suspension point between the
@@ -7,13 +7,12 @@ import { runExpiredDuty } from "./expire-settle.js";
7
7
  import { describeSuppliedValue } from "./decide-continuation.js";
8
8
  import { detachSkillLists } from "../skill-grant.js";
9
9
  import { readCallerSpec } from "../task-spec-members.js";
10
- import { isGateKind, PAUSE_REGISTRY } from "../pause-registry.js";
10
+ import { PAUSE_REGISTRY } from "../pause-registry.js";
11
11
  const DECIDE_ENTRY_BY_RESUME_GATE = {
12
12
  policy_ask: "a `policy_ask` outcome (decision allow/deny bound to the pending tool call)",
13
13
  dry_run_review: "a `dry_run_review` outcome (decision approve/reject)",
14
14
  plan_review: "a `plan_review` outcome (decision approve/edit/reject)",
15
15
  resource_limit: 'a `resource_limit` outcome (decision "continue")',
16
- task_done: undefined,
17
16
  };
18
17
  export async function resumeAdmission(input) {
19
18
  const { token, outcome, taskConfig, runner, sessions, parentConstraintRegistry, suspendedEnvReaps } = input;
@@ -71,29 +70,9 @@ export async function resumeAdmission(input) {
71
70
  if (outcomeGate === "wake") {
72
71
  suppliedMessage = outcome.message;
73
72
  const gk = cp.gate.kind;
74
- const decideEntry = isGateKind(gk) ? DECIDE_ENTRY_BY_RESUME_GATE[PAUSE_REGISTRY[gk].resume] : undefined;
75
73
  if (gk !== "task_done") {
76
74
  throw new CheckpointError("wake.gate_pending", `cannot wake: this checkpoint awaits a pending gate decision (gate "${gk}") — wake is not a decision ` +
77
- `channel; resume it with ${decideEntry ?? "its own gate outcome"} instead`);
78
- }
79
- const pa = cp.pendingAction;
80
- switch (pa.kind) {
81
- case "task_done":
82
- break;
83
- case "tool_approval":
84
- case "resource_limit":
85
- case "review":
86
- case "plan_review": {
87
- throw new CheckpointError("wake.gate_pending", `cannot wake: this checkpoint still carries a pending gate-typed action (pendingAction "${pa.kind}" ` +
88
- `on a "${gk}" gate — inconsistent row) — wake is not a decision channel; resolve it through its ` +
89
- `own decide entry instead`);
90
- }
91
- default: {
92
- const _exhaustive = pa;
93
- void _exhaustive;
94
- throw new CheckpointError("wake.gate_pending", `cannot wake: this checkpoint carries an unrecognized pendingAction kind "${pa.kind}" ` +
95
- `(newer-version row?) — fail-closed: wake only serves a pure park (pendingAction "task_done")`);
96
- }
75
+ `channel; resume it with ${DECIDE_ENTRY_BY_RESUME_GATE[PAUSE_REGISTRY[gk].resume]} instead`);
97
76
  }
98
77
  if (suppliedMessage !== undefined) {
99
78
  wakeMessage = validatePendingSteer(suppliedMessage);
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Which model roles the engine resolves ITSELF at a task's prepare, where, and whether a role that supplies nothing
3
+ * refuses — one table — and the one question a host asks of it: "will this model face (`{ models, tiers, roles }`, what a
4
+ * host hands `new Runner`) make a task's prepare refuse on a role?".
5
+ *
6
+ * Each row is a role the engine reads itself at a hop that can refuse; the hop is the engine's own function, the very
7
+ * one prepare calls — the question below calls it too, so the answer cannot drift from what a task meets, and no
8
+ * judgment is written twice. A hop is not a copy: `resolveTaskModel` (`roles.ts`: the task's own model),
9
+ * `resolveCompactionModel` (`prepare-config-doors.ts`: the `summarize` role; `Runner.compactSession` calls it too) and
10
+ * `assertAutoConsolidationWirable` (`memory-consolidation-driver.ts`: the consolidation arming door) — all three are called
11
+ * from `prepare-config-doors.ts`, and the rows stand in the order prepare reaches them.
12
+ *
13
+ * `when` says WHAT the hop reads. `per-task`: the face AND the task's own spec (`model`, `modelRole`, `compactionModel`,
14
+ * `roles`) — a task that names its model never walks the `default` chain, one that names its compaction model never reads
15
+ * `summarize`. `deployment`: the face alone — the deployment's own question, asked of every prepare (the deps door) and of
16
+ * a host-run consolidation, and only a refusal when auto-consolidation is armed (`autoRunOnRecommendation: true`); an
17
+ * explicit `memoryConsolidationDriver.chat` seat is no part of a face, so a deployment that names one holds a seat the
18
+ * question does not see. Nothing resolves a role at `new Runner` (it receives the catalog and the tier bindings, which are no
19
+ * roles): the first refusal on a role comes at the first prepare.
20
+ *
21
+ * `absence` says what a row does when its role supplies NO model at all: `throws` — the hop refuses; `falls-back` — the
22
+ * hop answers "none" and the caller carries on (the compaction pass rides the task's own model).
23
+ *
24
+ * Not rows, on purpose: the auto-mode classifier seat (`classifierSeatModel`) and the next-prompt suggestion pass resolve
25
+ * a role and take the main model when it supplies none — neither refuses; the `subagent` / `verifier` seats resolve when a
26
+ * child is spawned, not at the parent's prepare; `sideQuery` and `Runner.compactSession` resolve at the caller's call, on a
27
+ * model the caller names. A role resolution site that refuses at prepare and is not a row here is a missing row.
28
+ */
29
+ import type { Model } from "../../internal/llm.js";
30
+ import type { ModelRef, ModelRole, ModelRoles, TaskSpec } from "../types.js";
31
+ /** When a row's hop reads its role — see the module note. */
32
+ export type RoleResolutionWhen = "per-task" | "deployment";
33
+ /** What a row does when its role supplies no model — see the module note. */
34
+ export type RoleResolutionAbsence = "throws" | "falls-back";
35
+ /** One row: the role, when it is read, the hop that reads it (`file :: function`), and what its absence does. */
36
+ export interface RoleResolutionRow {
37
+ readonly role: ModelRole;
38
+ readonly when: RoleResolutionWhen;
39
+ readonly hop: string;
40
+ readonly absence: RoleResolutionAbsence;
41
+ }
42
+ /** The roles the engine resolves itself at prepare — read-only; the table the question below walks, in the order prepare reaches them. */
43
+ export declare const ROLE_RESOLUTION_TABLE: readonly [Readonly<{
44
+ role: "consolidate";
45
+ when: "deployment";
46
+ hop: "src/core/runner/memory-consolidation-driver.ts :: assertAutoConsolidationWirable";
47
+ absence: "throws";
48
+ }>, Readonly<{
49
+ role: "default";
50
+ when: "per-task";
51
+ hop: "src/core/roles.ts :: resolveTaskModel";
52
+ absence: "throws";
53
+ }>, Readonly<{
54
+ role: "summarize";
55
+ when: "per-task";
56
+ hop: "src/core/runner/prepare-config-doors.ts :: resolveCompactionModel";
57
+ absence: "falls-back";
58
+ }>];
59
+ /** The model face the question is asked of — the three members a host hands `new Runner` for models: the catalog, the tier bindings over it, and the role map. The question applies the Runner's own catalog door to them (do not pre-expand the tiers). */
60
+ export interface ModelFace {
61
+ models?: Record<string, Model>;
62
+ tiers?: Record<string, ModelRef>;
63
+ roles?: ModelRoles;
64
+ }
65
+ /** The task a per-task row is asked about: the members of a `TaskSpec` those hops read. Omitted ⇒ a task that names none of them. */
66
+ export type ModelFaceTask = Pick<TaskSpec, "model" | "modelRole" | "roles" | "compactionModel">;
67
+ export interface ModelFaceOptions {
68
+ /** The task the per-task rows are asked about (default: a task naming no model, no role, no compaction model). */
69
+ spec?: ModelFaceTask;
70
+ /** Which rows to ask (default `["per-task"]`; add `"deployment"` to ask the consolidation seat as armed). */
71
+ when?: readonly RoleResolutionWhen[];
72
+ }
73
+ /** The answer: `ok: true`, or the first row whose hop refuses — its role and the code of the refusal the hop itself throws. */
74
+ export type ModelFaceVerdict = {
75
+ ok: true;
76
+ } | {
77
+ ok: false;
78
+ role: (typeof ROLE_RESOLUTION_TABLE)[number]["role"];
79
+ code: string;
80
+ };
81
+ /**
82
+ * Will a task's prepare refuse on a role resolution, over this model face? Walks the rows of {@link ROLE_RESOLUTION_TABLE}
83
+ * the options select, in table order (the order prepare reaches them), and asks each row's own hop; the first that throws is
84
+ * the answer — `{ ok: false, role, code }`, the `code` the hop's refusal carries (nothing is minted here). `{ ok: true }` ⇔
85
+ * none refuses.
86
+ *
87
+ * Pure: reads the face and the spec, writes nothing; each member is read once, as prepare takes a task's members once, and
88
+ * the catalog and the role maps are received once before any hop reads them (a role map that is no map refuses before any
89
+ * role is read, and the first row asked carries that refusal). A face whose catalog `new Runner` would not accept is refused
90
+ * as `new Runner` refuses it — thrown, not a verdict. A role that supplies no model is a refusal only where the row's
91
+ * `absence` says `throws`; a `summarize` seat that is unset, or names a word the catalog does not hold, is `ok: true` (the
92
+ * compaction pass rides the task's model). A throw that carries no code is not a verdict and is rethrown.
93
+ *
94
+ * Whether a task's prepare refuses on a role over a given face is answered here and nowhere else: a host that derives it from
95
+ * its own copy of the role walk (for example by handing the engine a role map cut down to one key) answers a different
96
+ * question the day the walk moves.
97
+ */
98
+ export declare function modelFaceResolvable(face: ModelFace, options?: ModelFaceOptions): ModelFaceVerdict;
@@ -0,0 +1,62 @@
1
+ import { bindingShown, receiveModelCatalog, resolveTaskModel, screenRoleMap } from "../roles.js";
2
+ import { assertAutoConsolidationWirable } from "./memory-consolidation-driver.js";
3
+ import { resolveCompactionModel } from "./prepare-config-doors.js";
4
+ export const ROLE_RESOLUTION_TABLE = Object.freeze([
5
+ Object.freeze({ role: "consolidate", when: "deployment", hop: "src/core/runner/memory-consolidation-driver.ts :: assertAutoConsolidationWirable", absence: "throws" }),
6
+ Object.freeze({ role: "default", when: "per-task", hop: "src/core/roles.ts :: resolveTaskModel", absence: "throws" }),
7
+ Object.freeze({ role: "summarize", when: "per-task", hop: "src/core/runner/prepare-config-doors.ts :: resolveCompactionModel", absence: "falls-back" }),
8
+ ]);
9
+ const HOPS = {
10
+ consolidate: (_task, deps) => assertAutoConsolidationWirable({ ...deps, memoryConsolidation: {}, autoRunOnRecommendation: true }),
11
+ default: (task, deps) => void resolveTaskModel(task, deps),
12
+ summarize: (task, deps) => void resolveCompactionModel(task, deps, "TaskSpec.compactionModel"),
13
+ };
14
+ const WHEN_WORDS = ["per-task", "deployment"];
15
+ function argumentRefusal(message) {
16
+ const e = new Error(message);
17
+ e.code = "config.invalid_argument";
18
+ return e;
19
+ }
20
+ function refusalCode(thrown) {
21
+ const code = thrown !== null && typeof thrown === "object" ? thrown.code : undefined;
22
+ return typeof code === "string" ? code : undefined;
23
+ }
24
+ function kindOf(value) {
25
+ return value === null ? "null" : Array.isArray(value) ? "a list" : typeof value;
26
+ }
27
+ export function modelFaceResolvable(face, options = {}) {
28
+ if (typeof face !== "object" || face === null || Array.isArray(face))
29
+ throw argumentRefusal(`modelFaceResolvable: the face must be an object { models?, tiers?, roles? } (got ${kindOf(face)}).`);
30
+ if (typeof options !== "object" || options === null)
31
+ throw argumentRefusal(`modelFaceResolvable: the options must be an object { spec?, when? } when present (got ${kindOf(options)}).`);
32
+ const when = options.when ?? ["per-task"];
33
+ if (!Array.isArray(when))
34
+ throw argumentRefusal(`modelFaceResolvable: options.when must be a list of row groups (${WHEN_WORDS.join(" / ")}) when present (got ${kindOf(when)}).`);
35
+ for (const word of when) {
36
+ if (!WHEN_WORDS.includes(word))
37
+ throw argumentRefusal(`modelFaceResolvable: options.when holds ${bindingShown(word)}, which is no row group of the role resolution table (${WHEN_WORDS.join(" / ")}).`);
38
+ }
39
+ const given = options.spec ?? {};
40
+ if (typeof given !== "object" || given === null || Array.isArray(given))
41
+ throw argumentRefusal(`modelFaceResolvable: options.spec must be a task { model?, modelRole?, roles?, compactionModel? } when present (got ${kindOf(given)}).`);
42
+ const { models: heldModels, tiers, roles: deploymentRoles } = face;
43
+ const models = heldModels !== undefined || tiers !== undefined ? receiveModelCatalog(heldModels, tiers, "RunnerDeps").models : undefined;
44
+ const { model, modelRole, roles: taskRoles, compactionModel } = given;
45
+ let read;
46
+ const received = () => (read ??= { deps: { models, roles: screenRoleMap(deploymentRoles, "RunnerDeps.roles") }, task: { model, modelRole, roles: screenRoleMap(taskRoles, "TaskSpec.roles"), compactionModel } });
47
+ for (const row of ROLE_RESOLUTION_TABLE) {
48
+ if (!when.includes(row.when))
49
+ continue;
50
+ try {
51
+ const { deps, task } = received();
52
+ HOPS[row.role](task, deps);
53
+ }
54
+ catch (thrown) {
55
+ const code = refusalCode(thrown);
56
+ if (code === undefined)
57
+ throw thrown;
58
+ return { ok: false, role: row.role, code };
59
+ }
60
+ }
61
+ return { ok: true };
62
+ }
@@ -11,9 +11,9 @@ export function runCompactionMachinery(input) {
11
11
  prepared.sideCallBookRef.book = bookSideCall;
12
12
  const compactionBrain = derivedLegBrain(() => runner.deps.brain, "compaction", bookSideCall);
13
13
  const legOverlay = () => contextOverlayFor(runner.deps.contextSettings, prepared.harness.getModelRef(), runner.deps);
14
- const withinTaskCompaction = () => compactionEnabled(spec.compaction?.enabled, legOverlay()) && (spec.compaction?.withinTask ?? true);
14
+ const withinTaskCompaction = () => compactionEnabled("autoCompact", spec.compaction, legOverlay()) && (spec.compaction?.withinTask ?? true);
15
15
  const compactionBreaker = { failures: 0 };
16
- if (compactionEnabled(spec.compaction?.enabled, legOverlay())) {
16
+ if (compactionEnabled("autoCompact", spec.compaction, legOverlay())) {
17
17
  const prefixWindow = resolveTriggerWindow(prepared.model, legOverlay()).window;
18
18
  if (Number.isFinite(prefixWindow) && prefixWindow > 0) {
19
19
  const prefixSettings = sanitizeCompactionSettings({ ...DEFAULT_COMPACTION_SETTINGS, ...spec.compaction }, prefixWindow);
@@ -4,7 +4,7 @@ import { forwardSafely } from "./forward-sink.js";
4
4
  import { emitsChildRowFrames, taskStartedFrame } from "../delegation-frames.js";
5
5
  import { recordFrameReceipt, toolResultReceiptKey } from "../frame-settlement.js";
6
6
  import { createReceivingChain } from "../mods/session-receive.js";
7
- import { discloseDroppedPending, renderTaskNotificationXml, taskNotificationDedupKey } from "../task-notification.js";
7
+ import { discloseDroppedPending, renderTaskNotificationXml, sessionAddressOf, taskNotificationDedupKey } from "../task-notification.js";
8
8
  import { buildAppliedHumanInputEvent } from "../human-input-projection.js";
9
9
  import { announceAcceptance, nextHumanInputSeq } from "./steer-admission.js";
10
10
  import { deliverDelegationLifecycle, deliverEngineNotice, parentLegIds, parkedInputIdsOf, undrainedUserInputNotices } from "../types.js";
@@ -13,7 +13,7 @@ import { mintCallerStopGate } from "./caller-stop-gate.js";
13
13
  export function runIdentityWiring(input) {
14
14
  const { spec, queue, prepared, internals, taskIdRef, onReady, manualCompactRef, notifyRef, captureOptOutRef, mcpRedialRef, injectTaskNotification, deliveredAtTurnOpen, peerInboundChainRef, notificationLane, pendingSessionNotifications, runner } = input;
15
15
  notificationLane.harness = prepared.harness;
16
- notificationLane.sessionId = prepared.sessionId;
16
+ notificationLane.address = sessionAddressOf(prepared);
17
17
  if (taskIdRef)
18
18
  taskIdRef.effectiveMemoryScopes = prepared.effectiveMemoryScopes;
19
19
  if (taskIdRef)
@@ -54,13 +54,14 @@ export function runIdentityWiring(input) {
54
54
  queue.push({ type: "compaction_outcome", outcome: "mooted", trigger: "manual", reason, ...ident() });
55
55
  };
56
56
  prepared.harness.onUndrainedEngineNotes = (payloads) => {
57
- if (notificationLane.sessionId === undefined)
57
+ const address = notificationLane.address;
58
+ if (address === undefined)
58
59
  return;
59
60
  const boxBacked = prepared.frameSettlement.boxBacked;
60
61
  for (const p of payloads) {
61
62
  if (boxBacked !== undefined && boxBacked(p))
62
63
  continue;
63
- pendingSessionNotifications.pend(notificationLane.sessionId, p);
64
+ pendingSessionNotifications.pend(address, p);
64
65
  }
65
66
  };
66
67
  prepared.harness.engineInjectionsHeld = () => prepared.batchHaltRef.current !== undefined;
@@ -83,8 +84,9 @@ export function runIdentityWiring(input) {
83
84
  const peer = payload?.peer;
84
85
  if (peer !== undefined && Array.isArray(peer.hopChain))
85
86
  peerInboundChainRef.current = [...peer.hopChain];
86
- if (notificationLane.sessionId !== undefined && typeof payload?.task_id === "string" && typeof payload.status === "string")
87
- pendingSessionNotifications.markDelivered(notificationLane.sessionId, taskNotificationDedupKey(payload));
87
+ const address = notificationLane.address;
88
+ if (address !== undefined && typeof payload?.task_id === "string" && typeof payload.status === "string")
89
+ pendingSessionNotifications.markDelivered(address, taskNotificationDedupKey(payload));
88
90
  };
89
91
  prepared.harness.onUserInputConsumed = (record) => {
90
92
  const steer = record;
@@ -121,7 +123,8 @@ export function runIdentityWiring(input) {
121
123
  }
122
124
  {
123
125
  const receiving = createReceivingChain(() => prepared.receiveSeat);
124
- const pendingIdle = pendingSessionNotifications.drain(prepared.sessionId);
126
+ const ownAddress = sessionAddressOf(prepared);
127
+ const pendingIdle = pendingSessionNotifications.drain(ownAddress);
125
128
  if (pendingIdle !== undefined) {
126
129
  for (const payload of discloseDroppedPending(pendingIdle, prepared.taskReadHandleOf, () => prepared.listBackgroundTasks({ settled: true }))) {
127
130
  const parkedPriority = pendingIdle.priorities?.get(payload);
@@ -129,10 +132,10 @@ export function runIdentityWiring(input) {
129
132
  queue.push({ type: "task_notification", notification: payload, ...(parkedPriority !== undefined ? { priority: parkedPriority } : {}), ...ident() });
130
133
  const handOver = (shown) => {
131
134
  void prepared.harness.nextTurn(renderTaskNotificationXml(shown), { provenance: "engine-note", enginePayload: payload }).catch(() => {
132
- pendingSessionNotifications.pend(prepared.sessionId, payload, parkedPriority);
135
+ pendingSessionNotifications.pend(ownAddress, payload, parkedPriority);
133
136
  });
134
137
  };
135
- receiving.pass(payload, { handOver, fault: () => pendingSessionNotifications.pend(prepared.sessionId, payload, parkedPriority) });
138
+ receiving.pass(payload, { handOver, fault: () => pendingSessionNotifications.pend(ownAddress, payload, parkedPriority) });
136
139
  }
137
140
  }
138
141
  if (receiving.settled !== undefined)
@@ -175,6 +175,8 @@ export async function runLeg(input) {
175
175
  const unavailableResume = owedMcpUnavailable(prepared, rs.attach.attachmentsCfg);
176
176
  if (unavailableResume !== undefined)
177
177
  continuation += "\n\n" + mintSystemReminder(sanitizeUntrustedText(unavailableResume.body, attachmentEnvelopeTags("mcp_unavailable")), prepared.reminderMark);
178
+ if (prepared.memoryNoticesFrame !== undefined)
179
+ continuation += "\n\n" + prepared.memoryNoticesFrame;
178
180
  const advisorResumeFrame = advisorFrameText(prepared);
179
181
  if (advisorResumeFrame !== undefined)
180
182
  continuation += "\n\n" + advisorResumeFrame;
@@ -431,6 +433,8 @@ export async function runLeg(input) {
431
433
  }
432
434
  if (prepared.outputStyleFrame !== undefined)
433
435
  firstFrames.push({ source: "output_style", body: prepared.outputStyleFrame, commit: () => undefined, disclose: () => undefined });
436
+ if (prepared.memoryNoticesFrame !== undefined)
437
+ effectiveObjective = `${prepared.memoryNoticesFrame}\n${effectiveObjective}`;
434
438
  if (firstFrames.length > 0) {
435
439
  effectiveObjective = `${firstFrames.map((f) => mintSystemReminder(sanitizeUntrustedText(f.body, attachmentEnvelopeTags(f.source)), prepared.reminderMark)).join("\n")}\n${effectiveObjective}`;
436
440
  }
@@ -643,9 +647,9 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
643
647
  occurrences.gateRound(pendingAction.toolCallId, decidedGate, frozenInputSnapshot(resolvedArgs));
644
648
  let notExecuted = false;
645
649
  const resultRow = (text, isError) => withRowNotExecuted(toolResultMsg(pendingAction.toolCallId, pendingAction.toolName, text, isError), notExecuted);
646
- const settleEnd = async (isError, result, refusedBy, neverRan, extension) => {
650
+ const settleEnd = async (isError, result, refusedBy, neverRan, facts) => {
647
651
  if (refusedBy !== undefined)
648
- occurrences.refuse(pendingAction.toolCallId, refusedBy, extension);
652
+ occurrences.refuse(pendingAction.toolCallId, refusedBy, facts);
649
653
  const settled = emitSettled(occurrences, callStart, { result, isError, ...(neverRan ? { notExecuted: true } : {}) }, { push: emit, structured: prepared.structuredProjector, mediaBudgetBase64Chars: runner.deps.mediaBudgetBase64Chars });
650
654
  notExecuted = settled.notExecuted === true;
651
655
  const gate = settled.gate ?? decidedGate;
@@ -691,7 +695,7 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
691
695
  const screened = await prepared.approvedCallScreen?.({ toolCallId: pendingAction.toolCallId, toolName: pendingAction.toolName, args: structuredClone(resolvedArgs), decidedBy: outcome.hostDecision.decidedBy });
692
696
  if (screened !== undefined && "refused" in screened) {
693
697
  const hookDenial = formatHookFeedback(screened.refused, prepared.reminderMark);
694
- await settleEnd(true, { content: hookDenial }, "hook", undefined, screened.extension);
698
+ await settleEnd(true, { content: hookDenial }, "hook", undefined, screened.extension !== undefined ? { extension: screened.extension } : undefined);
695
699
  emitCommitted(await appendAdmittedRow(prepared.admitRows, prepared.session, resultRow(hookDenial, true)), "toolResult", pendingAction.toolCallId);
696
700
  return;
697
701
  }
@@ -845,7 +849,7 @@ async function resolvePendingCall(runner, prepared, resume, emit, emitCommitted,
845
849
  const reading = readStationAnswer(verdict, { toolName: pendingAction.toolName, toolCallId: pendingAction.toolCallId });
846
850
  if (reading.kind === "refuse" || reading.kind === "silence" || (unseen && reading.kind !== "vouch")) {
847
851
  const readDenial = formatHookFeedback(`The approved tool call "${pendingAction.toolName}" was not executed: ${reading.verdict.sentence ?? "the read boundary does not vouch for what it reads on this leg"} This approval is spent — the call has to be re-issued and approved again.`, prepared.reminderMark);
848
- await settleEnd(true, { content: readDenial, ...(reading.verdict.details !== undefined ? { details: reading.verdict.details } : {}) }, "read_boundary");
852
+ await settleEnd(true, { content: readDenial, ...(reading.verdict.details !== undefined ? { details: reading.verdict.details } : {}) }, "read_boundary", undefined, reading.verdict.echoed !== undefined ? { echoed: reading.verdict.echoed } : undefined);
849
853
  const eid = await appendAdmittedRow(prepared.admitRows, prepared.session, resultRow(readDenial, true));
850
854
  emitCommitted(eid, "toolResult", pendingAction.toolCallId);
851
855
  return;