@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
@@ -1,11 +1,11 @@
1
- import { closeSync, constants as FS, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { closeSync, constants as FS, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { createHash, randomBytes } from "node:crypto";
4
4
  import { isRuleBehavior } from "../../core/permission-rule-model.js";
5
5
  import { posixModeBitsMeaningful } from "../../core/posix-mode-face.js";
6
6
  import { readRuleOwner } from "../../core/rule-owner.js";
7
7
  import { principalNameOf, readPrincipal } from "../../core/principal-name.js";
8
- import { PERMISSION_RULES_LATER_GRAMMAR_CODE, PERMISSION_RULE_WRITER, applySyncJoin, applyTombstones, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, foldDelta, unknownRuleWriteDeltaError, } from "../../core/permission-rule-store.js";
8
+ import { PERMISSION_RULES_DAMAGED_BUCKET_CODE, PERMISSION_RULES_LATER_GRAMMAR_CODE, PERMISSION_RULES_UNREADABLE_BUCKET_CODE, PERMISSION_RULE_WRITER, applySyncJoin, applyTombstones, assertDeleteDeltaCarriesNoAdd, assertRedemptionNotQuarantined, assertWriteDeltaScopeDurable, foldDelta, unknownRuleWriteDeltaError, } from "../../core/permission-rule-store.js";
9
9
  import { sameOrgPolicyContent } from "../../core/permission-rule-org.js";
10
10
  import { SESSION_RULES_GRAMMAR, readRuleGrammarStamp } from "../../core/session-policy-store.js";
11
11
  import { canonicalize } from "../../core/canonical-json.js";
@@ -31,6 +31,7 @@ export const ORG_STATE_FILE = "org.json";
31
31
  export class OrgRevisionRefusal extends Error {
32
32
  }
33
33
  const LOCAL_OWNER_FILE = "local-owner.json";
34
+ const HASHED_BUCKET_FILE = /^[0-9a-f]{64}\.json$/;
34
35
  const ADOPTION_FILE = "PERMISSION-RULES-ADOPTION.json";
35
36
  function judgeRuleAdoptionFile(dir) {
36
37
  let raw;
@@ -143,7 +144,18 @@ function refusalText(onError, sentence, location) {
143
144
  return `${sentence}. The location is reported to the store's error disclosure (onError), not in this message.`;
144
145
  }
145
146
  function unreadableError(r, sentence = r.unreadable) {
146
- return r.code !== undefined ? Object.assign(new Error(sentence), { code: r.code }) : new Error(sentence);
147
+ return Object.assign(new Error(sentence), { code: r.code, ...(r.errno !== undefined ? { errno: r.errno } : {}) });
148
+ }
149
+ function errnoOf(err) {
150
+ const code = err?.code;
151
+ return typeof code === "string" && /^E[A-Z0-9]+$/.test(code) ? code : undefined;
152
+ }
153
+ function systemFaultRefusal(onError, err, sentence, location) {
154
+ const errno = errnoOf(err);
155
+ const unreadable = refusalText(onError, sentence, location);
156
+ if (errno === "EEXIST" || errno === "ENOTDIR")
157
+ return { unreadable, code: PERMISSION_RULES_DAMAGED_BUCKET_CODE };
158
+ return { unreadable, code: PERMISSION_RULES_UNREADABLE_BUCKET_CODE, ...(errno !== undefined ? { errno } : {}) };
147
159
  }
148
160
  function discloseTo(onError, message) {
149
161
  try {
@@ -153,9 +165,15 @@ function discloseTo(onError, message) {
153
165
  }
154
166
  }
155
167
  function assertSafeDirAtRequest(dir, onError, act, vetting) {
156
- const fault = unsafeDirFault(dir, vetting);
168
+ let fault;
169
+ try {
170
+ fault = unsafeDirFault(dir, vetting);
171
+ }
172
+ catch (err) {
173
+ throw unreadableError(systemFaultRefusal(onError, err, `the permission-rule store directory could not be examined (${err?.code ?? err?.name ?? "unknown"}); refusing to ${act} it`, `${dir}: ${thrownText(err)}`));
174
+ }
157
175
  if (fault !== undefined)
158
- throw new Error(refusalText(onError, `the permission-rule store directory ${fault}; refusing to ${act} it`, dir));
176
+ throw unreadableError({ unreadable: refusalText(onError, `the permission-rule store directory ${fault}; refusing to ${act} it`, dir), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE });
159
177
  }
160
178
  function writerLockRefusal(err, onError) {
161
179
  let sentence;
@@ -194,7 +212,7 @@ class FileDurableRulePartition {
194
212
  read() {
195
213
  const bucket = "this owner's permission-rule bucket";
196
214
  const whole = "refusing the whole file and loading zero rules — repair the file, or remove it (removing it gives up every rule and tombstone it held)";
197
- const unreadable = (sentence, location = this.file) => ({ unreadable: refusalText(this.onError, sentence, location) });
215
+ const unreadable = (sentence, location = this.file) => ({ unreadable: refusalText(this.onError, sentence, location), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE });
198
216
  let raw;
199
217
  try {
200
218
  const dirFault = unsafeDirFault(this.dir, this.vetting);
@@ -209,7 +227,7 @@ class FileDurableRulePartition {
209
227
  const e = err;
210
228
  if (e?.code === "ENOENT")
211
229
  return { absent: true };
212
- return unreadable(`${bucket} could not be read (${e?.code ?? err?.name ?? "unknown"}); loading zero rules`, `${this.file}: ${thrownText(err)}`);
230
+ return systemFaultRefusal(this.onError, err, `${bucket} could not be read (${e?.code ?? err?.name ?? "unknown"}); loading zero rules`, `${this.file}: ${thrownText(err)}`);
213
231
  }
214
232
  let parsed;
215
233
  try {
@@ -487,6 +505,56 @@ export class FileDurableRulePartitionProvider {
487
505
  }
488
506
  return new FileDurableRulePartition(this.dir, join(this.dir, LOCAL_OWNER_FILE), this.acquireWriteLock, this.onError, this.vetting);
489
507
  }
508
+ listBucketOwners() {
509
+ const faulted = (err, what) => unreadableError(systemFaultRefusal(this.onError, err, `the permission-rule store directory could not be ${what} (${err?.code ?? err?.name ?? "unknown"})`, `${this.dir}: ${thrownText(err)}`));
510
+ try {
511
+ lstatSync(this.dir);
512
+ }
513
+ catch (err) {
514
+ if (err?.code === "ENOENT")
515
+ return Object.freeze({ owners: Object.freeze([]), unnamedBuckets: 0 });
516
+ throw faulted(err, "examined");
517
+ }
518
+ let dirFault;
519
+ try {
520
+ dirFault = unsafeDirFault(this.dir, this.vetting);
521
+ }
522
+ catch (err) {
523
+ throw faulted(err, "examined");
524
+ }
525
+ if (dirFault !== undefined) {
526
+ throw unreadableError({ unreadable: refusalText(this.onError, `the permission-rule store directory ${dirFault}; refusing to list its buckets`, this.dir), code: PERMISSION_RULES_DAMAGED_BUCKET_CODE });
527
+ }
528
+ const adoption = this.adoptionMarker();
529
+ const rec = adoption === undefined ? undefined : "adopted" in adoption ? adoption.adopted : adoption.marker;
530
+ let names;
531
+ try {
532
+ names = new Set(readdirSync(this.dir));
533
+ }
534
+ catch (err) {
535
+ throw faulted(err, "listed");
536
+ }
537
+ const owners = [];
538
+ if (names.has(LOCAL_OWNER_FILE))
539
+ owners.push({ kind: "local-owner" });
540
+ const claimed = new Set();
541
+ const named = new Set();
542
+ for (const principal of [rec?.toPrincipal, rec?.from.kind === "principal" ? rec.from.principal : undefined]) {
543
+ if (principal === undefined || named.has(principal))
544
+ continue;
545
+ named.add(principal);
546
+ const file = principalRuleFileName(principal);
547
+ if (!names.has(file))
548
+ continue;
549
+ claimed.add(file);
550
+ owners.push({ kind: "principal", principal });
551
+ }
552
+ let unnamedBuckets = 0;
553
+ for (const name of names)
554
+ if (HASHED_BUCKET_FILE.test(name) && !claimed.has(name))
555
+ unnamedBuckets++;
556
+ return Object.freeze({ owners: Object.freeze(owners), unnamedBuckets });
557
+ }
490
558
  dispose() {
491
559
  this.lock?.release();
492
560
  this.lock = undefined;
@@ -1,3 +1,4 @@
1
+ import { type RetentionDeclaration } from "../../core/retention.js";
1
2
  import type { ToolResultDeletionReport, ToolResultProvenance, ToolResultSessionListing, ToolResultSlice, ToolResultStore } from "../../core/tool-result-store.js";
2
3
  import { type CorruptReadInfo } from "./corrupt-read-sink.js";
3
4
  /**
@@ -32,8 +33,13 @@ export interface FileToolResultStoreOptions {
32
33
  * FileToolResultStore.ownerOf} answers `undefined` — the same word it uses for an entry nobody owns,
33
34
  * so a host that authorizes on it reads damage as "unowned". Swallow-guarded. */
34
35
  onCorruptRead?: (info: CorruptReadInfo) => void;
36
+ /** The store's managed-retention declaration (retention.ts), stated by the party that runs the sweep; default `"none"`, a third
37
+ * word refused (`config.retention_capability`). */
38
+ retention?: RetentionDeclaration;
35
39
  }
36
40
  export declare class FileToolResultStore implements ToolResultStore {
41
+ /** {@link FileToolResultStoreOptions.retention}, as read at construction. */
42
+ readonly retention: RetentionDeclaration;
37
43
  private readonly dir;
38
44
  private readonly discloseCorrupt;
39
45
  constructor(root: string, options?: FileToolResultStoreOptions);
@@ -116,6 +122,14 @@ export declare class FileToolResultStore implements ToolResultStore {
116
122
  reap(now: number, opts?: {
117
123
  maxAgeMs?: number;
118
124
  }): number;
125
+ /**
126
+ * Delete the entries with no owner record stored before `cutoffMs` (interface: {@link ToolResultStore.deleteUnattributable}): a
127
+ * content file with no owner record beside it. A present owner record keeps its entry whether it reads or not, and age is the
128
+ * content file's modification time, as {@link reap} reads it — so a `put` caught between its content and its owner record (its
129
+ * content is as new as the write) is never past a cutoff in the past. The owner record is looked for again just before the
130
+ * unlink, so one that landed after the listing still keeps its entry. Both namespaces; names this store writes only.
131
+ */
132
+ deleteUnattributable(cutoffMs: number): number;
119
133
  /**
120
134
  * The entries `sessionId` owns, as ref + recorded owner (interface: {@link ToolResultStore.listBySession}). The selection is
121
135
  * {@link deleteBySession}'s own: it walks the same two namespaces and matches on the SIDECAR's `sessionId`, never on a file name; a
@@ -1,18 +1,21 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
3
3
  import { join } from "node:path";
4
- import { ageCutoff } from "../../core/retention-policy.js";
4
+ import { ageCutoff, refuseRetentionPolicy } from "../../core/retention-policy.js";
5
+ import { readRetentionDeclaration } from "../../core/retention.js";
5
6
  import { assertSafeToolResultRef, assertToolResultProvenanceMatch, normalizeToolResultProvenance, ToolResultRefConflictError, } from "../../core/tool-result-store.js";
6
7
  import { ensureDir, sanitizePathComponent, writeThenLink } from "./fs-atomic.js";
7
8
  import { guardCorruptSink } from "./corrupt-read-sink.js";
8
9
  import { assertAdoptionBootGate } from "./adoption/marker.js";
9
10
  import { optionKeys, receiveOptions } from "../../core/own-property-receipt.js";
10
- const FILE_TOOL_RESULT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0 });
11
+ const FILE_TOOL_RESULT_STORE_OPTION_KEYS = optionKeys()({ onCorruptRead: 0, retention: 0 });
11
12
  export class FileToolResultStore {
13
+ retention;
12
14
  dir;
13
15
  discloseCorrupt;
14
16
  constructor(root, options) {
15
17
  const opts = receiveOptions(options, "FileToolResultStore", FILE_TOOL_RESULT_STORE_OPTION_KEYS);
18
+ this.retention = readRetentionDeclaration("FileToolResultStore.retention", opts.retention);
16
19
  assertAdoptionBootGate(root, "FileToolResultStore");
17
20
  this.dir = join(root, "tool-results");
18
21
  this.discloseCorrupt = guardCorruptSink(opts?.onCorruptRead);
@@ -221,6 +224,40 @@ export class FileToolResultStore {
221
224
  }
222
225
  return removed;
223
226
  }
227
+ deleteUnattributable(cutoffMs) {
228
+ if (typeof cutoffMs !== "number" || !Number.isFinite(cutoffMs)) {
229
+ refuseRetentionPolicy("FileToolResultStore.deleteUnattributable", "cutoffMs", cutoffMs, "a finite number of milliseconds since the epoch");
230
+ }
231
+ let removed = 0;
232
+ for (const [dir, folded] of [[this.dir, false], [join(this.dir, FOLDED_SUBDIR), true]]) {
233
+ let names;
234
+ try {
235
+ names = readdirSync(dir);
236
+ }
237
+ catch (err) {
238
+ if (err.code === "ENOENT")
239
+ continue;
240
+ throw err;
241
+ }
242
+ const listed = new Set(names);
243
+ for (const name of names) {
244
+ if (!name.endsWith(CONTENT_SUFFIX))
245
+ continue;
246
+ const stem = name.slice(0, -CONTENT_SUFFIX.length);
247
+ if (!isEncodedStem(stem, folded) || listed.has(`${stem}${OWNER_SUFFIX}`))
248
+ continue;
249
+ const path = join(dir, name);
250
+ const modified = modifiedAt(path);
251
+ if (modified === undefined || modified >= cutoffMs)
252
+ continue;
253
+ if (readOwnerAt(join(dir, `${stem}${OWNER_SUFFIX}`)) !== "gone")
254
+ continue;
255
+ unlinkIfAbsentOk(path);
256
+ removed++;
257
+ }
258
+ }
259
+ return removed;
260
+ }
224
261
  listBySession(sessionId) {
225
262
  const entries = [];
226
263
  let unattributable = 0;
@@ -73,6 +73,10 @@ export declare class FileWorkflowJournalStore implements WorkflowJournalStore {
73
73
  * (`notRecords`) and the scope the first record fixes. Rows come back as written — which arm each one is, and
74
74
  * whether anything refuses, is {@link load}'s question, so the scope lookup `append` makes refuses on nothing. */
75
75
  private replay;
76
+ /** Erase the run's ledger file when its first record's scope is `scope` (interface: {@link WorkflowJournalStore.deleteRun}). A ledger
77
+ * no record attributes to a scope is not erased (nothing says it is this caller's). The run's open append log is closed first, so
78
+ * the next append to the id starts a new ledger. A traversal-shaped id has no ledger here: `false`. */
79
+ deleteRun(runId: string, scope: string): Promise<boolean>;
76
80
  append(runId: string, scope: string, entry: WorkflowJournalEntry): Promise<void>;
77
81
  /** The run's entries, ascending by ordinal, each winning line read through {@link readWorkflowJournalEntry}. A
78
82
  * ledger line that is not one of the run's records, or a corrupt row, REFUSES the whole load: dropped, what it
@@ -95,6 +95,23 @@ export class FileWorkflowJournalStore {
95
95
  byOrdinal.set(rec.ordinal, rec);
96
96
  return { scope, byOrdinal, notRecords };
97
97
  }
98
+ async deleteRun(runId, scope) {
99
+ const rec = this.replay(runId);
100
+ if (rec === undefined || rec.scope !== scope)
101
+ return false;
102
+ const log = this.logs.get(runId);
103
+ this.logs.delete(runId);
104
+ log?.close();
105
+ this.scopes.delete(runId);
106
+ try {
107
+ unlinkSync(this.pathFor(runId));
108
+ }
109
+ catch (err) {
110
+ if (err.code !== "ENOENT")
111
+ throw err;
112
+ }
113
+ return true;
114
+ }
98
115
  async append(runId, scope, entry) {
99
116
  assertJournalEntryFits(entry);
100
117
  const committed = this.scopes.get(runId) ?? this.replay(runId)?.scope;
@@ -33,6 +33,9 @@ export declare class FileWorkflowRunStore implements WorkflowRunStore {
33
33
  maxAgeMs?: number;
34
34
  keep?: number;
35
35
  }): Promise<number>;
36
+ /** The session's terminal runs, deleted each under its own id lock with the selection re-checked against the live row (interface:
37
+ * {@link WorkflowRunStore.deleteBySession}) — a run a concurrent update flipped back to running is kept, as `reap` keeps one. */
38
+ deleteBySession(sessionId: string, scope: string): Promise<string[]>;
36
39
  /** Force a compaction now (test/inspection): rewrite the snapshot from the authoritative map and
37
40
  * truncate the live ledger (RB-167's closeForSwap recipe lives in the base). */
38
41
  compactNow(): void;
@@ -113,6 +113,21 @@ export class FileWorkflowRunStore {
113
113
  }
114
114
  return n;
115
115
  }
116
+ async deleteBySession(sessionId, scope) {
117
+ const selected = (r) => r !== undefined && r.scope === scope && r.originatingSessionId === sessionId && isTerminalWorkflowStatus(r.status);
118
+ const deleted = [];
119
+ for (const id of [...this.runs.values()].filter(selected).map((r) => r.id)) {
120
+ const gone = await this.withLock(id, () => {
121
+ if (!selected(this.runs.get(id)))
122
+ return false;
123
+ this.commit({ t: "delete", id }, this.fsyncEnabled);
124
+ return true;
125
+ });
126
+ if (gone)
127
+ deleted.push(id);
128
+ }
129
+ return deleted;
130
+ }
116
131
  compactNow() {
117
132
  this.ledger.compact();
118
133
  }
@@ -1,3 +1,4 @@
1
+ import type { RefusalEcho } from "../../core/refusal-echo.js";
1
2
  import { type PathGuardFold, type PathGuardRow, type PathRowsHit, type TargetViews } from "../../core/path-guard-rows.js";
2
3
  /**
3
4
  * One deny entry: a `/`-separated run of path SEGMENTS. `*` matches any run of non-separator
@@ -306,7 +307,9 @@ export declare const READ_ROW_WRITE_SCOPE = "A read deny row holds on writes too
306
307
  * ({@link WriteDenyMatcher.guardsReads}) says the path's reads are denied, where a row of the write face alone says the
307
308
  * write list.
308
309
  */
309
- export declare function readDenySentence(finding: {
310
+ export declare function readDenySentence(finding: ReadDenyFinding): string;
311
+ /** One deny finding: what the sentence of {@link readDenyRefusal} says and the list of literals it quotes are both read off it. */
312
+ export interface ReadDenyFinding {
310
313
  readonly action?: string;
311
314
  readonly target: string;
312
315
  readonly canonical?: string;
@@ -318,7 +321,17 @@ export declare function readDenySentence(finding: {
318
321
  * `Read(…)` rule, not a rule about writing. The sentence then says the path's reads are denied, which is why it is not
319
322
  * written, instead of calling a read row a write deny row. */
320
323
  readonly readRow?: true;
321
- }): string;
324
+ }
325
+ /**
326
+ * The deny finding minted ONCE as both of its faces: the sentence ({@link readDenySentence}) and the literals that sentence
327
+ * quotes, in the order it quotes them — the target (with its canonical target where the sentence names one), the view the
328
+ * pattern actually hit when that is a spelling other than the target, and the pattern. The list holds each literal whole; only the
329
+ * sentence elides the middle of a long one.
330
+ */
331
+ export declare function readDenyRefusal(finding: ReadDenyFinding): {
332
+ readonly sentence: string;
333
+ readonly echoed: readonly RefusalEcho[];
334
+ };
322
335
  /** The per-part budget of the deny sentence — the gate's own card-account cap, not a second number. */
323
336
  export declare const READ_DENY_SENTENCE_PART_MAX = 200;
324
337
  /** `s` verbatim when it fits `budget`, else elided in its MIDDLE ({@link elideMiddle}). */
@@ -188,17 +188,25 @@ export const SENSITIVE_PATH_DENY_SCOPE = "This list guards credential-class path
188
188
  export const WRITE_DENY_SCOPE = "A write deny row holds regardless of the containment roots and of the permission mode.";
189
189
  export const READ_ROW_WRITE_SCOPE = "A read deny row holds on writes too, regardless of the containment roots and of the permission mode.";
190
190
  export function readDenySentence(finding) {
191
+ return readDenyRefusal(finding).sentence;
192
+ }
193
+ export function readDenyRefusal(finding) {
191
194
  const write = finding.face === "write";
192
195
  const canonicalNote = finding.canonical !== undefined && finding.canonical !== finding.target ? `(canonical target: "${fitMiddle(finding.canonical, READ_DENY_SENTENCE_PART_MAX)}") ` : "";
193
196
  const lexicalHit = finding.matchedView !== undefined && finding.matchedView !== (finding.canonical ?? finding.target);
194
197
  const frame = `${finding.action ?? (write ? "writing" : "reading")} "${fitMiddle(finding.target, READ_DENY_SENTENCE_PART_MAX)}" ${canonicalNote}is refused:`;
195
198
  const pattern = fitMiddle(finding.pattern, READ_DENY_SENTENCE_PART_MAX);
199
+ const echoed = Object.freeze([
200
+ Object.freeze({ kind: "path", value: finding.target, ...(finding.canonical !== undefined && finding.canonical !== finding.target ? { canonical: finding.canonical } : {}) }),
201
+ ...(lexicalHit ? [Object.freeze({ kind: "path", value: finding.matchedView })] : []),
202
+ Object.freeze({ kind: "pattern", value: finding.pattern }),
203
+ ]);
196
204
  if (write && finding.readRow === true) {
197
205
  const reaches = lexicalHit ? `the path passes through "${fitMiddle(finding.matchedView, READ_DENY_SENTENCE_PART_MAX)}", which the read deny row "${pattern}" denies reading` : `the target is a path the read deny row "${pattern}" denies reading`;
198
- return `${frame} ${reaches} — a path whose reads are denied is not written either. ${READ_ROW_WRITE_SCOPE}`;
206
+ return { sentence: `${frame} ${reaches} — a path whose reads are denied is not written either. ${READ_ROW_WRITE_SCOPE}`, echoed };
199
207
  }
200
208
  const judged = lexicalHit ? `the requested path's spelling ("${fitMiddle(finding.matchedView, READ_DENY_SENTENCE_PART_MAX)}") matches` : "the target matches";
201
- return `${frame} ${judged} ${sensitivePathDenyList(pattern, write ? "write" : "read")}. ${write ? WRITE_DENY_SCOPE : SENSITIVE_PATH_DENY_SCOPE}`;
209
+ return { sentence: `${frame} ${judged} ${sensitivePathDenyList(pattern, write ? "write" : "read")}. ${write ? WRITE_DENY_SCOPE : SENSITIVE_PATH_DENY_SCOPE}`, echoed };
202
210
  }
203
211
  export const READ_DENY_SENTENCE_PART_MAX = PROBE_REASON_MAX;
204
212
  export function fitMiddle(s, budget) {
@@ -19,6 +19,7 @@
19
19
  */
20
20
  import type { ExecutionEnv } from "../../internal/harness-types.js";
21
21
  import { violationDetails } from "./safety.js";
22
+ import type { RefusalEcho } from "../../core/refusal-echo.js";
22
23
  import { type ShellReadPlan } from "./shell-read-plan.js";
23
24
  import { type ReadLanding } from "./shell-read-identity.js";
24
25
  import { type HomeViewSource } from "./read-deny-home.js";
@@ -59,6 +60,7 @@ export interface ShellReadVouch extends ShellReadVerdictFacts {
59
60
  readonly face?: never;
60
61
  readonly sentence?: never;
61
62
  readonly details?: never;
63
+ readonly echoed?: never;
62
64
  readonly readRootCandidate?: never;
63
65
  readonly unestablished?: never;
64
66
  }
@@ -86,6 +88,9 @@ export interface ShellReadQuestion extends ShellReadVerdictFacts {
86
88
  * still carries WHAT was found on its `tool_end` — the targets outside the roots (`readonly_out_of_root`, or the file
87
89
  * tools' `path_not_in_root`), or that nothing could be established (`read_unestablished`). */
88
90
  readonly details?: ShellReadRefusalDetails;
91
+ /** `refuse` on a deny hit: the literals the refusal `sentence` quotes (target, the view that matched, pattern), minted with it
92
+ * from the one finding ({@link import("./read-deny.js").readDenyRefusal}); the gate files them on the refusal's record. */
93
+ readonly echoed?: readonly RefusalEcho[];
89
94
  /** `mandated` on an `outside_roots` finding: the directory whose grant would clear this ask. */
90
95
  readonly readRootCandidate?: ReadRootGrantCandidate;
91
96
  /** A FACT beside the disposition: some read of the command could not be established (an `unestablishable` or `declined`
@@ -212,8 +217,9 @@ export interface ShellReadStationOptions {
212
217
  * — the one trusted channel by which a refusal after the gate reaches the call's record (the tool's result is the
213
218
  * tool's own word, and a refusal must not read as a tool failure under the gate's `allowed`). Every shell tool this
214
219
  * station admits (both Bash faces, Monitor) refuses through {@link ShellReadStation.admit}, so this is the one
215
- * place to hear it. The Runner's; absent outside one. */
216
- readonly onAdmissionRefused?: (toolCallId: string) => void;
220
+ * place to hear it. A deny refusal passes the literals its sentence quotes (`echoed`, the same mint as the sentence). The
221
+ * Runner's; absent outside one. */
222
+ readonly onAdmissionRefused?: (toolCallId: string, echoed?: readonly RefusalEcho[]) => void;
217
223
  }
218
224
  /** What a consumer hands {@link judgeShellRead}: the command as written, the environment whose filesystem
219
225
  * answers where its words land (symlinks resolved, patterns expanded — a `NodeExecutionEnv` over a real
@@ -2,7 +2,7 @@ import { observeEnvironment } from "./shell-read-environment.js";
2
2
  import { errorResult } from "../../core/tools.js";
3
3
  import { BASH_READONLY_CONFINEMENT_NOTE } from "./fs-shared.js";
4
4
  import { isAbsoluteForFamily, normalizeAbsPathLexically, pathFamilyOf, violationDetails, withinAnyRoot } from "./safety.js";
5
- import { checkedReadDenyHomes, fitMiddle, READ_DENY_SENTENCE_PART_MAX, readDenySentence } from "./read-deny.js";
5
+ import { checkedReadDenyHomes, fitMiddle, READ_DENY_SENTENCE_PART_MAX, readDenyRefusal } from "./read-deny.js";
6
6
  import { NOT_AUTO_ALLOWED, declinedProgramSentence } from "./bash-program-position.js";
7
7
  import { bashClassifyDefaultAllow } from "./bash-readonly-classifier.js";
8
8
  import { planShellReads } from "./shell-read-plan.js";
@@ -302,10 +302,10 @@ function refusalOf(tool, fold, boundary, paths) {
302
302
  if (fold.finding === "deny_hit" && w?.deny !== undefined) {
303
303
  const target = w.read.target ?? w.deny.matchedView;
304
304
  const write = w.deny.face === "write";
305
- const core = readDenySentence({ target, pattern: w.deny.pattern, matchedView: w.deny.matchedView, ...(write ? { face: "write" } : {}), ...(w.deny.readRow === true ? { readRow: true } : {}) });
305
+ const { sentence: core, echoed } = readDenyRefusal({ target, pattern: w.deny.pattern, matchedView: w.deny.matchedView, ...(write ? { face: "write" } : {}), ...(w.deny.readRow === true ? { readRow: true } : {}) });
306
306
  const through = deniedThrough(w.read, boundary);
307
307
  const sentence = `Error (${tool}): ${core} ${write ? writeDenyRefusalNote() : DENY_REFUSAL_NOTE}${through !== undefined ? ` ${DENIED_THROUGH_NOTE[through]}` : ""}`;
308
- return { sentence, ...(write ? {} : { details: violationDetails({ code: "read_path_denied", message: sentence, target, pattern: w.deny.pattern }) }) };
308
+ return { sentence, echoed, ...(write ? {} : { details: violationDetails({ code: "read_path_denied", message: sentence, target, pattern: w.deny.pattern }) }) };
309
309
  }
310
310
  const account = findingAccount(fold, boundary);
311
311
  const sentence = `Error (${tool}): ${account}. ${BASH_READONLY_CONFINEMENT_NOTE}`;
@@ -345,7 +345,7 @@ function verdictOf(tool, seat, fold, judged, boundary) {
345
345
  const by = fold.finding === "unanswered" ? { environmentSilent: true } : {};
346
346
  if (disposition === "refuse") {
347
347
  const r = refusalOf(tool, fold, boundary, paths);
348
- return { disposition, finding: fold.finding, ...by, ...writes, sentence: r.sentence, ...(r.details !== undefined ? { details: r.details } : {}) };
348
+ return { disposition, finding: fold.finding, ...by, ...writes, sentence: r.sentence, ...(r.details !== undefined ? { details: r.details } : {}), ...(r.echoed !== undefined ? { echoed: r.echoed } : {}) };
349
349
  }
350
350
  const grant = fold.finding === "outside_roots" ? readRootGrantCandidateOf(judged, boundary) : undefined;
351
351
  const containment = fold.finding === "outside_roots" || fold.finding === "unestablishable" || fold.finding === "unanswered";
@@ -520,8 +520,8 @@ export function createShellReadStation(opts) {
520
520
  if (a === undefined)
521
521
  return undefined;
522
522
  admissions.delete(toolCallId);
523
- const refused = (r) => {
524
- opts.onAdmissionRefused?.(toolCallId);
523
+ const refused = (r, echoed) => {
524
+ opts.onAdmissionRefused?.(toolCallId, echoed);
525
525
  return r;
526
526
  };
527
527
  if (a.toolName !== toolName || a.command !== command) {
@@ -536,7 +536,7 @@ export function createShellReadStation(opts) {
536
536
  const fold = foldShellReadFindings(judged);
537
537
  if (fold.finding === "deny_hit") {
538
538
  const r = refusalOf(toolName, fold, a.boundary, outsidePathsOf(judged));
539
- return refused(errorResult(r.sentence, r.details));
539
+ return refused(errorResult(r.sentence, r.details), r.echoed);
540
540
  }
541
541
  const moved = changed[0];
542
542
  const identity = { finding: "identity_changed", witness: { read: moved, kind: "none", containment: "unknown" } };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sema-agent/core",
3
- "version": "7.63.0",
3
+ "version": "7.64.0",
4
4
  "description": "Stateless, task-oriented AI agent core",
5
5
  "type": "module",
6
6
  "license": "BUSL-1.1",
@@ -124,7 +124,7 @@
124
124
  "dependencies": {
125
125
  "@modelcontextprotocol/client": "2.4.0",
126
126
  "@modelcontextprotocol/core": "2.4.0",
127
- "@sema-agent/primitives": "7.63.0",
127
+ "@sema-agent/primitives": "7.64.0",
128
128
  "typebox": "1.1.39",
129
129
  "undici": "7.30.0"
130
130
  },