@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
package/dist/index.js CHANGED
@@ -75,7 +75,7 @@ export { createSessionRulePolicy } from "./core/runner/session-rule-policy.js";
75
75
  export { LOCKED_KEY_REGISTRY, resolveLockedKeys } from "./core/locked-config.js";
76
76
  export { BUILTIN_COMPLIANCE_DENIES, COMPLIANCE_CAPABILITIES, WEB_FETCH_TOOL_NAME, complianceCallDenial, resolveComplianceDenies, } from "./core/compliance.js";
77
77
  export { admitMemoryScopes, foldAdmissionFreeze, } from "./core/memory-admission.js";
78
- export { assertRetentionCapability, readRetentionDeclaration, RETENTION_CASCADE_DOMAINS, RETENTION_CASCADE_EXEMPT, } from "./core/retention.js";
78
+ export { assertRetentionCapability, readRetentionDeclaration, RETENTION_CASCADE, RETENTION_CASCADE_DOMAINS, RETENTION_CASCADE_EXEMPT, RETENTION_SESSION_TREE_STEPS, } from "./core/retention.js";
79
79
  export { GOVERNANCE_CODES, governanceRetryClass, TOOL_DECLARATION_CODES } from "./core/governance-codes.js";
80
80
  export { NOTICE_AUDIENCE, noticeAudienceOf, ENGINE_NOTICE_CODES, NOTICE_MINTER } from "./core/governance-codes.js";
81
81
  export { TtlSessionStore } from "./core/session-store.js";
@@ -98,7 +98,7 @@ export { confineShellStart } from "./core/shell-confinement.js";
98
98
  export { RemoteExecutionError, hasDestroy, isRemoteExecutionEnv, isSuspendable, isIsolated, canonicalPathIsAuthoritative, pathsAreHostLocal, keepsReadFloor, missingRestoreSurface, isRetryableRemoteErrorCode, RETRYABLE_REMOTE_ERROR_CODES, } from "./core/remote-env.js";
99
99
  export { withRetry } from "./core/with-retry.js";
100
100
  export { addWorktree, pruneWorktrees, WORKTREE_PARENT } from "./core/git-worktree-env.js";
101
- export { probeWorktreeCapability, releaseSessionCheckout, WORKTREE_INCAPABLE_REASONS, } from "./core/session-checkout.js";
101
+ export { listOrphanSessionTrees, probeWorktreeCapability, releaseOrphanSessionTree, releaseSessionCheckout, WORKTREE_INCAPABLE_REASONS, } from "./core/session-checkout.js";
102
102
  export { runExecGate } from "./core/exec-gate.js";
103
103
  export { sanitizeUntrustedText, delimitUntrusted, inlineUntrusted, isMintableProbeReason } from "./core/untrusted-text.js";
104
104
  export { mintReminderMark, isValidReminderMark, openSystemReminder, mintSystemReminder, reminderMarkDeclaration } from "./core/reminder-mint.js";
@@ -188,12 +188,13 @@ export { PERMISSION_MODES, isPermissionMode, PERMISSION_MODE_RANK, clampPermissi
188
188
  export { CROSS_BOUNDARY_TAINT_BITS, CROSS_BOUNDARY_POSTURES, BOUNDARY_LEGS, crossBoundaryObligation, CROSS_BOUNDARY_RECORD_TYPE, readCrossBoundaryRecord } from "./core/cross-boundary-taint.js";
189
189
  export { modePolicyOf, PERMISSION_MODE_FOLD_REASONS, ACCEPT_EDITS_FILE_COMMANDS, modeAcceptsFileCommand } from "./core/mode-policy.js";
190
190
  export { SKILL_GRANT_ORIGINS } from "./core/skill-grant.js";
191
- export { ALLOW_ENTRY_INERT_REASONS, readRuleEntry, compileAllowList, renderListEntry } from "./core/allow-entry.js";
191
+ export { ALLOW_ENTRY_INERT_REASONS, readRuleEntry, compileAllowList, renderListEntry, screenAllowedToolsValue } from "./core/allow-entry.js";
192
192
  export { ALLOW_RULE_MEMBERS } from "./core/allow-rule-shadow.js";
193
193
  export { mintNamespacePrefix } from "./core/protocol-naming.js";
194
194
  export { readDenyClassifierRules, renderClassifierDenyRules } from "./core/auto-mode-prompt.js";
195
195
  export { AUTO_MODE_DENY_SOURCES, isAutoModeDenySource } from "./core/runtime-caps.js";
196
196
  export { SETTLEMENT_KINDS, isSettlementKind, SETTLEMENT_PARTIES, isSettlementParty, HOST_DECIDERS, isHostDecider, DECIDED_VIA, SETTLEMENT_IS_REFUSAL, DENIED_BY_VALUES, isDeniedBy, DENIED_BY_MAY_VETO, CLASSIFIER_DENY_CAUSES, isClassifierDenyCause, DENIED_BY_MAY_CARRY_CAUSE, screenGateOutcome, RETIRED_MEMBERS, isRetiredMember } from "./core/gate-outcome.js";
197
+ export { REFUSAL_ECHO_KINDS, isRefusalEchoKind } from "./core/refusal-echo.js";
197
198
  export { ENGINE_BUILTIN_TOOL_NAMES, isEngineBuiltinToolName } from "./core/tool-catalog-entries.js";
198
199
  export { policyCannotAnswer } from "./core/real-approval.js";
199
200
  export {} from "./core/hooks.js";
@@ -208,7 +209,7 @@ export { AUTO_MODE_ARMING_RECIPE_VERSION, autoModeArmingRecipeOf, sanitizeAutoMo
208
209
  export { rebuildAutoModeDecider, } from "./core/auto-mode-rebuild.js";
209
210
  export { createPermissionRulePolicy, validatePermissionRules, parsePermissionRule, wildcardMatch, isCoveringRuleName, ruleNameCovers, } from "./core/permission-rules.js";
210
211
  export { RULE_BEHAVIORS, RULE_BEHAVIOR_PRECEDENCE, RULE_BEHAVIORS_BY_PRECEDENCE, isRuleBehavior, readRowBehavior, adjudicatePersistedRules, adjudicatePersistedPathRules, adjudicatePersistedToolRules, ruleReachesProgramRun, programRunReachOf, PROGRAM_RUN_REACHES, pathRuleReachOf, ruleBasesNeeded, PATH_RULE_BASES, PATH_RULE_BASE_LABEL, ruleToolGrammarOf, COMMAND_RULE_TOOL, READ_RULE_TOOL, parseRuleText, formatRuleText, ruleAdmitsCommand, findAdmittingRule, suggestRulesForCommand, scopeCoversCwd, pathWithinRoot, isRuleLive, renderUntrustedCommandText, stripFormatCharacters, UNCOVERED_SEGMENT_REASON_BASELINE, RULE_OFFERS_ABSENCE_BASELINE, PERSISTED_RULE_MATCHES, RULE_OFFER_KINDS, RULE_OFFER_BATCH_MEMBER_KINDS, UNCOVERED_SEGMENT_REASONS, EDITED_RULE_BREADTH_WARNING_CODES, RULE_ADD_ORIGINS, directoryRuleAdmits, BARE_INTERPRETER_NAMES, MAX_RULE_TEXT_CHARS, } from "./core/permission-rule-model.js";
211
- export { removePersistedRule, addPersistedRule, applyTombstones, sameScope, sameRuleIdentity, isValidConsentScope, isValidDurableScope, InMemoryDurableRulePartition, EMPTY_DURABLE_RULE_PARTITION, joinRuleStates, applySyncJoin, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, PERMISSION_RULES_LATER_GRAMMAR_CODE, } from "./core/permission-rule-store.js";
212
+ export { removePersistedRule, addPersistedRule, applyTombstones, sameScope, sameRuleIdentity, isValidConsentScope, isValidDurableScope, InMemoryDurableRulePartition, EMPTY_DURABLE_RULE_PARTITION, joinRuleStates, applySyncJoin, screenRuleSyncState, collectBelowFrontier, ruleSyncVector, joinFrontiers, dotAtOrBelowFrontier, PERMISSION_RULE_WRITER, writerOf, foldDelta, addDotsOf, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, PERMISSION_RULES_LATER_GRAMMAR_CODE, PERMISSION_RULES_DAMAGED_BUCKET_CODE, PERMISSION_RULES_UNREADABLE_BUCKET_CODE, } from "./core/permission-rule-store.js";
212
213
  export { readRuleOwner, sameRuleOwner, RULE_OWNER_KINDS, } from "./core/rule-owner.js";
213
214
  export { principalNameOf } from "./core/principal-name.js";
214
215
  export { syncPermissionRules, parseRuleSyncResponse, PERMISSION_RULE_SYNC_PATH, LOCAL_OWNER_UNSYNCABLE_CODE, } from "./core/permission-rule-sync.js";
@@ -233,7 +234,7 @@ export { SESSION_SEND_ORIGIN_KINDS } from "./core/mods/session-send.js";
233
234
  export { loadModPackage } from "./core/mods/package.js";
234
235
  export { CREDENTIAL_REF_KINDS, CREDENTIAL_REF_TRUST, CREDENTIAL_REF_TEXT_MAX, CREDENTIAL_REF_MAP_MAX, CREDENTIAL_REF_PROBLEM_REASONS, readCredentialRef, } from "@sema-agent/primitives";
235
236
  export { InMemoryMemoryStore, composeMemoryBlock, composeLayeredMemoryBlock, normalizeMemorySpec, supportsConsolidation, supportsPeriodicConsolidation, firstSentence, expandLexicalTerms, lexicalSearchMatch, classifyPromotable, enforcePromotableWriteGate, guardedMemoryStore, MemoryGateError, MemoryProjectionError, detectSecret, enforceSecretWriteGate, enforceStructuredNoteSecretGate, MEMORY_PROJECT_KEY_ABSENT_REASONS, } from "./core/memory.js";
236
- export { MemoryEngine, FileMemoryEngineBackend, readMemoryLedgerForm, memoryBackendContract, assertMemoryBackendSearchEquivalence, memoryGovernanceStoreContract, buildMemoryInstruction, writableRootOf, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, consolidationExposedFrontmatter, ambiguousOriginRepresentation, committedDistilledOf, distilledEquals, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, supersessionFuseCeiling, DELETION_FUSE_FLOOR, fileGovernanceStore, memoryGovernanceDurability, deriveShadowedSet, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, memoryConsolidationWithheldNotice, DISTILLER_DEFAULT_MAX_INPUTS_PER_PRODUCT, LLM_DISTILLER_CONTRACT, LLM_DISTILLER_CONTRACT_DL2, LLM_DISTILLER_CONTRACT_DL3, LLM_DISTILLER_CONTRACTS, MEMORY_DISTILLER_CONTRACT_V1, contractGroupingDiff, driveConsolidationToFixpoint, isAliasModelId, llmPlanDistiller, mintExposurePartitionedPlan, mintLlmConsolidationPlan, MEMORY_DISTILLER_PURITY_CONTRACT_V1, detectCleanArmVerbatimLeak, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, CONSOLIDATION_RUN_STOP_REASONS, CONSOLIDATION_WRITE_REFUSED_CODE, runMemoryConsolidationDriver, isInstructionEntry, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, MEMORY_CAPTURE_OPTOUT_NOTICE, memoryCaptureOptedOutNotice, memoryCaptureOptOutUnpersistedNotice, SESSION_CAPTURE_OPTOUT_DIR, markSessionCaptureOptOut, readSessionCaptureOptOut, listSessionCaptureOptOut, fileSessionCaptureRecordStore, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_INDEX_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, erasureSelectHash, computeMemoryBundleHash, MEMORY_GOVERNANCE_DOC_NAMES, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, memorySyncStoreOf, carriesCredential, memorySyncReportOf, memoryTravelGapOf, } from "./core/memory-engine/index.js";
237
+ export { MemoryEngine, FileMemoryEngineBackend, readMemoryLedgerForm, memoryBackendContract, assertMemoryBackendSearchEquivalence, memoryGovernanceStoreContract, buildMemoryInstruction, writableRootOf, truncateIndex, scanEntryFiles, deriveRepoKey, deriveRepoMemoryDir, deriveControlPlaneDir, deriveRepoControlPlaneDir, resolveMemoryEngineRoot, scopeDirName, ControlPlaneCorruptError, parseEntryFile, serializeEntryFile, computeEntryRev, entryFromFile, MEMORY_ORIGIN_CAUSES, committedOriginOf, originEquals, consolidationExposedFrontmatter, ambiguousOriginRepresentation, committedDistilledOf, distilledEquals, CONSOLIDATION_DEFAULTS, ConsolidationRefusedError, MEMORY_SEARCH_SUPERSEDED_TAG, consolidationTypeEligible, deriveSupersededSet, memorySupersededNote, supersessionFuseCeiling, DELETION_FUSE_FLOOR, fileGovernanceStore, memoryGovernanceDurability, deriveShadowedSet, memoryConsolidationRecommendedNotice, memoryConsolidationCommittedNotice, memoryConsolidationConflictNotice, memoryConsolidationIncompleteNotice, memoryConsolidationRefusedNotice, memoryConsolidationWithheldNotice, DISTILLER_DEFAULT_MAX_INPUTS_PER_PRODUCT, LLM_DISTILLER_CONTRACT, LLM_DISTILLER_CONTRACT_DL2, LLM_DISTILLER_CONTRACT_DL3, LLM_DISTILLER_CONTRACTS, MEMORY_DISTILLER_CONTRACT_V1, contractGroupingDiff, driveConsolidationToFixpoint, isAliasModelId, llmPlanDistiller, mintExposurePartitionedPlan, mintLlmConsolidationPlan, MEMORY_DISTILLER_PURITY_CONTRACT_V1, detectCleanArmVerbatimLeak, openAiCompatChatSeat, parseJsonAnswer, planParseRepairs, sanitizeLlmGroups, scheduleUnderFuse, CONSOLIDATION_RUN_STOP_REASONS, CONSOLIDATION_WRITE_REFUSED_CODE, runMemoryConsolidationDriver, isInstructionEntry, MEMORY_INSTRUCTION_TEMPLATE, MEMORY_RECALL_DISCIPLINE, MEMORY_PREFERENCE_DISCIPLINE, MEMORY_READONLY_NOTICE, MEMORY_CAPTURE_OPTOUT_NOTICE, memoryCaptureOptedOutNotice, memoryCaptureOptOutUnpersistedNotice, SESSION_CAPTURE_OPTOUT_DIR, markSessionCaptureOptOut, readSessionCaptureOptOut, listSessionCaptureOptOut, fileSessionCaptureRecordStore, readV2HeaderHints, LINEAGE_FILE, CHALLENGES_FILE, CHALLENGED_HISTORY_FILE, CHALLENGE_LEDGER_MAX_EVENTS, rebuildStrictControlPlaneLedger, MEMORY_INDEX_FILENAME, MEMORY_INDEX_MAX_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_SEARCH_TOOL_NAME, MEMORY_GET_TOOL_NAME, MEMORY_INDEX_TOOL_NAME, MEMORY_ENGINE_TOOL_NAMES, MEMORY_EXPOSURE_BANNER, MEMORY_EXPOSURE_HANDLE_TAG, memoryExposureIndexRow, STUB_ARCHIVED_LINE, DEFAULT_MAX_MEMORY_FILES, DEFAULT_MAX_ENTRY_DEPTH, DEFAULT_HARVEST_DEADLINE_MS, DEFAULT_HARVEST_FILE_BUDGET, MASS_DELETION_FUSE_RATIO, scanMemoryWrite, scanMemoryFileName, scanRemediation, MEMORY_FILENAME_SEGMENT_RE, renderAnnouncements, enqueueMemoryAnnouncement, drainMemoryAnnouncements, peekMemoryAnnouncements, bumpScanFuse, scanFuseCount, clearScanFuse, ANNOUNCEMENTS_FILE, MEMORY_ANNOUNCEMENTS_MAX, SCAN_FUSE_FILE, SCAN_FUSE_THRESHOLD, erasureSelectHash, computeMemoryBundleHash, MEMORY_GOVERNANCE_DOC_NAMES, MEMORY_CONTROL_OBJECT_KINDS, adoptReplicaControlPlane, replicaControlPlaneStrays, SCOPE_SEGMENT_MAX_ENCODED, PROJECT_MARKER_PATH, encodeScopeSegment, decodeScopeSegment, parseScopeKey, formatUserScope, formatUserLocalScope, formatOrgScope, formatProjScope, formatUserProjScope, isPersonalScope, isReplicableScope, isOrgScopeKey, assertScopeContractPlacement, formatProjectMarker, parseProjectMarker, resolveProjectId, PROJECT_ID_REGEX, migrateScope, materializeEntriesToFiles, harvestFilesToPatches, projectionsToWriteBack, screenInboundEntries, REMOTE_HARVEST_PER_FILE_BYTES, REMOTE_MASS_DELETION_FUSE_RATIO, deriveProjectMemoryDir, deriveProjectControlDir, recordProjectIdHint, lookupProjectIdHint, PROJECT_ID_HINTS_FILE, reconcileMemoryEntries, nextSyncBaseline, mergeRecallHits, syncMemoryScope, memorySyncStoreOf, carriesCredential, memorySyncReportOf, memoryTravelGapOf, } from "./core/memory-engine/index.js";
237
238
  export { createConsolidationWriteJudge, deliverWriteRefusal } from "./core/runner/memory-consolidation-write-judge.js";
238
239
  export { STORE_FORM_REFUSAL_CODES, TARGET_OUTSIDE_STORE, SCOPE_HOME_NOT_DIRECTORY, SCOPE_HOME_FORMS } from "./core/memory-engine/layout.js";
239
240
  export { resolveMemoryScopeStore } from "./core/memory-engine/dual-root.js";
@@ -248,6 +249,7 @@ export { sharedMemoryStoreContract, } from "./core/shared-memory/contract.js";
248
249
  export { termSet, jaccardDistance, cosineDistance } from "./core/memory-vector.js";
249
250
  export { encodeSurfacedKey, buildManifestText, validateSelectedIds, composeSelectiveBody, formatMemoryAge, resolveLinkedIds, RECALL_CAVEAT, DEFAULT_MAX_SELECTED, DEFAULT_MAX_LINKED, } from "./core/memory-recall.js";
250
251
  export { resolveMemoryConsolidationDriver, autoRunOnRecommendationEffective, } from "./core/runner/memory-consolidation-driver.js";
252
+ export { ROLE_RESOLUTION_TABLE, modelFaceResolvable, } from "./core/runner/role-resolution-table.js";
251
253
  export { teardownLegBudget } from "./core/runner/teardown-bounded.js";
252
254
  export { DEFAULT_COMPACTION_INSTRUCTIONS } from "./core/auto-compaction.js";
253
255
  export { DEFAULT_SYSTEM_PROMPT, CODE_AGENT_PROMPT, SUBAGENT_PROMPT, MEMORY_SAFETY, MEMORY_HYGIENE, OUTPUT_EFFICIENCY, CYBER_RISK, HARNESS_SECTION_ANCHOR, URL_SAFETY, SUMMARIZE_TOOL_RESULTS, EXECUTION_ENVIRONMENT, EXECUTION_ENVIRONMENT_OPEN_READS, executionEnvironmentBlockFor, buildEnvironmentContext, buildGitSnapshot, buildScratchpadSection, GIT_STATUS_MAX_CHARS, formatLocalDate, } from "./prompts/default.js";
@@ -175,6 +175,10 @@ export interface RunWorkflowToolDeps {
175
175
  * root MUST ride deps; `ctx.rootSessionId` stays first for a deployment-composed mount that
176
176
  * does get the enriched ctx. */
177
177
  rootSessionId?: string;
178
+ /** The occupant (`SessionMetadata.incarnation`) of {@link rootSessionId}'s row as this host tree holds it — read at call
179
+ * time (the host leg learns its own occupant after the mount is wired). Rides beside the root anchor for the same
180
+ * auto-mounted-ctx reason; a workflow-spawned agent addresses an escalated terminal frame to (root, occupant). */
181
+ rootSessionIncarnation?: () => string | undefined;
178
182
  /** design/380 O1② (C12) — the host run's EXPLICIT placement fixed point
179
183
  * (`RunInternals.placementRoot`), riding deps for the same auto-mounted-ctx reason as
180
184
  * `rootSessionId` above; threaded into the workflow run so every workflow-spawned agent keeps
@@ -60,6 +60,12 @@ function completionSummary(name, run) {
60
60
  return (`workflow${cleanName ? ` "${cleanName}"` : ""} completed${elapsed} — agents ${done}/${run.agents.length} done` +
61
61
  `${failed > 0 ? ` (${failed} failed)` : ""}${resumeClause}`);
62
62
  }
63
+ function rootOccupantSeat(rootId, ctx, d) {
64
+ if (rootId === undefined)
65
+ return {};
66
+ const occupant = (rootId === (ctx.rootSessionId ?? ctx.sessionId) ? ctx.rootSessionIncarnation : undefined) ?? (rootId === d.rootSessionId ? d.rootSessionIncarnation?.() : undefined);
67
+ return occupant !== undefined ? { rootSessionIncarnation: occupant } : {};
68
+ }
63
69
  const WORKFLOW_NOTIFY_ROWS_MAX = 5;
64
70
  function workflowRecordTeach(run, artifact) {
65
71
  const notDone = run.agents.filter((a) => a.status !== "completed");
@@ -516,6 +522,7 @@ async function mountRunWorkflowTool(d) {
516
522
  ...(sourceTaskId !== undefined ? { sourceTaskId } : {}),
517
523
  ...(d.originatingSessionId !== undefined ? { originatingSessionId: d.originatingSessionId } : {}),
518
524
  ...((ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId) !== undefined ? { rootSessionId: ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId } : {}),
525
+ ...rootOccupantSeat(ctx.rootSessionId ?? d.rootSessionId ?? d.originatingSessionId, ctx, d),
519
526
  ...((ctx.placementRoot ?? d.placementRoot) !== undefined ? { placementRoot: ctx.placementRoot ?? d.placementRoot } : {}),
520
527
  ...((ctx.placementTarget ?? d.placementTarget) !== undefined ? { placementTarget: ctx.placementTarget ?? d.placementTarget } : {}),
521
528
  ...((ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree) !== undefined ? { crossBoundaryTree: ctx.crossBoundaryTreeForChildren ?? d.crossBoundaryTree } : {}),
@@ -5,7 +5,8 @@ export type WorkflowRunStatus = "running" | "completed" | "failed";
5
5
  * {@link WorkflowAgentRun.parkedCheckpointToken}); a phase or group never parks (a parked agent ends the run). */
6
6
  export type WorkflowItemStatus = "running" | "completed" | "failed" | "parked";
7
7
  /** The arm a `workflow.park_truth_unreadable` resume refusal fired on (`detail.reason`): the prior run's record could not
8
- * be read (`store_threw`), is absent under this scope (`record_missing`), is not terminal (`record_not_terminal`),
8
+ * be read (`store_threw`), is absent under this scope (`record_missing` — never recorded under it, reaped, or deleted with
9
+ * the session that started it: one word, because after a deletion the three are the same absence), is not terminal (`record_not_terminal`),
9
10
  * carries no `parks` array and nothing to derive one from — an empty journal, or an empty derived union
10
11
  * (`parks_unreadable`) — or says its OWN resume admission never completed
11
12
  * ({@link WorkflowRun.resumeAdmissionIncomplete} — nothing on it describes a settled park set, so it is not a
@@ -342,6 +342,9 @@ export interface RunWorkflowOptions {
342
342
  * `ctx.rootSessionId ?? originatingSessionId`); rides the wa* observer frames so a recovery face
343
343
  * groups workflow-agent rows under the root host session too. */
344
344
  rootSessionId?: string;
345
+ /** The occupant (`SessionMetadata.incarnation`) of {@link rootSessionId}'s row as the host tree holds it; rides the
346
+ * shared internals base beside the root anchor (`RunInternals.rootSessionIncarnation`). Absent = unknown. */
347
+ rootSessionIncarnation?: string;
345
348
  /** design/380 O1② (C12) — the host run's EXPLICIT placement fixed point
346
349
  * (`RunInternals.placementRoot`, threaded by the run-workflow tool when the host carried one):
347
350
  * every workflow-spawned agent inherits it verbatim so descendants of a cascade/verify leg stay
@@ -740,6 +740,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
740
740
  ...(opts.inheritedGate !== undefined ? { inheritedGate: opts.inheritedGate } : {}),
741
741
  ...(agentCeiling !== undefined ? { toolCeiling: agentCeiling } : {}),
742
742
  ...((opts.rootSessionId ?? opts.originatingSessionId) !== undefined ? { rootSessionId: opts.rootSessionId ?? opts.originatingSessionId } : {}),
743
+ ...(opts.rootSessionId !== undefined && opts.rootSessionIncarnation !== undefined ? { rootSessionIncarnation: opts.rootSessionIncarnation } : {}),
743
744
  ...(opts.placementRoot !== undefined ? { placementRoot: opts.placementRoot } : {}),
744
745
  ...(opts.placementTarget !== undefined ? { placementTarget: opts.placementTarget } : {}),
745
746
  ...(opts.crossBoundaryTree !== undefined ? { crossBoundaryTree: opts.crossBoundaryTree } : {}),
@@ -2612,7 +2613,7 @@ export function startWorkflow(runner, fn, opts = {}, internals) {
2612
2613
  prior = null;
2613
2614
  }
2614
2615
  if (opts.store !== undefined && prior === null)
2615
- throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope, so its parks cannot be proven.`, { reason: "record_missing" });
2616
+ throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run's record is not in the run store under this scope (never recorded under it, reaped, or deleted with the session that started it), so its parks cannot be proven.`, { reason: "record_missing" });
2616
2617
  if (parkSeat !== undefined && prior !== null && prior.status === "running")
2617
2618
  throw new WorkflowParkRefusal("workflow.park_truth_unreadable", `startWorkflow: resume from "${fromRunId}" was REFUSED — the prior run is still recorded as running; a run that could park must have finished before it is resumed (a crashed park-capable run is decided through the deployment's approval channel, not resumed).`, { reason: "record_not_terminal" });
2618
2619
  if (prior?.resumeAdmissionIncomplete === true)
@@ -1,3 +1,4 @@
1
+ import { type RetentionDeclaration } from "../../core/retention.js";
1
2
  import { type ExecutionOutcomeRecordWord } from "../../core/checkpoint-execution-record.js";
2
3
  import { type HolderJudge } from "../../core/checkpoint-generation.js";
3
4
  import { type Checkpoint, type PendingSteerEntry, type PendingSteerInput, type CheckpointFaultMode, type CheckpointStore, type CheckpointSummary, type CheckpointToken, type ReopenReason, type ResolveExpectation, type ResumeOutcome } from "../../core/checkpoint-store.js";
@@ -102,6 +103,9 @@ export interface FileCheckpointStoreOptions {
102
103
  } | undefined>;
103
104
  /** The judge of a resolve's claim holder ({@link HolderJudge}); with it the store declares `fence = { holder: true }`. */
104
105
  holderIsCurrent?: HolderJudge;
106
+ /** The store's managed-retention declaration ({@link import("../../core/checkpoint-store.js").CheckpointStore.retention}), stated by
107
+ * the party that runs the sweep; default `"none"`, a third word refused (`config.retention_capability`). */
108
+ retention?: RetentionDeclaration;
105
109
  }
106
110
  /**
107
111
  * Every event kind this reader understands — the ledger's CLOSED SET, exported so a program that reads a `checkpoints.jsonl` itself judges
@@ -153,6 +157,8 @@ export declare class FileCheckpointStore implements CheckpointStore {
153
157
  * directory's writer fence and refuses a second OS process by name (see the class header). Serving
154
158
  * many writers at once remains Pg/TiDB's job — this refuses the second one, it does not coordinate it. */
155
159
  readonly durability: "durable";
160
+ /** {@link FileCheckpointStoreOptions.retention}, as read at construction. */
161
+ readonly retention: RetentionDeclaration;
156
162
  /** Honest declaration on the fidelity axis: the ledger is JSONL, so what this backend holds is the JSON
157
163
  * PROJECTION of the row — a `Date` reads as its ISO string, a `Map`/`Set` as `{}`, `NaN` as `null`, an
158
164
  * `undefined`-valued key not at all — before a restart and after it alike (the live map is filled from the
@@ -2,13 +2,14 @@ import { join } from "node:path";
2
2
  import { assertAdoptionBootGate } from "./adoption/marker.js";
3
3
  import { memberPresent, optionKeys, receiveOptions } from "../../core/own-property-receipt.js";
4
4
  import { readLedgerTuning } from "./ledger-tuning.js";
5
+ import { readRetentionDeclaration } from "../../core/retention.js";
5
6
  import { checkpointExecutionRecorded, executionRecordDisposition, ExecutionOutcomeConflictError, } from "../../core/checkpoint-execution-record.js";
6
7
  import { checkpointHolderMatches, checkpointOccMatches, checkpointRevOf } from "../../core/checkpoint-generation.js";
7
8
  import { appendPendingSteer, CheckpointError, checkpointRowMatches, encodeAtFidelity, summarizeStoredCheckpoint, validatePendingSteer, winnerFromOutcome, } from "../../core/checkpoint-store.js";
8
9
  import { checkpointDeadlinePassed, deleteSessionRowsAtStart, readCheckpointOverdueQuery, readCheckpointSessionQuery, selectOverduePage, selectSessionPage, } from "../../core/checkpoint-queries.js";
9
10
  import { readLedgerSettled, SharedLedgerTable } from "./shared-ledger.js";
10
11
  import { guardCorruptSink } from "./corrupt-read-sink.js";
11
- const FILE_CHECKPOINT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, fsync: 0, compactEvery: 0, sessionHeadOf: 0, holderIsCurrent: 0 });
12
+ const FILE_CHECKPOINT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, fsync: 0, compactEvery: 0, sessionHeadOf: 0, holderIsCurrent: 0, retention: 0 });
12
13
  export const CHECKPOINT_LEDGER_EVENT_KINDS = Object.freeze(["put", "resolve", "reopen", "execution", "expire", "delete", "steer_append"]);
13
14
  const KNOWN_CHECKPOINT_LEDGER_EVENTS = new Set(CHECKPOINT_LEDGER_EVENT_KINDS);
14
15
  function applyCheckpointEvent(cps, ev) {
@@ -93,6 +94,7 @@ export function readCheckpointLedger(root, opts = {}) {
93
94
  }
94
95
  export class FileCheckpointStore {
95
96
  durability = "durable";
97
+ retention;
96
98
  fidelity = "json";
97
99
  execution = { outcome: true };
98
100
  holderIsCurrent;
@@ -109,6 +111,7 @@ export class FileCheckpointStore {
109
111
  ledgerPath;
110
112
  constructor(root, options) {
111
113
  const opts = receiveOptions(options, "FileCheckpointStore", FILE_CHECKPOINT_STORE_OPTION_KEYS);
114
+ this.retention = readRetentionDeclaration("FileCheckpointStore.retention", opts.retention);
112
115
  assertAdoptionBootGate(root, "FileCheckpointStore");
113
116
  const tuning = readLedgerTuning(opts, "FileCheckpointStore", "FileCheckpointStore options");
114
117
  this.fsyncEnabled = tuning.fsync;
@@ -118,6 +118,10 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
118
118
  * and a capture by an entry id, and one map holding both would be a key space where two unrelated
119
119
  * vocabularies have to promise never to spell the same string. */
120
120
  private readonly activeImports;
121
+ /** scope → how many of the verbs that write its history (`trackEdit`, `annulTrack`, `snapshot`, `importHistory`) are running in
122
+ * this store, counted from the call to its settle — before any await, so a write parked at its first read is counted. The two
123
+ * maps above answer which journals lease blobs; this answers whether `deleteBySession` may erase the scope now. */
124
+ private readonly writers;
121
125
  /**
122
126
  * The CONSUMED-ID ledger's in-process view — a CACHE over `scopes/<scope>/reaped.log`, not the
123
127
  * record itself (design/381 slice 3, closing the residual slice 2 registered here by name).
@@ -308,11 +312,15 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
308
312
  private boundaryOrderOf;
309
313
  /** Publish a blob write-ONCE (EEXIST = the identical bytes are already stored — dedup no-op). */
310
314
  private putBlob;
315
+ /** Run one history write of `scope` counted in {@link writers}. */
316
+ private writing;
311
317
  trackEdit(scope: string, absPath: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryTrackResult>;
318
+ private trackEditCounted;
312
319
  annulTrack(scope: string, absPath: string, root: string, verify?: {
313
320
  env: ExecutionEnv;
314
321
  signal?: AbortSignal;
315
322
  }): Promise<FileHistoryResult>;
323
+ private annulTrackCounted;
316
324
  /**
317
325
  * Is this scope free of history RIGHT NOW? Synchronous on purpose (adversarial round 1): the
318
326
  * empty-target law is only sound if the observation and the publish happen with no await between
@@ -342,10 +350,12 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
342
350
  * unreadable ≠ empty (a file gone since the listing cannot be judged either). ENOENT is no boundary yet. */
343
351
  private listBoundaryIds;
344
352
  snapshot(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryResult>;
353
+ private snapshotCounted;
345
354
  restore(scope: string, entryId: string, env: ExecutionEnv, root: string, signal?: AbortSignal): Promise<FileHistoryRestoreResult>;
346
355
  canRestore(scope: string, entryId: string): Promise<boolean>;
347
356
  diffStats(scope: string, entryId: string, env: ExecutionEnv, root: string): Promise<FileHistoryDiffStats | null>;
348
357
  reap(scope: string, keepEntryIds: string[]): Promise<number>;
358
+ deleteBySession(scope: string): Promise<number>;
349
359
  /**
350
360
  * Blob GC across EVERY scope — FAIL-SAFE by construction: build the COMPLETE live set or keep
351
361
  * every blob. An incomplete live set (a swallowed scan error) would delete still-live bytes, so
@@ -354,11 +364,14 @@ export declare class FileFileHistoryStore implements FileHistoryStore {
354
364
  * await; the live set additionally unions the staging journals of THIS process's in-flight
355
365
  * attempts (bytes published but not yet chained), while every OTHER journal is dead-attempt
356
366
  * residue: it is removed here, and the blobs it was protecting become collectable in this pass.
367
+ * Answers why it did not collect every unreferenced blob (undefined = it did): `reap` has no error
368
+ * channel and discards it; `deleteBySession` throws it.
357
369
  */
358
370
  private collectBlobs;
359
371
  adoptScope(fromScope: string, toScope: string): Promise<FileHistoryResult>;
360
372
  exportHistory(scope: string): Promise<FileHistoryExportResult>;
361
373
  importHistory(scope: string, data: FileHistoryExport, srcGetBlob: (hash: string) => Promise<Uint8Array | undefined>): Promise<FileHistoryResult>;
374
+ private importHistoryCounted;
362
375
  /** The import's body, so EVERY exit (typed refusal, thrown fault, success) passes one `finally`
363
376
  * that releases the journal + lease — an early return used to leak both, and a leaked lease is
364
377
  * permanent liveness for blobs nothing references (adversarial round 2). */
@@ -134,6 +134,7 @@ export class FileFileHistoryStore {
134
134
  spentAttempts = new Map();
135
135
  activeCaptures = new Map();
136
136
  activeImports = new Map();
137
+ writers = new Map();
137
138
  reapedCache = new Map();
138
139
  boundaryKeep;
139
140
  lastCommittedAt = 0;
@@ -405,7 +406,23 @@ export class FileFileHistoryStore {
405
406
  throw err;
406
407
  }
407
408
  }
408
- async trackEdit(scope, absPath, env, root, signal) {
409
+ async writing(scope, write) {
410
+ this.writers.set(scope, (this.writers.get(scope) ?? 0) + 1);
411
+ try {
412
+ return await write();
413
+ }
414
+ finally {
415
+ const left = (this.writers.get(scope) ?? 1) - 1;
416
+ if (left === 0)
417
+ this.writers.delete(scope);
418
+ else
419
+ this.writers.set(scope, left);
420
+ }
421
+ }
422
+ trackEdit(scope, absPath, env, root, signal) {
423
+ return this.writing(scope, () => this.trackEditCounted(scope, absPath, env, root, signal));
424
+ }
425
+ async trackEditCounted(scope, absPath, env, root, signal) {
409
426
  try {
410
427
  const { key, kind, family } = describeTrackKey(root, absPath);
411
428
  const before = this.readTrackedState(scope);
@@ -456,7 +473,10 @@ export class FileFileHistoryStore {
456
473
  return { ok: false, error: { code: "track_failed", message: `first-touch record for ${absPath} could not be persisted: ${thrownText(err)}`, ...caughtFault(err) } };
457
474
  }
458
475
  }
459
- async annulTrack(scope, absPath, root, verify) {
476
+ annulTrack(scope, absPath, root, verify) {
477
+ return this.writing(scope, () => this.annulTrackCounted(scope, absPath, root, verify));
478
+ }
479
+ async annulTrackCounted(scope, absPath, root, verify) {
460
480
  try {
461
481
  const key = trackKeyOf(root, absPath);
462
482
  const state = this.readTrackedState(scope);
@@ -573,7 +593,10 @@ export class FileFileHistoryStore {
573
593
  return ids;
574
594
  return { fault: worstFault(faults), what: `boundaries that cannot be used (${unusable.slice(0, 3).map((i) => JSON.stringify(i)).join(", ")}${unusable.length > 3 ? ", …" : ""})` };
575
595
  }
576
- async snapshot(scope, entryId, env, root, signal) {
596
+ snapshot(scope, entryId, env, root, signal) {
597
+ return this.writing(scope, () => this.snapshotCounted(scope, entryId, env, root, signal));
598
+ }
599
+ async snapshotCounted(scope, entryId, env, root, signal) {
577
600
  const bpath = this.tryBoundaryPath(scope, entryId);
578
601
  if (bpath === null)
579
602
  return { ok: false, error: { code: "snapshot_failed", message: `unsafe boundary key ${JSON.stringify(entryId)}` } };
@@ -913,6 +936,40 @@ export class FileFileHistoryStore {
913
936
  this.collectBlobs();
914
937
  return removed;
915
938
  }
939
+ async deleteBySession(scope) {
940
+ if (this.writers.has(scope)) {
941
+ throw Object.assign(new Error(`file history scope "${scope}" has a write in flight in this store (a capture, a first-touch record, a retraction or an import) — a session's history is erased when no leg of it runs`), { code: "conflict" });
942
+ }
943
+ const sdir = this.scopeDir(scope);
944
+ const ledger = this.reapedLogPath(scope);
945
+ let removed = 0;
946
+ if (existsSync(sdir)) {
947
+ try {
948
+ removed += readdirSync(this.boundaryDir(scope)).filter((f) => f.endsWith(".json")).length;
949
+ }
950
+ catch (err) {
951
+ if (err.code !== "ENOENT")
952
+ removed += 1;
953
+ }
954
+ const read = this.readTrackedState(scope);
955
+ if (read.corrupt)
956
+ removed += 1;
957
+ else
958
+ for (const rec of read.tracked.values())
959
+ removed += rec.versions.length;
960
+ rmSync(sdir, { recursive: true, force: true });
961
+ }
962
+ rmSync(ledger, { force: true });
963
+ this.reapedCache.delete(scope);
964
+ this.spentAttempts.delete(scope);
965
+ this.seededScopes.delete(scope);
966
+ this.activeCaptures.delete(scope);
967
+ this.activeImports.delete(scope);
968
+ const kept = this.collectBlobs();
969
+ if (kept !== undefined)
970
+ throw new Error(`file history scope "${scope}" is erased but its blobs are not: ${kept}`);
971
+ return removed;
972
+ }
916
973
  collectBlobs() {
917
974
  const live = new Set();
918
975
  let complete = true;
@@ -922,9 +979,9 @@ export class FileFileHistoryStore {
922
979
  }
923
980
  catch (err) {
924
981
  if (err.code === "ENOENT")
925
- return;
982
+ return undefined;
926
983
  this.disclose(this.scopesDir, `scope root unreadable (${err.code ?? "unknown"}) — blob GC aborted, every blob kept`);
927
- return;
984
+ return "the scope root could not be read, so every blob was kept";
928
985
  }
929
986
  const liveJournals = new Set([...[...this.activeCaptures.values()].flatMap((m) => [...m.values()]), ...[...this.activeImports.values()].flatMap((set) => [...set])]);
930
987
  for (const name of scopeDirs) {
@@ -1009,20 +1066,22 @@ export class FileFileHistoryStore {
1009
1066
  break;
1010
1067
  }
1011
1068
  if (!complete)
1012
- return;
1069
+ return "a scope's history or staging could not be judged during the live-set scan, so every blob was kept";
1013
1070
  let blobs;
1014
1071
  try {
1015
1072
  blobs = readdirSync(this.blobsDir);
1016
1073
  }
1017
1074
  catch (err) {
1018
- if (err.code !== "ENOENT") {
1019
- this.disclose(this.blobsDir, `blob directory unreadable (${err.code ?? "unknown"}) — blob GC skipped, every blob kept`);
1020
- }
1021
- return;
1075
+ if (err.code === "ENOENT")
1076
+ return undefined;
1077
+ this.disclose(this.blobsDir, `blob directory unreadable (${err.code ?? "unknown"}) — blob GC skipped, every blob kept`);
1078
+ return "the blob directory could not be read, so every blob was kept";
1022
1079
  }
1080
+ let stuck = 0;
1023
1081
  for (const blob of blobs)
1024
- if (!live.has(blob))
1025
- safeRm(join(this.blobsDir, blob));
1082
+ if (!live.has(blob) && !safeRm(join(this.blobsDir, blob)))
1083
+ stuck++;
1084
+ return stuck === 0 ? undefined : `${stuck} unreferenced blob(s) could not be removed`;
1026
1085
  }
1027
1086
  async adoptScope(fromScope, toScope) {
1028
1087
  try {
@@ -1145,7 +1204,10 @@ export class FileFileHistoryStore {
1145
1204
  };
1146
1205
  return { ok: true, history };
1147
1206
  }
1148
- async importHistory(scope, data, srcGetBlob) {
1207
+ importHistory(scope, data, srcGetBlob) {
1208
+ return this.writing(scope, () => this.importHistoryCounted(scope, data, srcGetBlob));
1209
+ }
1210
+ async importHistoryCounted(scope, data, srcGetBlob) {
1149
1211
  try {
1150
1212
  const shaped = validateFileHistoryExport(data);
1151
1213
  if (!shaped.ok)
@@ -15,6 +15,7 @@ import { type SessionPolicyStore } from "../../core/session-policy-store.js";
15
15
  import type { WorkflowJournalStore } from "../../core/workflow-journal-store.js";
16
16
  import type { UsageWindowStore } from "../../core/usage-window-store.js";
17
17
  import type { EngineStorageBackend } from "../../core/engine-storage-backend.js";
18
+ import { type RetentionDeclaration } from "../../core/retention.js";
18
19
  export { FileCheckpointStore, CHECKPOINT_LEDGER_EVENT_KINDS, readCheckpointLedger, type CheckpointLedgerEventKind, type CheckpointLedgerReading, type FileCheckpointStoreOptions, type ReadCheckpointLedgerOptions, } from "./checkpoint-store.js";
19
20
  export { FileMemoryStore } from "./memory-store.js";
20
21
  export { FileSessionRepo, type FileSessionRepoOptions } from "./session-store.js";
@@ -70,7 +71,16 @@ export interface FileStorageBackendOptions {
70
71
  /** Checkpoint store tuning (fsync cadence for `put`/`setPendingSteer`, ledger compaction threshold, the holder judge). The
71
72
  * corrupt-read sink and the session head read are the backend's own — the sink is {@link FileStorageBackendOptions.onCorruptRead}
72
73
  * (one failure grammar, one sink) and the head read is its session store's — so neither is accepted here. */
73
- checkpoint?: Omit<FileCheckpointStoreOptions, "onCorruptRead" | "sessionHeadOf">;
74
+ checkpoint?: Omit<FileCheckpointStoreOptions, "onCorruptRead" | "sessionHeadOf" | "retention">;
75
+ /**
76
+ * The managed-retention declaration of this backend's three declaring stores — {@link FileStorageBackend.sessionStore},
77
+ * {@link FileStorageBackend.checkpointStore} and {@link FileStorageBackend.toolResultStore} — stated by the party that runs the sweep
78
+ * (`"managed"`: an executor deletes their rows on schedule; default `"none"`; a third word refused, `config.retention_capability`).
79
+ * The backend carries no executor of its own: a deployment that says `"managed"` runs one over these stores (the legs it calls are
80
+ * `RETENTION_CASCADE`'s) and hands it to `assertRetentionCapability` as `executor`, which refuses `"managed"` beside `executor: null`.
81
+ * One word for the three, because one sweep covers them; it is not a per-store choice, so the `checkpoint` record does not take it.
82
+ */
83
+ retention?: RetentionDeclaration;
74
84
  /**
75
85
  * design/381 §片2 — file-history tuning, today just the boundary RETENTION bound (omitted ⇒ the
76
86
  * engine default; `{ retention: { keep: "unbounded" } }` hands the GC schedule to the deployment).
@@ -16,8 +16,9 @@ import { FileMailboxStore } from "./mailbox-store.js";
16
16
  import { FileRosterStore } from "../../agents/roster-store.js";
17
17
  import { FileFileHistoryStore } from "./file-history-store.js";
18
18
  import { readMountedToolNames } from "../../core/session-policy-store.js";
19
- import { optionKeys, receiveMembers, receiveOptions, refuseProxy, refuseStrayMembers } from "../../core/own-property-receipt.js";
19
+ import { optionKeys, receiveMembers, receiveOptions, refuseStrayMembers } from "../../core/own-property-receipt.js";
20
20
  import { receiveFileHistoryRetention } from "../../core/file-history-retention.js";
21
+ import { readRetentionDeclaration } from "../../core/retention.js";
21
22
  function nestedOptions(value, member, keys) {
22
23
  return value === undefined ? undefined : receiveMembers(value, { subject: `FileStorageBackendOptions.${member}`, unit: "option", moment: "at new FileStorageBackend" }, keys);
23
24
  }
@@ -36,7 +37,7 @@ export { atomicWriteFile, writeThenLink, ensureDir, readJsonlRecords, AppendLog
36
37
  export { processFingerprint, isProcessLive } from "./fs-atomic.js";
37
38
  export { AdoptionError, assertAdoptionBootGate, readRootAdoptionFile, writeRootAdoptionFile, ROOT_ADOPTION_FILE, } from "./adoption/marker.js";
38
39
  export { adoptLocalDataRoot, ackAdoptionConfig, witnessAdoptionConfig, listAdoptionQuarantine, readAdoptionStatus, } from "./adoption/adopt.js";
39
- const FILE_STORAGE_BACKEND_OPTION_KEYS = optionKeys()({ root: 0, utilityGate: 0, evict: 0, checkpoint: 0, fileHistory: 0, sessionPolicy: 0, embedder: 0, onCorruptRead: 0, sessions: 0 });
40
+ const FILE_STORAGE_BACKEND_OPTION_KEYS = optionKeys()({ root: 0, utilityGate: 0, evict: 0, checkpoint: 0, retention: 0, fileHistory: 0, sessionPolicy: 0, embedder: 0, onCorruptRead: 0, sessions: 0 });
40
41
  const NESTED_FILE_HISTORY_OPTION_KEYS = optionKeys()({ retention: 0 });
41
42
  const NESTED_SESSION_POLICY_OPTION_KEYS = optionKeys()({ mountedToolNames: 0 });
42
43
  const NESTED_CHECKPOINT_OPTION_KEYS = optionKeys()({ fsync: 0, compactEvery: 0, holderIsCurrent: 0 });
@@ -62,13 +63,8 @@ export class FileStorageBackend {
62
63
  fileSessions;
63
64
  fileWorkflowJournal;
64
65
  constructor(options) {
65
- if (options !== undefined && options !== null && typeof options === "object") {
66
- refuseProxy(options, { subject: "FileStorageBackend options", unit: "option", moment: "at new FileStorageBackend" });
67
- if (Object.hasOwn(options, "retention")) {
68
- throw Object.assign(new Error(`FileStorageBackend runs no retention executor, so its options take no \`retention\` word: its stores declare "none".`), { code: "config.retention_capability" });
69
- }
70
- }
71
66
  const opts = receiveOptions(options, "FileStorageBackend", FILE_STORAGE_BACKEND_OPTION_KEYS);
67
+ const retention = readRetentionDeclaration("FileStorageBackendOptions.retention", opts.retention);
72
68
  const checkpointRecord = nestedOptions(opts.checkpoint, "checkpoint", NESTED_CHECKPOINT_OPTION_KEYS);
73
69
  const checkpointOptions = checkpointRecord === undefined ? undefined : { ...checkpointRecord, ...readLedgerTuning(checkpointRecord, "FileCheckpointStore", "FileStorageBackendOptions.checkpoint") };
74
70
  const sessionPolicyRecord = nestedOptions(opts.sessionPolicy, "sessionPolicy", NESTED_SESSION_POLICY_OPTION_KEYS);
@@ -86,16 +82,16 @@ export class FileStorageBackend {
86
82
  const corruptRead = opts.onCorruptRead !== undefined ? { onCorruptRead: opts.onCorruptRead } : undefined;
87
83
  const repo = new FileSessionRepo(this.root, corruptRead);
88
84
  this.fileSessions = repo;
89
- this.ttl = new TtlSessionStore({ repo, evict: opts.evict ?? "forget", durability: "durable", placements: { subagent: { durability: "durable" } }, ...(opts.sessions !== undefined ? { hooks: opts.sessions } : {}) });
85
+ this.ttl = new TtlSessionStore({ repo, evict: opts.evict ?? "forget", durability: "durable", placements: { subagent: { durability: "durable" } }, retention, ...(opts.sessions !== undefined ? { hooks: opts.sessions } : {}) });
90
86
  this.sessionStore = this.ttl;
91
87
  const sessionHeadOf = this.ttl.headOf;
92
- this.fileCheckpoints = new FileCheckpointStore(this.root, { ...checkpointOptions, ...corruptRead, ...(sessionHeadOf !== undefined ? { sessionHeadOf } : {}) });
88
+ this.fileCheckpoints = new FileCheckpointStore(this.root, { ...checkpointOptions, ...corruptRead, retention, ...(sessionHeadOf !== undefined ? { sessionHeadOf } : {}) });
93
89
  built.push(() => this.fileCheckpoints.close());
94
90
  this.checkpointStore = this.fileCheckpoints;
95
91
  this.fileMemory = new FileMemoryStore(this.root, opts.embedder ? { embedder: opts.embedder } : {});
96
92
  built.push(() => this.fileMemory.close());
97
93
  this.memoryStore = guardedMemoryStore(this.fileMemory, opts.utilityGate);
98
- this.toolResultStore = new FileToolResultStore(this.root, corruptRead);
94
+ this.toolResultStore = new FileToolResultStore(this.root, { ...corruptRead, retention });
99
95
  this.sessionPolicyStore = new FileSessionPolicyStore(this.root, { ...sessionPolicyOptions, ...corruptRead });
100
96
  this.fileWorkflowJournal = new FileWorkflowJournalStore(this.root, true, corruptRead);
101
97
  built.push(() => this.fileWorkflowJournal.dispose());
@@ -251,6 +251,29 @@ export declare class FileDurableRulePartitionProvider implements DurableRulePart
251
251
  * into a retired bucket. A corrupt marker throws (fail-closed) rather than guessing an owner.
252
252
  */
253
253
  forLocalOwner(): DurableRulePartition;
254
+ /**
255
+ * The owners this directory can NAME that hold a bucket here, and how many buckets it cannot name — the one listing a host
256
+ * that must visit every bucket (a one-time migration over the rules of every owner) reads, so a bucket no record points at is
257
+ * not skipped. Names only: no rule, tombstone or revision is read, and no bucket file is opened.
258
+ *
259
+ * A bucket's file is named by a one-way digest of its owner (`principalRuleFileName`) and holds no owner name, so the
260
+ * directory names an owner only by what it records: `local-owner` when the local-owner bucket file is present, and the principals
261
+ * the adoption marker names (the adopted principal, and a principal source) when their bucket file is present. After an adoption
262
+ * the renamed bucket is the adopted principal's, so it is listed under that name whether or not any approval record ever named it.
263
+ * Every other digest-named bucket file is counted in `unnamedBuckets` — present, unreadable as to whose, and never silently
264
+ * dropped. A host reads `owners` through {@link forPrincipal} / {@link forLocalOwner} like any owner it knows; `unnamedBuckets > 0`
265
+ * says its census of owners is incomplete by that many, not that they are empty.
266
+ *
267
+ * Reading takes no lock and writes nothing. A directory this engine refuses to use refuses with
268
+ * {@link PERMISSION_RULES_DAMAGED_BUCKET_CODE}, as the read faces refuse it; a listing that failed to read refuses with
269
+ * {@link PERMISSION_RULES_UNREADABLE_BUCKET_CODE} and the system error's name in `errno`; an adoption marker that does not read
270
+ * refuses as {@link forPrincipal} refuses it (the marker is the truth of whose bucket is whose, so a listing never guesses
271
+ * past it). An absent directory lists nothing.
272
+ */
273
+ listBucketOwners(): {
274
+ readonly owners: readonly RuleOwner[];
275
+ readonly unnamedBuckets: number;
276
+ };
254
277
  /** Release the writer lock. A long-lived deployment holds it for its lifetime; a test or a short-lived
255
278
  * tool releases so the next holder is not told a live process owns the directory. */
256
279
  dispose(): void;