@sema-agent/core 7.64.0 → 7.65.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 (103) hide show
  1. package/CHANGELOG.md +317 -0
  2. package/dist/agents/peer-held-queue.js +1 -1
  3. package/dist/agents/peer-idle.js +1 -1
  4. package/dist/agents/peer-session-drain.js +3 -3
  5. package/dist/agents/subagent.js +5 -2
  6. package/dist/core/auto-promote.d.ts +3 -2
  7. package/dist/core/background-agent-store.d.ts +7 -0
  8. package/dist/core/checkpoint-store.d.ts +2 -3
  9. package/dist/core/context-settings.d.ts +1 -2
  10. package/dist/core/context-settings.js +1 -1
  11. package/dist/core/engine-attestation.d.ts +2 -2
  12. package/dist/core/engine-notice.d.ts +13 -1
  13. package/dist/core/engine-notice.js +3 -1
  14. package/dist/core/file-history-store.d.ts +2 -2
  15. package/dist/core/file-history-store.js +0 -4
  16. package/dist/core/gate-fold.js +3 -1
  17. package/dist/core/governance-codes.d.ts +6 -4
  18. package/dist/core/governance-codes.js +4 -3
  19. package/dist/core/leg-identity.d.ts +18 -2
  20. package/dist/core/leg-identity.js +5 -7
  21. package/dist/core/mailbox-store.d.ts +1 -1
  22. package/dist/core/memory-engine/consolidation.d.ts +10 -4
  23. package/dist/core/memory-engine/consolidation.js +11 -1
  24. package/dist/core/memory-engine/control-objects.d.ts +36 -3
  25. package/dist/core/memory-engine/control-objects.js +134 -12
  26. package/dist/core/memory-engine/control-plane-adoption.d.ts +5 -2
  27. package/dist/core/memory-engine/control-plane-adoption.js +5 -3
  28. package/dist/core/memory-engine/delegation-settlement.d.ts +59 -42
  29. package/dist/core/memory-engine/delegation-settlement.js +175 -202
  30. package/dist/core/memory-engine/dual-root.d.ts +3 -2
  31. package/dist/core/memory-engine/dual-root.js +5 -1
  32. package/dist/core/memory-engine/engine.d.ts +16 -10
  33. package/dist/core/memory-engine/engine.js +138 -145
  34. package/dist/core/memory-engine/file-backend.d.ts +17 -11
  35. package/dist/core/memory-engine/file-backend.js +53 -103
  36. package/dist/core/memory-engine/layout.d.ts +129 -49
  37. package/dist/core/memory-engine/layout.js +202 -82
  38. package/dist/core/memory-engine/memory-age.d.ts +12 -0
  39. package/dist/core/memory-engine/memory-age.js +17 -0
  40. package/dist/core/memory-engine/memory-backend-contract.js +5 -4
  41. package/dist/core/memory-engine/memory-deployment.d.ts +1 -1
  42. package/dist/core/memory-engine/origin-clearance.js +1 -5
  43. package/dist/core/memory-engine/tools.d.ts +2 -2
  44. package/dist/core/memory-engine/tools.js +7 -7
  45. package/dist/core/memory-engine/types.d.ts +16 -10
  46. package/dist/core/memory-vector.d.ts +6 -14
  47. package/dist/core/memory.d.ts +0 -462
  48. package/dist/core/memory.js +0 -333
  49. package/dist/core/permission-rule-consent.d.ts +49 -18
  50. package/dist/core/permission-rule-consent.js +59 -38
  51. package/dist/core/permission-rule-store.d.ts +24 -14
  52. package/dist/core/retention.d.ts +2 -7
  53. package/dist/core/retention.js +0 -1
  54. package/dist/core/runner/classifier-ladder.d.ts +3 -1
  55. package/dist/core/runner/classifier-ladder.js +2 -2
  56. package/dist/core/runner/contracts.d.ts +9 -9
  57. package/dist/core/runner/delegation-owner.d.ts +0 -8
  58. package/dist/core/runner/delegation-owner.js +1 -3
  59. package/dist/core/runner/prepare-gate-stations.d.ts +8 -5
  60. package/dist/core/runner/prepare-gate-stations.js +13 -5
  61. package/dist/core/runner/prepare-memory-engine-session.js +1 -1
  62. package/dist/core/runner/prepare-memory.js +9 -9
  63. package/dist/core/runner/prepare-policy-chain.js +11 -3
  64. package/dist/core/runner/prepare-task.d.ts +5 -1
  65. package/dist/core/runner/prepare-task.js +3 -3
  66. package/dist/core/runner/run-notification-lane.js +1 -1
  67. package/dist/core/runner/sub-agent-deny-lists.d.ts +19 -0
  68. package/dist/core/runner/sub-agent-deny-lists.js +25 -0
  69. package/dist/core/secret-env.d.ts +2 -2
  70. package/dist/core/secret-env.js +6 -20
  71. package/dist/core/session-store.d.ts +6 -6
  72. package/dist/core/session-store.js +3 -3
  73. package/dist/core/store-contracts/background-agent-store-contract.js +13 -0
  74. package/dist/core/task-notification.d.ts +35 -8
  75. package/dist/core/task-notification.js +31 -13
  76. package/dist/core/task-registry-agent.js +1 -0
  77. package/dist/core/task-registry-shared.d.ts +4 -0
  78. package/dist/core/tool-errors.d.ts +3 -3
  79. package/dist/core/tool-spec.d.ts +7 -7
  80. package/dist/core/write-protect.d.ts +16 -0
  81. package/dist/core/write-protect.js +10 -0
  82. package/dist/engine/session/repo-utils.d.ts +14 -4
  83. package/dist/engine/session/repo-utils.js +5 -4
  84. package/dist/index.d.ts +6 -6
  85. package/dist/index.js +6 -6
  86. package/dist/prompts/default.d.ts +1 -2
  87. package/dist/scenarios/full-body.d.ts +1 -1
  88. package/dist/stores/file/adoption/adopt.d.ts +1 -1
  89. package/dist/stores/file/index.d.ts +1 -15
  90. package/dist/stores/file/index.js +1 -15
  91. package/dist/stores/file/permission-rule-store.d.ts +12 -1
  92. package/dist/stores/file/permission-rule-store.js +31 -4
  93. package/dist/stores/file/session-store.js +1 -1
  94. package/package.json +2 -2
  95. package/test/export-surface.snapshot.json +9 -73
  96. package/wire-changes/core-stores-sql@7.65.0.json +30 -0
  97. package/wire-changes/core@7.65.0.json +1650 -0
  98. package/wire-changes/mods-kernel@7.65.0.json +30 -0
  99. package/wire-changes/primitives@7.65.0.json +337 -0
  100. package/dist/core/memory-recall.d.ts +0 -208
  101. package/dist/core/memory-recall.js +0 -136
  102. package/dist/stores/file/memory-store.d.ts +0 -124
  103. package/dist/stores/file/memory-store.js +0 -353
@@ -18,7 +18,7 @@ import { emitTrace } from "../trace.js";
18
18
  import { skillGrantBindingMembers } from "../skill-grant.js";
19
19
  import { withArgsBinding } from "../skill-grant-binding.js";
20
20
  import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
21
- import { delegationPoolReading, policyNameRefusal, POLICY_NAME_REFUSAL_CODE } from "./sub-agent-deny-lists.js";
21
+ import { delegationPoolReading, policyNameRefusal, POLICY_NAME_REFUSAL_CODE, retiredToolNameNotice } from "./sub-agent-deny-lists.js";
22
22
  import { valveLeaves } from "../../agents/tool-filter.js";
23
23
  import { autoStrippedRule, cardDisclosureOf, classifiesAllShell, rootFacingToolNames } from "../allow-entry.js";
24
24
  import { arbitrateByMode, askClassMembersOf, askFaceOf, askMandateMember, INHERITED_STATION_FACTS } from "../ask-origin.js";
@@ -48,6 +48,7 @@ export async function preparePolicyChain(input) {
48
48
  const policy = lockedPreflight.toolPolicy;
49
49
  const auditPolicyNames = (auditee, layer = "caller_policy") => {
50
50
  const refused = [];
51
+ const retiredLeftOut = [];
51
52
  const nameGroups = toolPolicyNameSets(auditee);
52
53
  if (nameGroups.length > 0) {
53
54
  const known = mountedToolNames(tools);
@@ -61,8 +62,9 @@ export async function preparePolicyChain(input) {
61
62
  for (const [kind, list] of [["deny", g.deny], ["ask", g.ask], ["allow", g.allow]]) {
62
63
  for (const n of list ?? []) {
63
64
  const verdict = judgeRuleToolName(n, known, kind);
64
- const twin = verdict.kind === "current" && layer !== "ancestor_session_rules" ? nearMissSpellingOf(n, rootFacing) : undefined;
65
- const stale = verdict.kind !== "current" ? verdict : twin !== undefined ? { kind: "case_twin", twin, carrier: known.has(twin) || callerNames.has(twin) ? "run" : pool.names.has(twin) ? "pool" : "catalog" } : undefined;
65
+ const asksTwin = verdict.kind === "current" || (verdict.kind === "retired" && verdict.currentName === undefined && kind !== "allow");
66
+ const twin = asksTwin && layer !== "ancestor_session_rules" ? nearMissSpellingOf(n, rootFacing) : undefined;
67
+ const stale = twin !== undefined ? { kind: "case_twin", twin, carrier: known.has(twin) || callerNames.has(twin) ? "run" : pool.names.has(twin) ? "pool" : "catalog" } : verdict.kind !== "current" ? verdict : undefined;
66
68
  if (stale?.kind === "retired" && kind === "allow") {
67
69
  unmatched.add(`"${n}" (allow — a retired tool name: ${stale.guidance})`);
68
70
  continue;
@@ -71,6 +73,10 @@ export async function preparePolicyChain(input) {
71
73
  unmatched.add(`"${n}" (allow — ${stale.guidance}${stale.currentName !== undefined ? ` Write "${stale.currentName}".` : ""})`);
72
74
  continue;
73
75
  }
76
+ if (stale?.kind === "retired" && stale.currentName === undefined && kind !== "allow") {
77
+ retiredLeftOut.push({ field: kind, entry: n, layer, guidance: stale.guidance });
78
+ continue;
79
+ }
74
80
  if (stale !== undefined) {
75
81
  const entry = `tool policy ${kind}-list entry "${n}"`;
76
82
  let message;
@@ -105,6 +111,8 @@ export async function preparePolicyChain(input) {
105
111
  }
106
112
  if (refused[0] !== undefined)
107
113
  throw policyNameRefusal(refused[0], refused.slice(1));
114
+ if (retiredLeftOut.length > 0)
115
+ deliverEngineNotice(deps.onNotice, retiredToolNameNotice(layer, retiredLeftOut, sessionId));
108
116
  const dedupeKey = [...unmatched].sort().join("|");
109
117
  const advised = advisedPolicyNames.get(deps) ?? new Set();
110
118
  if (unmatched.size > 0 && !advised.has(dedupeKey)) {
@@ -8,6 +8,7 @@ export { DEFAULT_IRREVERSIBLE_SCOPE, checkpointScopeOf, placementValueOrAbsent }
8
8
  export { mcpManifestEntries } from "./prepare-wiring-manifest.js";
9
9
  export { __resetMaterializeEnvAnnouncements } from "./prepare-tool-disclosure-mount.js";
10
10
  export { fileHistoryFilesystemIdentity, resolveFileHistoryScope } from "./prepare-file-history.js";
11
+ import { type NoticeDestinationJudge } from "../task-notification.js";
11
12
  import type { RunnerSelfSeat } from "./contracts.js";
12
13
  import type { Prepared, PrepareResume, PrepareTaskFn, RunInternals } from "./contracts.js";
13
14
  export type { FileHistoryBoundarySeat, InheritedGate, Prepared, PreparedMicroCompact, PrepareResume, ResolvedWorkspace, RunInternals, UsageGovernance } from "./contracts.js";
@@ -118,7 +119,10 @@ runIdSink?: {
118
119
  /** The Runner's lock on this leg's session, handed only when the spec named none: taken the moment the store mints the id. */
119
120
  holdSessionLock?: (sessionId: string) => Promise<void>,
120
121
  /** This leg's view of the Runner's session write ledger (`session-write-ledger.ts`): the acquired storage writes through it. */
121
- legWrites?: LegWrites): Promise<Prepared>;
122
+ legWrites?: LegWrites,
123
+ /** The Runner's judge of where this leg's user-face notices go when they are routed to its tree's root (its in-process
124
+ * notification store's): absent when prepareTask runs outside a Runner, and then every notice is delivered. */
125
+ noticeDestinations?: NoticeDestinationJudge): Promise<Prepared>;
122
126
  /** The entry IS the contract the notification lane's seat names ({@link PrepareTaskFn}, contracts.ts):
123
127
  * a signature change reds HERE, at the declaration, as `false` failing the `true` bound. IDENTITY, not assignability:
124
128
  * the parameter tuple (arity, optionality, each type) and the return type must be the SAME type in both directions —
@@ -304,7 +304,7 @@ function refuseRegistryScopeMismatch(spec, internals) {
304
304
  function validateInputFaultNotice(onError, sessionId) {
305
305
  return ({ toolName, toolCallId, error }) => onError?.(new Error(`tool input pre-validation (validateInput) threw for ${toolName} (call ${toolCallId}) — read as no verdict; the call proceeded to the gate: ${thrownText(error)}`), { phase: "hook", sessionId });
306
306
  }
307
- export async function prepareTask(request, deps, sessions, resume, internals, runnerSelf, runIdSink, holdSessionLock, legWrites) {
307
+ export async function prepareTask(request, deps, sessions, resume, internals, runnerSelf, runIdSink, holdSessionLock, legWrites, noticeDestinations) {
308
308
  const runId = uuidv7();
309
309
  if (runIdSink !== undefined)
310
310
  runIdSink.runId = runId;
@@ -368,7 +368,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
368
368
  internals = restoreRowTaskId(internals, resume?.seed.rowTaskId);
369
369
  const hostTaskId = legTaskIdOf(spec, internals, sessionId);
370
370
  const askSource = mintAskSourceIdentity({ principal: spec.principal, sessionId, taskId: hostTaskId, isDelegatedChild: delegation.isDelegatedChild, internals });
371
- const noticeAddress = noticeAddressOf(askSource, internals?.rootSessionId);
371
+ const noticeRoute = noticeAddressOf(askSource, internals);
372
372
  announceRoleSeatsDefaulted({ spec, deps, onceLedger, rootLeg: !delegation.isDelegatedChild, sessionId, runId });
373
373
  const placementRootResolved = (internals = restorePlacementRoot(internals, resume?.seed.placementRootSessionId))?.placementRoot ?? internals?.rootSessionId ?? sessionId;
374
374
  const compositionLegResolved = compositionLegRecord(internals?.compositionLeg ?? resume?.seed.compositionLeg);
@@ -874,7 +874,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
874
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 });
875
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 });
876
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() })) } } });
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 });
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, noticeRoute, noticeDestinations, 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 });
878
878
  const postureFrameRef = { report: (err) => deps.onError?.(err, { phase: "degraded", sessionId }) };
879
879
  const frameReceipts = { pending: [], listingSnapshotOwed: false };
880
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 } : {}) });
@@ -152,7 +152,7 @@ async function runNotificationLaneAs(input, obligations) {
152
152
  sessionReadStates,
153
153
  sessionModeSeats,
154
154
  onTaskNotification: laneSink,
155
- }, self, taskIdRef, holdSessionLock, legWrites);
155
+ }, self, taskIdRef, holdSessionLock, legWrites, (destination, delivery) => pendingSessionNotifications.discardsStaleNotice(destination, delivery));
156
156
  pendingSessionNotifications.admit(sessionAddressOf(prepared), prepared.sessionBox);
157
157
  const settling = pendingSessionNotifications.settleBoxDebts(sessionAddressOf(prepared), prepared.abortController.signal);
158
158
  if (settling !== undefined)
@@ -35,6 +35,7 @@
35
35
  */
36
36
  import type { AgentTool } from "../../internal/harness.js";
37
37
  import { valveLeaves } from "../../agents/tool-filter.js";
38
+ import type { EngineNotice } from "../engine-notice.js";
38
39
  import { type ProtocolId } from "../protocol-table.js";
39
40
  import type { ToolLegKind, ToolSelector, ToolSelectorLayer } from "../tool-face.js";
40
41
  import { type ConstraintChainEntry } from "../tool-policy.js";
@@ -103,6 +104,24 @@ export interface PolicyNameFinding {
103
104
  * the first entry's, `detail.problems` lists the refused entries of the layer in scan order (within the bounds above), `detail.total`
104
105
  * counts every one. */
105
106
  export declare function policyNameRefusal(first: PolicyNameFinding, more: readonly PolicyNameFinding[]): Error;
107
+ /** One entry of a restricting policy list (`deny` / `ask`) that names a tool the engine retired with no successor to write: the name
108
+ * matches nothing in any roster, so the audit leaves the entry out and says so ({@link retiredToolNameNotice}) instead of refusing
109
+ * the run. `guidance` is the retirement table's own line for the name. */
110
+ export interface RetiredPolicyEntry {
111
+ readonly field: "deny" | "ask";
112
+ readonly entry: string;
113
+ readonly layer: PolicyNameLayer;
114
+ readonly guidance: string;
115
+ }
116
+ /**
117
+ * The notice for the entries of one policy layer's deny or ask list that name a retired tool (`config.legacy_tool_name`, audience
118
+ * `user` — the person who wrote the entry believes it guards a tool): the audit left them out, they reach no tool in any roster, and the
119
+ * run goes on. One notice per audited layer per prepared task, minted here and nowhere else. `detail: { layer, entries: [{ field,
120
+ * entry, layer, guidance }], total, sessionId }` — `entries` are unique by (field, entry) in scan order, at most
121
+ * {@link RETIRED_NOTICE_ENTRIES_SHOWN}, `total` counts every one. The entries that name a tool the engine renamed are not here: their
122
+ * names have a successor, the entry guarded it, and the audit still refuses them.
123
+ */
124
+ export declare function retiredToolNameNotice(layer: PolicyNameLayer, entries: readonly RetiredPolicyEntry[], sessionId: string): EngineNotice;
106
125
  /**
107
126
  * The names a definition's denied-tools entries stand for, for a lane that has neither a roster nor a notice sink at the point
108
127
  * it builds its own policy (a workflow leg's agentType): each entry is read by the one reading, so `Tool(content)` denies the
@@ -84,6 +84,31 @@ export function policyNameRefusal(first, more) {
84
84
  e.detail = { problems: listed.slice(0, POLICY_NAME_PROBLEMS_SHOWN), total: 1 + more.length };
85
85
  return e;
86
86
  }
87
+ const LAYER_WORD = {
88
+ caller_policy: "the run's tool policy",
89
+ session_rules: "the session's stored permission rules",
90
+ ancestor_session_rules: "the stored permission rules of an ancestor session",
91
+ };
92
+ const RETIRED_NOTICE_ENTRIES_SHOWN = 32;
93
+ export function retiredToolNameNotice(layer, entries, sessionId) {
94
+ const unique = [];
95
+ const seen = new Set();
96
+ for (const e of entries) {
97
+ const key = `${e.field}\u0000${e.entry}`;
98
+ if (seen.has(key))
99
+ continue;
100
+ seen.add(key);
101
+ unique.push(e);
102
+ }
103
+ const one = unique.length === 1;
104
+ const shown = unique.slice(0, 5).map((e) => `${e.field}-list entry "${e.entry}"`);
105
+ const more = unique.length > shown.length ? ` and ${unique.length - shown.length} more` : "";
106
+ return {
107
+ code: POLICY_NAME_REFUSAL_CODE,
108
+ message: `${LAYER_WORD[layer]} holds ${shown.join(", ")}${more}, ${one ? "a RETIRED tool name" : "RETIRED tool names"} that ${one ? "reaches" : "reach"} no tool in this run's roster — ${one ? "it guards" : "they guard"} nothing, and the run goes on without ${one ? "it" : "them"}. Remove ${one ? "the entry" : "the entries"} from the list.`,
109
+ detail: { layer, entries: unique.slice(0, RETIRED_NOTICE_ENTRIES_SHOWN).map((e) => ({ field: e.field, entry: e.entry, layer: e.layer, guidance: e.guidance })), total: unique.length, sessionId },
110
+ };
111
+ }
87
112
  const LIST_WORD = { allowed: "allowed tools", denied: "denied tools" };
88
113
  const NEAR_MISS_EFFECT = {
89
114
  allowed: "it admits nothing, so the tool it was written for is not granted",
@@ -23,8 +23,8 @@ import { type RedactionConfidence, type RedactionSource } from "@sema-agent/prim
23
23
  import { type EngineNotice } from "./engine-notice.js";
24
24
  /** Does a value carry a credential? A URL userinfo (after every `scheme://`, and a leading `//`) with a password or a
25
25
  * token-like user; a scheme-less `user:password@host`; a credential assignment; a webhook URL; a Sonar login; a
26
- * private-key header; an `Authorization` header, `token …`, `Bearer …` or `Basic …` with credential-shaped content.
27
- * Reads the first {@link VALUE_SCAN_LIMIT} code units. The value half of the judgment, exported apart from the env
26
+ * private-key header; an `Authorization` header, `token …`, `Bearer …` or `Basic …` with credential-shaped content (the
27
+ * value forms are the vocabulary's rows, {@link ENV_VALUES}). Reads the first {@link VALUE_SCAN_LIMIT} code units. The value half of the judgment, exported apart from the env
28
28
  * entry's exemptions ({@link isExemptEnvName}): a caller holding a value that is no environment variable asks this. */
29
29
  export declare function looksLikeCredentialValue(value: string): boolean;
30
30
  /** Which rule withheld an entry: one of the scrub's rules, or `own-credential` — the entry is one of the engine's own
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { types } from "node:util";
3
- import { CREDENTIAL_MIN_CHARS, envNameView, isSensitiveHeaderName, splitCamelCase } from "@sema-agent/primitives";
3
+ import { CREDENTIAL_MIN_CHARS, envNameView, envValueView, isSensitiveHeaderName, splitCamelCase } from "@sema-agent/primitives";
4
4
  import { DEFAULT_INHERITED_ENV_VARS } from "@modelcontextprotocol/client/stdio";
5
5
  import { deliverEngineNotice } from "./engine-notice.js";
6
6
  import { optionKeys, receiveMembers } from "./own-property-receipt.js";
@@ -10,6 +10,7 @@ function isExemptEnvName(name) {
10
10
  return GIT_CONFIG_ENV_RE.test(name) || PROXY_ENV_RE.test(name);
11
11
  }
12
12
  const ENV_NAMES = envNameView();
13
+ const ENV_VALUES = envValueView();
13
14
  const OTEL_ENV_RE = /^(?:INPUT_)?OTEL_/i;
14
15
  const SEMA_NAMESPACE_SECRET_RE = ENV_NAMES.anySegmentUnder("SEMA_");
15
16
  const BUNDLER_SETTINGS = ["BUILD", "LOCAL", "MIRROR", "PATH", "WITH", "WITHOUT", "CACHE", "DISABLE", "IGNORE", "ONLY"];
@@ -33,7 +34,7 @@ function nameIsCredentialShaped(name) {
33
34
  }
34
35
  const VALUE_SCAN_LIMIT = 8192;
35
36
  function looksLikeToken(user) {
36
- return ENV_NAMES.tokenPrefix.test(user) || (user.length >= 20 && /[0-9]/.test(user) && /[a-z]/i.test(user));
37
+ return ENV_VALUES.tokenHead.test(user) || (user.length >= 20 && /[0-9]/.test(user) && /[a-z]/i.test(user));
37
38
  }
38
39
  const HOST_RE = /^(?:localhost|[a-z0-9_-]+(?:\.[a-z0-9_-]+)*\.(?=[a-z0-9-]*[a-z])[a-z0-9-]+|[a-z0-9_.-]+(?=:\d+(?:[/?#]|$))|\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i;
39
40
  const HOSTLIKE_RE = /^(?:(?=[a-z0-9._-]*[a-z])[a-z0-9._-]+|\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i;
@@ -69,14 +70,6 @@ function carriesSchemelessUserinfo(text) {
69
70
  const at = text.lastIndexOf("@", text.search(/\s|$/));
70
71
  return !isHostPortPathBeforeAt(text.slice(0, at), text.slice(at + 1)) && !/^(?:mailto|sips?|xmpp|im|acct):/i.test(text);
71
72
  }
72
- const FLAG_WORDS = ["true", "false", "none", "null", "yes", "no", "on", "off", "enabled", "disabled", "required", "optional"];
73
- const CREDENTIAL_ASSIGNMENT_RE = new RegExp(String.raw `(?:(?:^|[;&?#,{]|\/:)\s*|\s)["']?(?!-*jobserver-auth\s*[=:])(?:[a-z0-9_.-]{0,64}(?:password|passwd|pwd|secret|token|(?:account|access|api|private|subscription)[-_]?key|signature|sig|credential)|[a-z0-9_.-]{0,63}[_.-]auth)["']?\s*[=:]\s*["']?(?!(?:${FLAG_WORDS.join("|")})(?:$|[;&,\s"']))[^;&,\s"']+`, "i");
74
- const WEBHOOK_URL_RE = /https:\/\/(?:hooks\.slack\.com\/(?:services|workflows|triggers)\/|(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/|[\w.-]+\.webhook\.office\.com\/webhookb2\/)[\w\/@.~-]{16,}/i;
75
- const SONAR_LOGIN_RE = new RegExp(String.raw `["']?sonar\.login["']?\s*[:=]\s*["']?[^\s"',}]{${CREDENTIAL_MIN_CHARS},}`);
76
- const PRIVATE_KEY_HEADER_RE = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
77
- const AUTHORIZATION_HEADER_RE = new RegExp(String.raw `\bauthorization\s*[:=]\s*["']?[a-z][a-z0-9_-]*\s+[A-Za-z0-9._~+\/=-]{${CREDENTIAL_MIN_CHARS},}`, "i");
78
- const TOKEN_WORD_RE = /\b(?:[Tt]oken|TOKEN)\s+(?=[A-Za-z0-9_~+=-]*[0-9])(?=[A-Za-z0-9_~+=-]*[A-Z])(?=([A-Za-z0-9_~+=-]{20,}))\1(?![\/.])/;
79
- const BEARER_BASIC_RE = new RegExp(String.raw `\b(?:Bearer|Basic)\s+(?=[A-Za-z._~+\/=-]*[0-9]|(?:[A-Za-z0-9._~+\/=-]*?[a-z][A-Z](?![a-z])){2}|[A-Za-z0-9.-]*[_~+\/=])[A-Za-z0-9._~+\/=-]{${CREDENTIAL_MIN_CHARS},}`);
80
73
  export function looksLikeCredentialValue(value) {
81
74
  const text = value.length > VALUE_SCAN_LIMIT ? value.slice(0, VALUE_SCAN_LIMIT) : value;
82
75
  for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 3)) {
@@ -85,14 +78,7 @@ export function looksLikeCredentialValue(value) {
85
78
  }
86
79
  if (text.startsWith("//") && authorityCarriesCredential(text.slice(2)))
87
80
  return true;
88
- return (carriesSchemelessUserinfo(text) ||
89
- CREDENTIAL_ASSIGNMENT_RE.test(text) ||
90
- WEBHOOK_URL_RE.test(text) ||
91
- SONAR_LOGIN_RE.test(text) ||
92
- PRIVATE_KEY_HEADER_RE.test(text) ||
93
- AUTHORIZATION_HEADER_RE.test(text) ||
94
- TOKEN_WORD_RE.test(text) ||
95
- BEARER_BASIC_RE.test(text));
81
+ return carriesSchemelessUserinfo(text) || ENV_VALUES.forms.some((form) => form.re.test(text));
96
82
  }
97
83
  const OWN_CREDENTIAL = "the engine's own service credential";
98
84
  const SECRET_ENV_KIND_CONFIDENCE = {
@@ -197,7 +183,7 @@ function runtimeSuppliedHolderOf(value) {
197
183
  const supplied = policyArm([...runtimeSuppliedEnv()]);
198
184
  return Object.keys(supplied).find((k) => supplied[k] === value);
199
185
  }
200
- const PLACEHOLDER_KEY_WORDS = new Set([...FLAG_WORDS, "undefined", "placeholder", "lm-studio", "not-needed", "sk-no-key-required"]);
186
+ const PLACEHOLDER_KEY_WORDS = new Set([...ENV_VALUES.flagWords, "undefined", "placeholder", "lm-studio", "not-needed", "sk-no-key-required"]);
201
187
  const ONE_REPEATED_CHARACTER_RE = /^(\S)\1{2,}$/u;
202
188
  export function isBlankCredential(value) {
203
189
  return value.trim() === "";
@@ -210,7 +196,7 @@ function notACredentialReason(value) {
210
196
  return `a string of fewer than ${CREDENTIAL_MIN_CHARS} characters, which names no secret`;
211
197
  if (PLACEHOLDER_KEY_WORDS.has(text.toLowerCase()))
212
198
  return "a flag or placeholder word, which names no secret";
213
- if (ONE_REPEATED_CHARACTER_RE.test(text.replace(ENV_NAMES.tokenPrefix, "")))
199
+ if (ONE_REPEATED_CHARACTER_RE.test(text.replace(ENV_VALUES.tokenHead, "")))
214
200
  return "one character repeated, which names no secret";
215
201
  return undefined;
216
202
  }
@@ -182,12 +182,12 @@ export declare class TtlSessionStore implements SessionStore {
182
182
  placement?: SessionPlacement;
183
183
  }): Promise<AcquiredSession>;
184
184
  /** The one judgement of "does this cached view still stand for this row": `shown` is the view's session metadata and `row` the row as
185
- * a read of it answered (a listed row, or the repo's head; `undefined` = no row, or no read of one). A row naming the view's
186
- * occupant (`compareOccupants`) stands for it; a row naming another does not; and a row naming a different owner does not either —
187
- * the owner is recorded once, by the write that creates the row, so another owner's row is another row whatever it names. When
188
- * the evidence says neither (unknown) the answer is the repo's: over one with a head read the row can always be read again, so a
189
- * view without positive proof is dropped and the id resolved from the row; over one with no head read (it mints no occupant token)
190
- * the cached view is the only evidence of the occupant, and it stands. */
185
+ * a read of it answered (a listed row, or the repo's head; `undefined` = no row, or no read of one). A row naming another occupant
186
+ * (`compareOccupants` — the same token, or no token on either side, is one occupant) does not stand for it; neither does a row
187
+ * naming a different owner — the owner is recorded once, by the write that creates the row, so another owner's row is another row
188
+ * whatever it names; any other row does. With no row to judge (unknown) the answer is the repo's: over one with a head read the row
189
+ * can always be read again, so the view is dropped and the id resolved from the row; over one with no head read the cached view is
190
+ * the only evidence of the occupant, and it stands. */
191
191
  private viewStandsFor;
192
192
  /** Whether a cached view is still the occupant the row holds ({@link viewStandsFor}, over the row's head read in one read) and still
193
193
  * the log it holds — the row's leaf is the view's: a log replaced under the same occupant (a cross-backend move's commit, through
@@ -139,11 +139,11 @@ export class TtlSessionStore {
139
139
  }
140
140
  viewStandsFor(shown, row) {
141
141
  const verdict = compareOccupants(shown, row);
142
- if (verdict !== "unknown")
143
- return verdict === "same";
142
+ if (verdict === "different")
143
+ return false;
144
144
  if (row !== undefined && (shown.owner ?? null) !== (row.owner ?? null))
145
145
  return false;
146
- return this.repoHead === undefined;
146
+ return verdict === "same" || this.repoHead === undefined;
147
147
  }
148
148
  async standingRow(sessionId, cached) {
149
149
  if (this.repoHead === undefined)
@@ -99,6 +99,19 @@ export async function backgroundAgentStoreContract(mk, runAssertion) {
99
99
  assert.deepEqual(after.policyFloor, before.policyFloor, `a CAS update must carry the floor it did not change (${handle})`);
100
100
  }
101
101
  });
102
+ run("the root anchor's occupant round-trips beside the anchor — ABSENT stays absent, a CAS carries it", async (make) => {
103
+ const store = make();
104
+ await store.put(record({ handle: "a1", rootSessionId: "sess-root", rootSessionIncarnation: "occ-root-1" }));
105
+ const withOccupant = await held(store, "a1");
106
+ assert.equal(withOccupant.rootSessionId, "sess-root");
107
+ assert.equal(withOccupant.rootSessionIncarnation, "occ-root-1");
108
+ await store.put(record({ handle: "a2", rootSessionId: "sess-root" }));
109
+ const without = await held(store, "a2");
110
+ assert.equal(without.rootSessionIncarnation, undefined, "a row that records no root occupant must not read back with one");
111
+ const after = { ...withOccupant, status: "completed", settledAt: 2_000 };
112
+ assert.equal(await store.update("a1", S, after, { rev: withOccupant.rev }), true);
113
+ assert.equal((await held(store, "a1")).rootSessionIncarnation, "occ-root-1", "a CAS update must carry the root occupant it did not change");
114
+ });
102
115
  run("put refuses a scopeless row (a row with no tenant partition would be world-readable)", async (make) => {
103
116
  const store = make();
104
117
  await assert.rejects(store.put(record({ scope: "" })), "an empty scope must be refused loudly, not stored");
@@ -523,15 +523,31 @@ export declare function sessionAddressOf(leg: {
523
523
  readonly sessionIncarnation?: string;
524
524
  readonly sessionIncarnationUnread?: true;
525
525
  }): SessionAddress;
526
- /** Which seat a frame addressed to an earlier occupant of a session would have reached under the occupant the session
527
- * holds now: that occupant's live run, its durable box, or its next run's turn-open drain. */
528
- export type DiscardedDeliveryPath = "live" | "box" | "drain";
526
+ /** The words {@link DiscardedDeliveryPath} is made of, as a value (#3505): the closed set a host reads off
527
+ * `delegation.delivery_discarded`'s `detail.path` against, so it does not copy the four words by hand. Root-exported. */
528
+ export declare const DISCARDED_DELIVERY_PATHS: readonly ["live", "box", "drain", "notice"];
529
+ /** Which seat a delivery addressed to an earlier occupant of a session would have reached under the occupant the session
530
+ * holds now: for a frame, that occupant's live run, its durable box, or its next run's turn-open drain; for a delegated leg's
531
+ * user-face notice addressed to its tree's root, the notice sink that routes it to the root session (`notice`). Derived from
532
+ * {@link DISCARDED_DELIVERY_PATHS}, so the type and the value are one set. */
533
+ export type DiscardedDeliveryPath = (typeof DISCARDED_DELIVERY_PATHS)[number];
534
+ /** What a discarded delivery was, by name only: a frame's task (its id and type), or a delegated leg's user-face notice (the
535
+ * leg it came from — its agent id, else its session — and the notice's code). */
536
+ export interface DiscardedDelivery {
537
+ readonly taskId: string;
538
+ readonly taskType: string;
539
+ }
540
+ /** The Runner's judge of a delegated leg's notice destination ({@link PendingSessionNotifications.discardsStaleNotice}): `true`
541
+ * = the notice is addressed to an occupant the root no longer holds, and was discarded and announced. */
542
+ export type NoticeDestinationJudge = (destination: SessionAddress, delivery: DiscardedDelivery) => boolean;
543
+ /** A frame's name as a discarded delivery: its task id and type, nothing of its text. */
544
+ export declare function frameDelivery(payload: TaskNotificationPayload): DiscardedDelivery;
529
545
  /**
530
- * The account of a frame discarded because its address names an occupant the session no longer holds — the one mint of
531
- * `delegation.delivery_discarded`. Counts and words only: the frame's text (a child's summary, a peer's words) never
532
- * rides it, nor either occupant token (only whether each side had one).
546
+ * The account of a delivery discarded because its address names an occupant the session no longer holds — the one mint of
547
+ * `delegation.delivery_discarded`. Counts and words only: the delivery's text (a child's summary, a peer's words, a notice's
548
+ * sentence) never rides it, nor either occupant token (only whether each side had one).
533
549
  */
534
- export declare function deliveryDiscardedNotice(address: Pick<SessionAddress, "sessionId" | "occupant">, current: string | undefined, payload: TaskNotificationPayload, path: DiscardedDeliveryPath): EngineNotice;
550
+ export declare function deliveryDiscardedNotice(address: Pick<SessionAddress, "sessionId" | "occupant">, current: string | undefined, delivery: DiscardedDelivery, path: DiscardedDeliveryPath): EngineNotice;
535
551
  /**
536
552
  * A session's DURABLE box, bound to the park seat by the leg that mounts its session-box drain — one
537
553
  * mint (the drain mount judgment), two readers (the drain and {@link routeOrParkNotification}), so
@@ -933,7 +949,18 @@ export declare class PendingSessionNotifications {
933
949
  * address (a leg that could not read its occupant) is nobody's: its frames are discarded the same way, whatever the seat.
934
950
  */
935
951
  discardsStale(address: SessionAddress, payload: TaskNotificationPayload): boolean;
936
- /** The one place a discarded frame is announced. */
952
+ /**
953
+ * The same question for a delegated leg's user-face notice, addressed to its tree's root: is `destination` (the root's id
954
+ * and the occupant the tree was born under) an earlier occupant of a session whose current occupant is another? Then the
955
+ * notice is discarded — announced with path `notice` — and the answer is `true`: the leg delivers nothing. `false` for the
956
+ * current occupant, and for a root no leg of which this process admitted. A notice cannot wait for the root's next leg
957
+ * the way a frame parks, so a root that was created again but not yet admitted here is not known to be another occupant.
958
+ */
959
+ discardsStaleNotice(destination: SessionAddress, delivery: DiscardedDelivery): boolean;
960
+ /** The one judgement both discards read: `undefined` when `address` is the session's current occupant, or the session has
961
+ * none on record; else the seat it was judged against (absent for an unread address on a session with no seat). */
962
+ private staleAgainst;
963
+ /** The one place a discarded delivery is announced. */
937
964
  private announceDiscard;
938
965
  /** Discard a record parked for an occupant the session no longer holds: every frame in it is announced; the record's own
939
966
  * bookkeeping (its eviction counts, its box debts) belongs to that occupant and goes with it. */
@@ -5,7 +5,7 @@ import { redactThenCut } from "../agents/subagent-steps.js";
5
5
  import { PEER_MESSAGE_NOTICE } from "../agents/peer-admission.js";
6
6
  import { buildCrossSessionEnvelope, CROSS_PRINCIPAL_MESSAGE_NOTICE, CROSS_SESSION_MESSAGE_NOTICE, neutralizePeerBody } from "../agents/cross-session-envelope.js";
7
7
  import { deliverEngineNotice } from "./engine-notice.js";
8
- import { sameOccupant } from "./runner/delegation-owner.js";
8
+ import { sameOccupant } from "../engine/session/repo-utils.js";
9
9
  export const TASK_NOTIFICATION_TERMINAL_STATUSES = Object.freeze(["completed", "failed", "killed", "cancelled"]);
10
10
  export const NOTIFICATION_INJECTION_OUTCOMES = Object.freeze(["queued", "parked", "parked_durably", "dropped_duplicate", "refused"]);
11
11
  export function isNotificationInjectionOutcome(value) {
@@ -168,17 +168,21 @@ export const MAX_SESSION_BOX_BINDINGS = 4096;
168
168
  export function sessionAddressOf(leg) {
169
169
  return { sessionId: leg.sessionId, occupant: leg.sessionIncarnation, ...(leg.sessionIncarnationUnread === true ? { unread: true } : {}) };
170
170
  }
171
- export function deliveryDiscardedNotice(address, current, payload, path) {
171
+ export const DISCARDED_DELIVERY_PATHS = Object.freeze(["live", "box", "drain", "notice"]);
172
+ export function frameDelivery(payload) {
173
+ return { taskId: payload.task_id, taskType: payload.task_type };
174
+ }
175
+ export function deliveryDiscardedNotice(address, current, delivery, path) {
172
176
  return {
173
177
  code: "delegation.delivery_discarded",
174
- message: `a ${inlineUntrusted(String(payload.task_type), 40)} frame of task ${inlineUntrusted(String(payload.task_id), 120)} was addressed to session ${inlineUntrusted(address.sessionId, 120)} under an occupant the session does not hold now (the id was deleted and created again, or the address carried no occupant), so it was discarded, not delivered`,
178
+ message: `a ${inlineUntrusted(String(delivery.taskType), 40)} ${path === "notice" ? "notice" : "frame"} of task ${inlineUntrusted(String(delivery.taskId), 120)} was addressed to session ${inlineUntrusted(address.sessionId, 120)} under an occupant the session does not hold now (the id was deleted and created again, or the address carried no occupant), so it was discarded, not delivered`,
175
179
  detail: {
176
- taskId: payload.task_id,
177
- taskType: payload.task_type,
180
+ taskId: delivery.taskId,
181
+ taskType: delivery.taskType,
178
182
  sessionId: address.sessionId,
179
183
  path,
180
- addressed: address.occupant !== undefined ? "known" : "unknown",
181
- current: current !== undefined ? "known" : "unknown",
184
+ addressed: sameOccupant(address.occupant, undefined) ? "unknown" : "known",
185
+ current: sameOccupant(current, undefined) ? "unknown" : "known",
182
186
  },
183
187
  };
184
188
  }
@@ -550,22 +554,36 @@ export class PendingSessionNotifications {
550
554
  return seat !== undefined && sameOccupant(seat.occupant, address.occupant) ? seat.box : undefined;
551
555
  }
552
556
  discardsStale(address, payload) {
553
- const seat = this.seats.get(address.sessionId);
554
- if (address.unread !== true && (seat === undefined || sameOccupant(address.occupant, seat.occupant)))
557
+ const stale = this.staleAgainst(address);
558
+ if (stale === undefined)
555
559
  return false;
560
+ const { seat } = stale;
556
561
  const current = { sessionId: address.sessionId, occupant: seat?.occupant };
557
562
  const path = seat !== undefined && this.liveLanes.holds(current) ? "live" : seat?.box !== undefined && parksDurably(payload, seat.box) ? "box" : "drain";
558
- this.announceDiscard(address, seat?.occupant, payload, path);
563
+ this.announceDiscard(address, seat?.occupant, frameDelivery(payload), path);
564
+ return true;
565
+ }
566
+ discardsStaleNotice(destination, delivery) {
567
+ const stale = this.staleAgainst(destination);
568
+ if (stale === undefined)
569
+ return false;
570
+ this.announceDiscard(destination, stale.seat?.occupant, delivery, "notice");
559
571
  return true;
560
572
  }
561
- announceDiscard(address, current, payload, path) {
562
- deliverEngineNotice(this.noticeSeat(), deliveryDiscardedNotice(address, current, payload, path));
573
+ staleAgainst(address) {
574
+ const seat = this.seats.get(address.sessionId);
575
+ if (address.unread !== true && (seat === undefined || sameOccupant(address.occupant, seat.occupant)))
576
+ return undefined;
577
+ return { seat };
578
+ }
579
+ announceDiscard(address, current, delivery, path) {
580
+ deliverEngineNotice(this.noticeSeat(), deliveryDiscardedNotice(address, current, delivery, path));
563
581
  }
564
582
  discardRecord(sessionId, record, current) {
565
583
  if (this.sessions.get(sessionId) === record)
566
584
  this.sessions.delete(sessionId);
567
585
  for (const n of record.items)
568
- this.announceDiscard({ sessionId, occupant: record.occupant }, current, n, "drain");
586
+ this.announceDiscard({ sessionId, occupant: record.occupant }, current, frameDelivery(n), "drain");
569
587
  }
570
588
  recordOf(address) {
571
589
  const s = this.sessions.get(address.sessionId);
@@ -450,6 +450,7 @@ export function registerBackgroundAgentLane(core, input) {
450
450
  sessionScoped: input.sessionScoped === true,
451
451
  ...(input.parentSessionId !== undefined ? { parentSessionId: input.parentSessionId } : {}),
452
452
  ...(input.rootSessionId !== undefined ? { rootSessionId: input.rootSessionId } : {}),
453
+ ...(input.rootSessionId !== undefined && input.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: input.rootSessionIncarnation } : {}),
453
454
  ...(input.parentTaskId !== undefined ? { parentTaskId: input.parentTaskId } : {}),
454
455
  name,
455
456
  ...(input.agentType !== undefined ? { agentType: input.agentType } : {}),
@@ -948,6 +948,10 @@ export interface RegisterBackgroundAgentInput extends TaskAccess {
948
948
  * internals chain; equals parentSessionId at depth 1). Persisted on the handle, the durable row
949
949
  * and the roster so recovery faces enumerate the whole tree under the root without alias walks. */
950
950
  rootSessionId?: string;
951
+ /** The occupant of {@link rootSessionId}'s row as the spawning tree holds it (the spawner's `ctx.rootSessionIncarnation`):
952
+ * persisted on the durable row beside the anchor (`BackgroundAgentRecord.rootSessionIncarnation`), so a revival addresses
953
+ * its subtree's escalations to the occupant the tree was born under. Written only together with {@link rootSessionId}. */
954
+ rootSessionIncarnation?: string;
951
955
  /** design/151 S3b — the revival lookup key (CC meta-sidecar shape): the model RECORD KEY,
952
956
  * persisted on the durable row so a tier-3 revival rebuilds the spec the way a fresh
953
957
  * named-teammate spawn would. A lookup key only, never a serialized spec. `model` is NOT the
@@ -103,9 +103,9 @@ export declare function formatToolError(error: unknown): string;
103
103
  * `memory.admission_required`/`_denied` are EXACT codes, not a broad `memory.` prefix —
104
104
  * falsification review (A-005.3 follow-up) caught an
105
105
  * earlier draft folding EVERY `memory.*` code here, which misclassified the
106
- * memory-engine's non-governance incident codes (`memory.secret_detected` et al.,
107
- * explicitly listed as NON-governance in `NON_GOVERNANCE_MEMORY_CODES` — a content-safety
108
- * tool-call refusal, not a task-spec rejection) as configuration failures. `usage.*` STAYS
106
+ * memory-engine's non-governance incident codes (`memory.announce_failed` et al.,
107
+ * explicitly listed as NON-governance in `NON_GOVERNANCE_MEMORY_CODES` — engine incidents,
108
+ * not task-spec rejections) as configuration failures. `usage.*` STAYS
109
109
  * a broad prefix: governance-codes.ts's own `governanceRetryClass` already treats every
110
110
  * `usage.*` code (registered or not) as governance by prefix — a deliberate legacy-family
111
111
  * rule this folder mirrors rather than re-deciding (questioned whether that
@@ -16,7 +16,7 @@ import type { TaskSpec } from "./task-spec.js";
16
16
  import type { BackgroundChildEvent } from "./delegation-frames.js";
17
17
  import type { ModelRef } from "./model-seat.js";
18
18
  import type { ToolFamily, ToolHostTarget, ToolPathTarget, ToolRenderHints, ToolRuleFace } from "./tool-face.js";
19
- import type { MemoryGovernanceDocs } from "./memory-engine/types.js";
19
+ import type { MemoryGovernanceStore } from "./memory-engine/types.js";
20
20
  /**
21
21
  * Side-effect class of a tool. Used by wake/resume reconciliation: when a call was interrupted
22
22
  * before its result was recorded, the outcome is unknown, so core must decide whether re-doing it
@@ -673,12 +673,11 @@ export interface NestedUsageAccum {
673
673
  * carry knownness alongside the number it qualifies. */
674
674
  anyUnpriced: boolean;
675
675
  }
676
- /** {@link ToolExecuteContext.delegationSettlement}'s answer: where a delegation's settlement rows are kept (the WRITE
677
- * plane's governance store), that plane's control-plane directory (the pollution marker and the hold custody files a
678
- * settled delegation's effects reach), and the session whose rows they are. */
676
+ /** {@link ToolExecuteContext.delegationSettlement}'s answer: the WRITE plane's governance store — where a delegation's
677
+ * settlement rows are kept and where the effects a settled delegation reaches land (the session's pollution marker) —
678
+ * and the session whose rows they are. */
679
679
  export interface DelegationSettlementSeat {
680
- readonly governance: MemoryGovernanceDocs;
681
- readonly controlDir: string;
680
+ readonly governance: MemoryGovernanceStore;
682
681
  readonly sessionId: string;
683
682
  }
684
683
  export interface ToolExecuteContext {
@@ -711,7 +710,8 @@ export interface ToolExecuteContext {
711
710
  rootSessionId?: string;
712
711
  /** The occupant (`SessionMetadata.incarnation`) of the session the fixed point above names (`rootSessionId ?? sessionId`)
713
712
  * as this tree holds it — Runner-filled, trusted. A spawn hands it down beside the root anchor
714
- * (`RunInternals.rootSessionIncarnation`); absent = unknown (a row minted before occupants, a revival's tree). */
713
+ * (`RunInternals.rootSessionIncarnation`) and a background spawn persists it on its row, where a revival reads it back;
714
+ * absent = unknown (a row minted before occupants, a revival of a row that recorded none). */
715
715
  rootSessionIncarnation?: string;
716
716
  /** The run's delegation tree owner seat (`RunInternals.delegationOwner`, Runner-filled): a delegation tool reads the tree's owner
717
717
  * through it for the rows it creates for a child (a placed transcript, a fork, a park's durable row) and threads it into a spawned
@@ -295,6 +295,22 @@ export declare function compileLegWriteJudgment(entries: readonly WriteProtected
295
295
  * · `clear` ⇒ `undefined`: the surviving decision stands.
296
296
  */
297
297
  export declare function writeProtectionTightenDecision(toolName: string, verdict: WriteProtectionVerdict): PermissionResult | undefined;
298
+ /**
299
+ * The question a surviving ASK is said with when the table also meets its target: the standing ask — its action, provenance
300
+ * and disclosures — with {@link writeProtectionTightenDecision}'s own sentence after its message in parentheses (the form the
301
+ * persisted-rule tightening appends its account in), once; a standing ask without a message takes the sentence alone. One
302
+ * sentence is minted (beside the verdict); this only places it. A standing ask whose message IS the engine's own sentence
303
+ * (`engineSentenceOf`) keeps the account of it over the result: both halves are the engine's words, the literals the account
304
+ * lists are still quoted by the longer text, and this station composed the longer text — the account's only writer — so it
305
+ * restates the account for it (`generic` and `echoed` ride along, `text` is the result's message). Any other standing ask
306
+ * (a hook's, a deployment's) keeps its words and no account.
307
+ */
308
+ export declare function askWithTableSentence<T extends {
309
+ readonly message?: string;
310
+ }>(standing: T, tightenSentence: string, call: {
311
+ toolCallId: string;
312
+ toolName: string;
313
+ }): T;
298
314
  /**
299
315
  * @contract write_protection.verdict_is_the_mandate — a MATCHED row is the one fact of the judge's verdict a standing
300
316
  * allow rule may not retire (a live decider may still clear it), and `clear` is not it; this predicate is the one reading
@@ -7,6 +7,7 @@ import { chainHopsOrNone, symlinkChainHops } from "./path-identity.js";
7
7
  import { readDenyPatternRun } from "../tools/fs/read-deny.js";
8
8
  import { agentConfigDirSegments, agentConfigDirTail } from "./agent-config-dir.js";
9
9
  import { thrownText } from "./thrown-value.js";
10
+ import { attest, engineSentenceOf } from "./engine-attestation.js";
10
11
  import { fromSource, gateWaitFailureOf } from "./gate-bounded-await.js";
11
12
  const freezeTable = (rows) => Object.freeze(rows.map((r) => Object.freeze(r)));
12
13
  export const WRITE_PROTECTED_DEFAULT_TABLE = freezeTable([
@@ -463,6 +464,15 @@ export function writeProtectionTightenDecision(toolName, verdict) {
463
464
  decisionReason: "safety",
464
465
  };
465
466
  }
467
+ export function askWithTableSentence(standing, tightenSentence, call) {
468
+ if (standing.message === undefined)
469
+ return { ...standing, message: tightenSentence };
470
+ if (standing.message.includes(tightenSentence))
471
+ return standing;
472
+ const merged = { ...standing, message: `${standing.message} (${tightenSentence})` };
473
+ const account = engineSentenceOf(standing, call);
474
+ return account === undefined ? merged : attest(merged, call, { sentence: { ...account, text: merged.message } });
475
+ }
466
476
  export function writeProtectionMandated(verdict) {
467
477
  return verdict.kind === "hit";
468
478
  }