@sema-agent/core 7.62.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 (320) hide show
  1. package/CHANGELOG.md +936 -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-transcript-placement.d.ts +23 -0
  23. package/dist/agents/subagent-transcript-placement.js +14 -0
  24. package/dist/agents/subagent.js +102 -54
  25. package/dist/brain/route-adjudicator.js +9 -4
  26. package/dist/core/allow-entry.d.ts +4 -0
  27. package/dist/core/approval-object.js +1 -1
  28. package/dist/core/arg-summary.js +1 -1
  29. package/dist/core/ask-origin.d.ts +1 -1
  30. package/dist/core/ask-origin.js +2 -2
  31. package/dist/core/ask-question.d.ts +2 -2
  32. package/dist/core/ask-unresolvable-notice.d.ts +13 -4
  33. package/dist/core/ask-unresolvable-notice.js +10 -3
  34. package/dist/core/auto-compaction.d.ts +7 -5
  35. package/dist/core/background-agent-store.d.ts +7 -0
  36. package/dist/core/background-agent-store.js +3 -0
  37. package/dist/core/canonical-json.d.ts +23 -13
  38. package/dist/core/canonical-json.js +4 -4
  39. package/dist/core/checkpoint-queries.d.ts +50 -4
  40. package/dist/core/checkpoint-queries.js +42 -17
  41. package/dist/core/checkpoint-requirements.d.ts +3 -3
  42. package/dist/core/checkpoint-requirements.js +2 -1
  43. package/dist/core/checkpoint-row-verdict.d.ts +15 -4
  44. package/dist/core/checkpoint-row-verdict.js +22 -2
  45. package/dist/core/checkpoint-store.d.ts +28 -11
  46. package/dist/core/checkpoint-store.js +45 -4
  47. package/dist/core/compliance.d.ts +6 -2
  48. package/dist/core/compliance.js +3 -3
  49. package/dist/core/context-settings.d.ts +40 -9
  50. package/dist/core/context-settings.js +32 -10
  51. package/dist/core/engine-attestation.d.ts +27 -7
  52. package/dist/core/engine-attestation.js +5 -1
  53. package/dist/core/engine-notice.d.ts +43 -5
  54. package/dist/core/extension-requester.d.ts +9 -0
  55. package/dist/core/extension-requester.js +7 -0
  56. package/dist/core/file-history-store.d.ts +28 -0
  57. package/dist/core/file-history-store.js +48 -5
  58. package/dist/core/fs-write-gate-policy.js +1 -1
  59. package/dist/core/gate-fold.js +2 -0
  60. package/dist/core/gate-lanes.js +2 -0
  61. package/dist/core/gate-outcome.d.ts +39 -2
  62. package/dist/core/gate-outcome.js +20 -1
  63. package/dist/core/git-worktree-env.d.ts +62 -3
  64. package/dist/core/git-worktree-env.js +91 -30
  65. package/dist/core/governance-codes.d.ts +9 -3
  66. package/dist/core/governance-codes.js +17 -3
  67. package/dist/core/leg-identity.d.ts +19 -1
  68. package/dist/core/leg-identity.js +12 -0
  69. package/dist/core/mailbox-store.d.ts +39 -4
  70. package/dist/core/mailbox-store.js +14 -2
  71. package/dist/core/memory-engine/consolidation-driver.d.ts +32 -17
  72. package/dist/core/memory-engine/consolidation-driver.js +99 -98
  73. package/dist/core/memory-engine/consolidation.d.ts +74 -10
  74. package/dist/core/memory-engine/consolidation.js +183 -11
  75. package/dist/core/memory-engine/control-objects.d.ts +25 -0
  76. package/dist/core/memory-engine/control-objects.js +151 -0
  77. package/dist/core/memory-engine/control-plane-adoption.d.ts +48 -0
  78. package/dist/core/memory-engine/control-plane-adoption.js +159 -0
  79. package/dist/core/memory-engine/data-plane.d.ts +8 -4
  80. package/dist/core/memory-engine/data-plane.js +11 -6
  81. package/dist/core/memory-engine/delegation-settlement.d.ts +58 -40
  82. package/dist/core/memory-engine/delegation-settlement.js +270 -85
  83. package/dist/core/memory-engine/dual-root.d.ts +12 -6
  84. package/dist/core/memory-engine/dual-root.js +11 -7
  85. package/dist/core/memory-engine/engine.d.ts +136 -58
  86. package/dist/core/memory-engine/engine.js +491 -394
  87. package/dist/core/memory-engine/entry-scan.d.ts +8 -0
  88. package/dist/core/memory-engine/entry-scan.js +3 -0
  89. package/dist/core/memory-engine/file-backend.d.ts +62 -60
  90. package/dist/core/memory-engine/file-backend.js +122 -198
  91. package/dist/core/memory-engine/index.d.ts +8 -7
  92. package/dist/core/memory-engine/index.js +7 -6
  93. package/dist/core/memory-engine/landing-admission.d.ts +5 -3
  94. package/dist/core/memory-engine/landing-admission.js +3 -3
  95. package/dist/core/memory-engine/layout.d.ts +127 -46
  96. package/dist/core/memory-engine/layout.js +264 -109
  97. package/dist/core/memory-engine/memory-backend-contract.d.ts +26 -1
  98. package/dist/core/memory-engine/memory-backend-contract.js +476 -0
  99. package/dist/core/memory-engine/memory-deployment.d.ts +42 -11
  100. package/dist/core/memory-engine/memory-deployment.js +54 -15
  101. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  102. package/dist/core/memory-engine/origin-clearance.js +68 -9
  103. package/dist/core/memory-engine/scope-contract.d.ts +52 -11
  104. package/dist/core/memory-engine/scope-contract.js +68 -19
  105. package/dist/core/memory-engine/session-write-home.d.ts +37 -2
  106. package/dist/core/memory-engine/session-write-home.js +38 -11
  107. package/dist/core/memory-engine/sync-client.d.ts +3 -1
  108. package/dist/core/memory-engine/sync-client.js +7 -0
  109. package/dist/core/memory-engine/sync-report.d.ts +3 -2
  110. package/dist/core/memory-engine/sync-report.js +6 -2
  111. package/dist/core/memory-engine/tools.d.ts +2 -2
  112. package/dist/core/memory-engine/tools.js +10 -10
  113. package/dist/core/memory-engine/types.d.ts +155 -19
  114. package/dist/core/memory-engine/types.js +2 -0
  115. package/dist/core/memory.js +15 -6
  116. package/dist/core/mode-policy.js +3 -3
  117. package/dist/core/mods/agent-stations.d.ts +18 -0
  118. package/dist/core/mods/agent-stations.js +8 -6
  119. package/dist/core/mods/extension-call.d.ts +4 -0
  120. package/dist/core/mods/extension-call.js +8 -0
  121. package/dist/core/mods/stations.d.ts +20 -1
  122. package/dist/core/mods/stations.js +21 -2
  123. package/dist/core/mods/tool-call.js +3 -4
  124. package/dist/core/parent-spec-seat.d.ts +2 -2
  125. package/dist/core/park-selfcheck.js +2 -2
  126. package/dist/core/pause-registry.d.ts +2 -0
  127. package/dist/core/pause-registry.js +3 -0
  128. package/dist/core/peer-channel.d.ts +5 -0
  129. package/dist/core/permission-rule-consent.d.ts +26 -8
  130. package/dist/core/permission-rule-consent.js +76 -36
  131. package/dist/core/permission-rule-store.d.ts +72 -13
  132. package/dist/core/permission-rule-store.js +29 -8
  133. package/dist/core/read-only-shell.js +3 -2
  134. package/dist/core/redaction-marks.d.ts +8 -0
  135. package/dist/core/redaction-marks.js +6 -0
  136. package/dist/core/refusal-echo.d.ts +20 -0
  137. package/dist/core/refusal-echo.js +33 -0
  138. package/dist/core/remote-env.d.ts +12 -1
  139. package/dist/core/remote-env.js +3 -0
  140. package/dist/core/retention.d.ts +180 -10
  141. package/dist/core/retention.js +45 -0
  142. package/dist/core/retired-keys.d.ts +5 -0
  143. package/dist/core/retired-keys.js +3 -0
  144. package/dist/core/rule-offer-read.d.ts +0 -4
  145. package/dist/core/rule-offer-read.js +2 -18
  146. package/dist/core/runner/child-tree.d.ts +29 -3
  147. package/dist/core/runner/child-tree.js +39 -16
  148. package/dist/core/runner/classifier-ladder.d.ts +7 -1
  149. package/dist/core/runner/classifier-ladder.js +4 -2
  150. package/dist/core/runner/compact-session.js +10 -7
  151. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  152. package/dist/core/runner/compaction-call-options.js +3 -2
  153. package/dist/core/runner/contracts.d.ts +39 -11
  154. package/dist/core/runner/delegation-owner.d.ts +10 -3
  155. package/dist/core/runner/delegation-owner.js +4 -1
  156. package/dist/core/runner/gate-exit.d.ts +6 -0
  157. package/dist/core/runner/gate-exit.js +13 -4
  158. package/dist/core/runner/inherited-ask-grants.js +1 -1
  159. package/dist/core/runner/memory-consolidation-driver.d.ts +10 -5
  160. package/dist/core/runner/memory-consolidation-driver.js +12 -9
  161. package/dist/core/runner/memory-consolidation-write-judge.d.ts +2 -1
  162. package/dist/core/runner/memory-consolidation-write-judge.js +3 -2
  163. package/dist/core/runner/person-path-rows.d.ts +8 -3
  164. package/dist/core/runner/person-path-rows.js +5 -1
  165. package/dist/core/runner/placement-fence.d.ts +12 -0
  166. package/dist/core/runner/placement-fence.js +20 -6
  167. package/dist/core/runner/prepare-ask-lane.js +5 -5
  168. package/dist/core/runner/prepare-caps-and-workflow.d.ts +7 -2
  169. package/dist/core/runner/prepare-caps-and-workflow.js +7 -4
  170. package/dist/core/runner/prepare-config-doors.js +4 -0
  171. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  172. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  173. package/dist/core/runner/prepare-execution-env.js +17 -6
  174. package/dist/core/runner/prepare-gate-stations.d.ts +5 -0
  175. package/dist/core/runner/prepare-gate-stations.js +5 -5
  176. package/dist/core/runner/prepare-hands-readface.d.ts +2 -1
  177. package/dist/core/runner/prepare-hands-readface.js +5 -4
  178. package/dist/core/runner/prepare-inherited-gate.d.ts +13 -9
  179. package/dist/core/runner/prepare-inherited-gate.js +12 -6
  180. package/dist/core/runner/prepare-memory-engine-session.d.ts +2 -4
  181. package/dist/core/runner/prepare-memory-engine-session.js +4 -4
  182. package/dist/core/runner/prepare-memory.d.ts +7 -2
  183. package/dist/core/runner/prepare-memory.js +41 -39
  184. package/dist/core/runner/prepare-park-ask.js +4 -3
  185. package/dist/core/runner/prepare-policy-chain.js +7 -7
  186. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  187. package/dist/core/runner/prepare-task.js +26 -18
  188. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  189. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  190. package/dist/core/runner/prepare-workspace-restore.js +3 -6
  191. package/dist/core/runner/resume-admission.d.ts +2 -2
  192. package/dist/core/runner/resume-admission.js +2 -23
  193. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  194. package/dist/core/runner/role-resolution-table.js +62 -0
  195. package/dist/core/runner/run-compaction-machinery.js +2 -2
  196. package/dist/core/runner/run-identity-wiring.js +12 -9
  197. package/dist/core/runner/run-leg.js +9 -5
  198. package/dist/core/runner/run-notification-lane.js +22 -22
  199. package/dist/core/runner/run-recovery-lanes.js +3 -3
  200. package/dist/core/runner/run-settle-and-teardown.js +3 -2
  201. package/dist/core/runner/run-terminal-adoption.js +1 -1
  202. package/dist/core/runner/run-turn-boundary.js +14 -15
  203. package/dist/core/runner/runtask.js +1 -1
  204. package/dist/core/runner/terminal-account.js +1 -1
  205. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  206. package/dist/core/runner/tool-occurrence.js +2 -2
  207. package/dist/core/runner-deps.d.ts +7 -3
  208. package/dist/core/secret-env.d.ts +1 -1
  209. package/dist/core/secret-env.js +4 -4
  210. package/dist/core/session-checkout.d.ts +168 -0
  211. package/dist/core/session-checkout.js +579 -0
  212. package/dist/core/session-store.d.ts +12 -4
  213. package/dist/core/session-store.js +23 -3
  214. package/dist/core/session.d.ts +16 -2
  215. package/dist/core/session.js +3 -0
  216. package/dist/core/shell-read-silence.js +8 -0
  217. package/dist/core/store-contracts/checkpoint-store-contract.d.ts +0 -12
  218. package/dist/core/store-contracts/checkpoint-store-contract.js +6 -7
  219. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  220. package/dist/core/store-contracts/session-store-contract.js +39 -0
  221. package/dist/core/task-event.d.ts +30 -5
  222. package/dist/core/task-notification.d.ts +119 -32
  223. package/dist/core/task-notification.js +186 -100
  224. package/dist/core/task-registry-agent.d.ts +25 -2
  225. package/dist/core/task-registry-agent.js +56 -22
  226. package/dist/core/task-registry-shared.d.ts +33 -11
  227. package/dist/core/task-registry.d.ts +33 -9
  228. package/dist/core/task-registry.js +36 -18
  229. package/dist/core/task-spec-members.js +1 -1
  230. package/dist/core/task-spec.d.ts +27 -2
  231. package/dist/core/tool-errors.d.ts +14 -6
  232. package/dist/core/tool-errors.js +1 -1
  233. package/dist/core/tool-policy.d.ts +32 -13
  234. package/dist/core/tool-policy.js +27 -17
  235. package/dist/core/tool-result-store.d.ts +20 -0
  236. package/dist/core/tool-spec.d.ts +42 -19
  237. package/dist/core/trace.d.ts +3 -2
  238. package/dist/core/types.d.ts +1 -1
  239. package/dist/core/untrusted-egress.d.ts +15 -4
  240. package/dist/core/untrusted-egress.js +23 -22
  241. package/dist/core/workflow-journal-store.d.ts +11 -0
  242. package/dist/core/workflow-journal-store.js +7 -0
  243. package/dist/core/workflow-run-store.d.ts +9 -0
  244. package/dist/core/workflow-run-store.js +6 -0
  245. package/dist/core/workspace-snapshot.d.ts +3 -1
  246. package/dist/core/workspace-snapshot.js +1 -0
  247. package/dist/engine/compaction/compaction.d.ts +2 -1
  248. package/dist/engine/harness/types.d.ts +67 -1
  249. package/dist/engine/harness/types.js +108 -0
  250. package/dist/engine/session/import-validate.js +6 -1
  251. package/dist/engine/session/session.d.ts +30 -1
  252. package/dist/engine/session/session.js +48 -1
  253. package/dist/index.d.ts +12 -7
  254. package/dist/index.js +12 -7
  255. package/dist/internal/harness-types.d.ts +1 -1
  256. package/dist/orchestration/run-workflow-tool.d.ts +8 -1
  257. package/dist/orchestration/run-workflow-tool.js +8 -0
  258. package/dist/orchestration/workflow-types.d.ts +2 -1
  259. package/dist/orchestration/workflow.d.ts +6 -0
  260. package/dist/orchestration/workflow.js +5 -2
  261. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  262. package/dist/stores/file/checkpoint-store.js +4 -1
  263. package/dist/stores/file/file-history-store.d.ts +13 -0
  264. package/dist/stores/file/file-history-store.js +75 -13
  265. package/dist/stores/file/index.d.ts +11 -1
  266. package/dist/stores/file/index.js +7 -11
  267. package/dist/stores/file/permission-rule-store.d.ts +23 -0
  268. package/dist/stores/file/permission-rule-store.js +75 -7
  269. package/dist/stores/file/session-store.js +2 -1
  270. package/dist/stores/file/tool-result-store.d.ts +14 -0
  271. package/dist/stores/file/tool-result-store.js +39 -2
  272. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  273. package/dist/stores/file/workflow-journal-store.js +17 -0
  274. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  275. package/dist/stores/file/workflow-run-store.js +15 -0
  276. package/dist/tools/fs/bash-program-position.js +3 -3
  277. package/dist/tools/fs/program-read-model.d.ts +34 -10
  278. package/dist/tools/fs/program-read-model.js +37 -7
  279. package/dist/tools/fs/program-read-model.rows.js +13 -2
  280. package/dist/tools/fs/read-deny.d.ts +28 -3
  281. package/dist/tools/fs/read-deny.js +18 -2
  282. package/dist/tools/fs/removal-targets.js +3 -3
  283. package/dist/tools/fs/safety.d.ts +2 -0
  284. package/dist/tools/fs/safety.js +1 -1
  285. package/dist/tools/fs/shell-read-argv.d.ts +8 -1
  286. package/dist/tools/fs/shell-read-argv.js +34 -29
  287. package/dist/tools/fs/shell-read-bindings.d.ts +2 -0
  288. package/dist/tools/fs/shell-read-bindings.js +5 -1
  289. package/dist/tools/fs/shell-read-brace.d.ts +18 -0
  290. package/dist/tools/fs/shell-read-brace.js +79 -0
  291. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  292. package/dist/tools/fs/shell-read-check.js +16 -14
  293. package/dist/tools/fs/shell-read-establish.js +23 -16
  294. package/dist/tools/fs/shell-read-judge.d.ts +11 -0
  295. package/dist/tools/fs/shell-read-judge.js +3 -3
  296. package/dist/tools/fs/shell-read-plan.d.ts +10 -0
  297. package/dist/tools/fs/shell-read-plan.js +189 -93
  298. package/dist/tools/fs/shell-read-start.d.ts +19 -9
  299. package/dist/tools/fs/shell-read-start.js +20 -12
  300. package/dist/tools/fs/shell-read-word.d.ts +10 -0
  301. package/dist/tools/fs/shell-read-word.js +9 -5
  302. package/dist/tools/fs/shell-read-workdir.d.ts +26 -7
  303. package/dist/tools/fs/shell-read-workdir.js +73 -12
  304. package/dist/tools/fs/shell-read-write-targets.js +13 -8
  305. package/dist/tools/worktree.d.ts +3 -2
  306. package/dist/tools/worktree.js +7 -35
  307. package/package.json +3 -2
  308. package/test/export-surface.snapshot.json +135 -11
  309. package/wire-changes/core-stores-sql@7.63.0.json +30 -0
  310. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  311. package/wire-changes/core@7.63.0.json +3523 -0
  312. package/wire-changes/core@7.64.0.json +2653 -0
  313. package/wire-changes/mods-kernel@7.63.0.json +30 -0
  314. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  315. package/wire-changes/primitives@7.63.0.json +445 -0
  316. package/wire-changes/primitives@7.64.0.json +30 -0
  317. package/dist/core/credential-vocabulary.d.ts +0 -176
  318. package/dist/core/credential-vocabulary.js +0 -190
  319. package/dist/core/redaction-passes.d.ts +0 -82
  320. package/dist/core/redaction-passes.js +0 -377
@@ -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;
@@ -343,7 +343,8 @@ export class FileSessionRepo {
343
343
  const id = options.id ?? uuidv7();
344
344
  const createdAt = new Date().toISOString();
345
345
  const path = this.pathFor(id);
346
- const meta = { id, createdAt, ...forkRowCells(await source.getMetadata(), options.owner) };
346
+ const placement = placementCellToWrite(options.placement, id, Date.now());
347
+ const meta = { id, createdAt, ...(placement !== undefined ? { placement } : {}), ...forkRowCells(await source.getMetadata(), options.owner) };
347
348
  const lines = [JSON.stringify({ kind: "meta", ...meta })];
348
349
  for (const entry of forked) {
349
350
  lines.push(JSON.stringify({ kind: "entry", entry }));
@@ -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,6 +1,6 @@
1
1
  import { SHELL_CONTROL_PREFIXES, argvOf, lexShellText } from "../../shell/lex.js";
2
2
  import { shellWordsOf } from "../../shell/shell-words.js";
3
- import { BLOCK_WORD_NAMES, LAUNCHER_NAMES, feedsArgvFromStdin, launcherOptionMovesBase, launcherOptionQueries, launcherOptionStep, launcherRunsShell, programRow, selectedOptions, streamDefaultProgram } from "./program-read-model.js";
3
+ import { BLOCK_WORD_NAMES, feedsArgvFromStdin, launcherOptionMovesBase, launcherOptionQueries, launcherOptionStep, launcherRunsShell, programRow, selectedOptions, streamDefaultProgram } from "./program-read-model.js";
4
4
  export const NOT_AUTO_ALLOWED = "— not auto-allowed";
5
5
  export function programBasename(word) {
6
6
  return word.includes("/") ? (word.split("/").pop() ?? word) : word;
@@ -106,7 +106,7 @@ export function readProgramPosition(words) {
106
106
  const owner = controlWords.length > 0 ? folded[controlWords[controlWords.length - 1]] : head;
107
107
  return none(written, assignments, optionShaped(owner, head));
108
108
  }
109
- if (!LAUNCHER_NAMES.has(basename)) {
109
+ if (launcherRowOf(basename) === undefined) {
110
110
  const glob = globProgramRefusal(i);
111
111
  if (glob !== undefined)
112
112
  return none(written, assignments, glob);
@@ -155,7 +155,7 @@ export function readProgramPosition(words) {
155
155
  ended.by = undefined;
156
156
  continue;
157
157
  }
158
- if (LAUNCHER_NAMES.has(wordBasename)) {
158
+ if (launcherRowOf(wordBasename) !== undefined) {
159
159
  launchers.push({ index: j, name: wordBasename });
160
160
  lastRow = launcherRowOf(wordBasename)?.launcher;
161
161
  if (launcherRunsShell(launcherRowOf(wordBasename), folded.slice(j + 1)))
@@ -2,7 +2,8 @@
2
2
  * The PROGRAM READ MODEL — one table that answers "what does this program do with its k-th word", and the readers
3
3
  * every shell face reads it through.
4
4
  *
5
- * A row is one program (the basename bash runs; a versioned spelling of an interpreter is its row), carrying every
5
+ * A row is one program (the basename bash runs; a spelling of its name the row declares — an interpreter's version, a GNU
6
+ * build's `g` — is its row), carrying every
6
7
  * argument fact the shell faces need: its option grammar (one per implementation where implementations disagree),
7
8
  * the ROLE each option value and each operand plays, whether a form walks a tree, how an interpreter receives the
8
9
  * program it runs, what a launcher steps over before the program it runs, which words a builtin keeps as shell text
@@ -305,6 +306,13 @@ export interface OperandSpec {
305
306
  readonly assignmentArguments?: "not-paths";
306
307
  /** The role of the LAST operand, unless an option delivered it ({@link OptionSpec.fillsLast}): a copy's destination. */
307
308
  readonly last?: ArgRole;
309
+ /** A LONE operand (no option delivering the last) is no destination: the program puts its copy / link in the working
310
+ * directory, under the operand's last segment (`ln -s dir/f` makes `./f`). Absent: a lone operand is the last. */
311
+ readonly loneOperand?: "into-working-directory";
312
+ /** Operands spelled `KEY=VALUE` (`dd if=… of=…`): the role of the VALUE of each key this table names — the operand is read
313
+ * in that role and its value is the path it names ({@link ArgEvent} `value`). An operand of a key the table does not name,
314
+ * or of no key, is an ordinary operand. */
315
+ readonly keyed?: Readonly<Record<string, ArgRole>>;
308
316
  /** What an ordinary operand becomes when an option selects editing in place ({@link OptionSpec.selects}). */
309
317
  readonly editedInPlace?: ArgRole;
310
318
  /** With fewer operands than this (the first-operand slot counted), the program reads its standard input; `always`:
@@ -400,10 +408,14 @@ export interface Subcommand {
400
408
  readonly operands?: OperandSpec;
401
409
  readonly traversal?: TraversalSpec;
402
410
  }
411
+ /** A spelling of a program's name, other than its row's key, that runs the row ({@link programRow}): `versioned` — the key with a
412
+ * trailing version (`python3`, `python3.11`); `gnu-prefixed` — the key behind a `g`, the name a GNU build is installed under
413
+ * beside the system's own implementation (`gln`, `gtimeout`), which runs the row's GNU grammar. */
414
+ export type ProgramSpelling = "versioned" | "gnu-prefixed";
403
415
  export interface ProgramRow {
404
416
  readonly key: string;
405
- /** A versioned spelling (`python3`, `python3.11`) is this row. */
406
- readonly versioned?: true;
417
+ /** The other spellings of the name that run this row ({@link ProgramSpelling}). */
418
+ readonly spellings?: readonly ProgramSpelling[];
407
419
  readonly grammars: readonly Grammar[];
408
420
  readonly operands?: OperandSpec;
409
421
  readonly traversal?: TraversalSpec;
@@ -437,12 +449,16 @@ export interface ProgramRow {
437
449
  readonly optionsComplete?: true;
438
450
  readonly witness: Witness;
439
451
  }
440
- /** The row bash runs for this basename: the exact key, or — for a row that declares versioned spellings — the name
441
- * with its trailing version dropped (`python3.11` is `python`). */
452
+ /** The row bash runs for this basename: the exact key, or a spelling of it the row declares ({@link ProgramRow.spellings}) —
453
+ * `python3.11` is `python`, `gln` is `ln` read by its GNU grammar. */
442
454
  export declare function programRow(name: string): ProgramRow | undefined;
455
+ /** The key of the row bash runs for this basename ({@link programRow}): what a table of programs is keyed by, so a spelling of
456
+ * a name (`gcp`) is the program it spells; the name itself where no row reads it. */
457
+ export declare function programKeyOf(name: string): string;
443
458
  /** Every row, in table order. */
444
459
  export declare function programRows(): readonly ProgramRow[];
445
- /** The launcher names — derived from the rows. */
460
+ /** The launcher rows' keys — derived from the rows (a name is read as a launcher by its row, {@link programRow}, spellings
461
+ * included). */
446
462
  export declare const LAUNCHER_NAMES: ReadonlySet<string>;
447
463
  /** The block words — derived from the rows. */
448
464
  export declare const BLOCK_WORD_NAMES: ReadonlySet<string>;
@@ -610,7 +626,8 @@ type Event<R> =
610
626
  readonly unsettled?: true;
611
627
  }
612
628
  /** An operand, the `ordinal`-th. `slot` = the first-operand slot's role when the slot applies; `role` = the role the
613
- * row declares for an operand at this position past the slot (a URL, a name it only examines); `dash` = the word is
629
+ * row declares for an operand at this position past the slot (a URL, a name it only examines), or for a `KEY=VALUE`
630
+ * operand by its key — whose `value` is then the text after the `=` ({@link OperandSpec.keyed}); `dash` = the word is
614
631
  * a lone `-`, read as standard input (`stdin`) or as a file name. */
615
632
  | {
616
633
  readonly kind: "operand";
@@ -618,6 +635,7 @@ type Event<R> =
618
635
  readonly ordinal: number;
619
636
  readonly slot?: ArgRole;
620
637
  readonly role?: ArgRole;
638
+ readonly value?: string;
621
639
  readonly dash?: "stdin" | "file";
622
640
  };
623
641
  export type ArgEvent = Event<ArgRole>;
@@ -757,8 +775,13 @@ export type WritingRole = Extract<ArgRole, {
757
775
  }>;
758
776
  /** Does this role write its path ({@link WRITING_EFFECTS})? */
759
777
  export declare function writesPath(role: ArgRole | undefined): role is WritingRole;
778
+ /** The programs whose OPERANDS the table says they write — a row whose ordinary or last operands take a writing role, a
779
+ * `KEY=VALUE` operand of a writing key (named by its key: `dd's of=`), an operand an in-place edit rewrites (`an in-place
780
+ * sed`) — in table order, as a sentence names them. The write face's refusal note reads it: the sentence names what the
781
+ * station judges by, never a list of its own. */
782
+ export declare function operandWriterNames(): readonly string[];
760
783
  /** One word an implementation's reading writes: its argv index, the value inside it when an option carries it
761
- * attached, and the role it is written by. */
784
+ * attached (or a `KEY=VALUE` operand after its key), and the role it is written by. */
762
785
  export interface WrittenWord {
763
786
  readonly at: number;
764
787
  readonly value?: string;
@@ -776,9 +799,10 @@ export interface WriteReading {
776
799
  readonly unexplained: boolean;
777
800
  /** The backup suffixes an option selecting edit-in-place was given (empty values dropped: no backup). */
778
801
  readonly suffixes: readonly string[];
779
- /** A copy's destination (argv index, and its value when an option carries it attached) and its sources. */
802
+ /** A copy's destination (argv index, and its value when an option carries it attached) and its sources; no destination:
803
+ * the working directory ({@link OperandSpec.loneOperand}). */
780
804
  readonly copy?: {
781
- readonly destination: {
805
+ readonly destination?: {
782
806
  readonly at: number;
783
807
  readonly value?: string;
784
808
  };
@@ -7,13 +7,24 @@ export const ARG_ROLE_KINDS = Object.freeze(["path", "mount-source", "object-pat
7
7
  export const PATH_EFFECTS = Object.freeze(["read", "names", "write", "create", "edit-in-place"]);
8
8
  export const WRITING_EFFECTS = new Set(["write", "create", "edit-in-place"]);
9
9
  const ROWS_BY_KEY = new Map(PROGRAM_ROWS.map((r) => [r.key, r]));
10
+ const SPELLING_FORMS = [
11
+ { form: "versioned", keyOf: (name) => name.replace(/\d+(?:\.\d+)*$/, ""), runs: (row) => row },
12
+ { form: "gnu-prefixed", keyOf: (name) => name.replace(/^g/, ""), runs: (row) => implementationsOf(row).find((view) => view.grammars[0]?.dialect === "gnu") ?? row },
13
+ ];
10
14
  export function programRow(name) {
11
15
  const exact = ROWS_BY_KEY.get(name);
12
16
  if (exact !== undefined)
13
17
  return exact;
14
- const stripped = name.replace(/\d+(?:\.\d+)*$/, "");
15
- const row = stripped === name ? undefined : ROWS_BY_KEY.get(stripped);
16
- return row?.versioned === true ? row : undefined;
18
+ for (const { form, keyOf, runs } of SPELLING_FORMS) {
19
+ const key = keyOf(name);
20
+ const row = key === name ? undefined : ROWS_BY_KEY.get(key);
21
+ if (row?.spellings?.includes(form) === true)
22
+ return runs(row);
23
+ }
24
+ return undefined;
25
+ }
26
+ export function programKeyOf(name) {
27
+ return programRow(name)?.key ?? name;
17
28
  }
18
29
  export function programRows() {
19
30
  return PROGRAM_ROWS;
@@ -510,12 +521,20 @@ function walkArgs(row, words, readOption, slot, readsRole, ownedValue) {
510
521
  }
511
522
  const inSlot = slot !== undefined && !slotSupplied && !sawOperand;
512
523
  sawOperand = true;
513
- const declared = inSlot ? undefined : slot !== undefined ? row?.operands?.positional?.[slotSupplied ? ordinal + 1 : ordinal] ?? row?.operands?.rest : row?.operands?.rest;
524
+ const keyed = inSlot ? undefined : keyedOperandOf(row, t);
525
+ const declared = keyed !== undefined ? keyed.role : inSlot ? undefined : slot !== undefined ? row?.operands?.positional?.[slotSupplied ? ordinal + 1 : ordinal] ?? row?.operands?.rest : row?.operands?.rest;
514
526
  const role = declared !== undefined && readsRole(declared) ? declared : undefined;
515
- out.push({ kind: "operand", at: k, ordinal: ordinal++, ...(inSlot ? { slot: slot.role } : {}), ...(role !== undefined ? { role } : {}), ...(t === "-" ? { dash: dashRead } : {}) });
527
+ out.push({ kind: "operand", at: k, ordinal: ordinal++, ...(inSlot ? { slot: slot.role } : {}), ...(role !== undefined ? { role, ...(keyed !== undefined ? { value: keyed.value } : {}) } : {}), ...(t === "-" ? { dash: dashRead } : {}) });
516
528
  }
517
529
  return out;
518
530
  }
531
+ function keyedOperandOf(row, word) {
532
+ const table = row?.operands?.keyed;
533
+ const eq = word.indexOf("=");
534
+ if (table === undefined || eq <= 0 || !Object.hasOwn(table, word.slice(0, eq)))
535
+ return undefined;
536
+ return { role: table[word.slice(0, eq)], value: word.slice(eq + 1) };
537
+ }
519
538
  export function readArgs(row, words, opts) {
520
539
  const slot = opts.firstOperandSlot === false ? undefined : firstOperandSlot(row);
521
540
  const owned = opts.ownedValues === true && row?.traversal?.discloses === "contents"
@@ -879,6 +898,15 @@ export function rowRefusesArgv(row, args) {
879
898
  export function writesPath(role) {
880
899
  return role?.kind === "path" && WRITING_EFFECTS.has(role.effect);
881
900
  }
901
+ export function operandWriterNames() {
902
+ const writes = (r) => writesPath(r.operands?.rest) || writesPath(r.operands?.last);
903
+ const keys = (r) => Object.entries(r.operands?.keyed ?? {}).flatMap(([k, role]) => (writesPath(role) ? [`${k}=`] : []));
904
+ return [
905
+ ...PROGRAM_ROWS.filter(writes).map((r) => r.key),
906
+ ...PROGRAM_ROWS.flatMap((r) => (keys(r).length > 0 ? [`${r.key}'s ${keys(r).join(" ")}`] : [])),
907
+ ...PROGRAM_ROWS.filter((r) => writesPath(r.operands?.editedInPlace)).map((r) => `an in-place ${r.key}`),
908
+ ];
909
+ }
882
910
  export function writeReadings(row, args) {
883
911
  return implementationsOf(row).map((view) => {
884
912
  const ops = view.operands;
@@ -906,7 +934,7 @@ export function writeReadings(row, args) {
906
934
  continue;
907
935
  const role = e.role ?? ordinary;
908
936
  if (writesPath(role))
909
- written.push({ at: e.at, role });
937
+ written.push({ at: e.at, ...(e.value !== undefined ? { value: e.value } : {}), role });
910
938
  }
911
939
  else if (e.kind === "dash-word-operand") {
912
940
  if (writesPath(ordinary))
@@ -918,7 +946,9 @@ export function writeReadings(row, args) {
918
946
  if (writesPath(last)) {
919
947
  const filled = scan.values.filter((v) => v.spec.fillsLast === true).at(-1);
920
948
  const destination = filled !== undefined ? { at: filled.at, ...(filled.value !== undefined ? { value: filled.value } : {}) } : scan.operands.length > 0 ? { at: scan.operands.at(-1) } : undefined;
921
- if (destination !== undefined) {
949
+ if (filled === undefined && scan.operands.length === 1 && ops?.loneOperand === "into-working-directory")
950
+ copy = { sources: scan.operands };
951
+ else if (destination !== undefined) {
922
952
  copy = { destination, sources: scan.operands.filter((at) => at !== destination.at) };
923
953
  for (let i = written.length - 1; i >= 0; i--)
924
954
  if (written[i].at === destination.at && written[i].value === destination.value)
@@ -35,6 +35,8 @@ const file = (language) => ({ kind: "program-file", language });
35
35
  const WALKS = { walks: true };
36
36
  const REBASES = { rebases: true };
37
37
  const SWITCH = { arity: 0 };
38
+ const SWITCH_NONE = { arity: 0, effect: "none" };
39
+ const SWITCH_WRITES = { arity: 0, effect: "writes" };
38
40
  const QUERY = { arity: 0, mode: "queries" };
39
41
  const val = (value, extra = {}) => ({ arity: 1, ...(value !== undefined ? { value } : {}), ...extra });
40
42
  const optional = (value) => ({ arity: "attached", ...(value !== undefined ? { value } : {}) });
@@ -312,7 +314,7 @@ function interpreterGrammar(language, g) {
312
314
  }
313
315
  const interpreter = (key, language, g, program, stdinWhenUnnamed, extra = {}, departures) => ({
314
316
  key,
315
- versioned: true,
317
+ spellings: ["versioned"],
316
318
  grammars: departures === undefined ? [interpreterGrammar(language, g)] : implementations(interpreterGrammar(language, g), departures.gnu, departures.bsd),
317
319
  ...(program === "none" ? {} : { operands: { positional: program === "file" ? [file(language)] : program === "text" ? [text(language)] : [undefined, text(language)] } }),
318
320
  delivery: { stdinWhenUnnamed },
@@ -656,6 +658,10 @@ const writerRows = [
656
658
  { key: "tee", grammars: [], operands: { rest: WRITE_THROUGH, dash: "file" }, witness: BINARY },
657
659
  { key: "cp", grammars: copyGrammars(true, COPY_DESTINATION), operands: { rest: COPY_SOURCE, last: COPY_DESTINATION, dash: "file" }, witness: BINARY },
658
660
  { key: "mv", grammars: copyGrammars(false, MOVE_DESTINATION), operands: { rest: MOVE_SOURCE, last: MOVE_DESTINATION, dash: "file" }, witness: BINARY },
661
+ { key: "truncate", grammars: implementations(grammar({ c: SWITCH_NONE, o: SWITCH_NONE, r: val(READ, { effect: "none" }), s: val(LABEL, { effect: "none" }) }, { "no-create": SWITCH_NONE, "io-blocks": SWITCH_NONE, reference: val(READ, { effect: "none" }), size: val(LABEL, { effect: "none" }), ...BANNERS }), { afterFirstOperand: "options" }, { lacks: ["-o", "--no-create", "--io-blocks", "--reference", "--size", "--help", "--version"], afterFirstOperand: "operands" }), operands: { rest: WRITE, dash: "file" }, witness: BINARY },
662
+ { key: "dd", grammars: implementations(grammar({}, { ...BANNERS }), {}, { lacks: ["--help", "--version"] }), operands: { keyed: { if: READ, of: WRITE_THROUGH } }, witness: BINARY },
663
+ { key: "install", grammars: implementations(grammar({ b: SWITCH_WRITES, c: SWITCH_NONE, C: SWITCH_NONE, d: SWITCH_WRITES, D: SWITCH_NONE, g: val(LABEL, { effect: "none" }), m: val(LABEL, { effect: "none" }), o: val(LABEL, { effect: "none" }), p: SWITCH_NONE, s: SWITCH, v: SWITCH_NONE, t: val(MOVE_DESTINATION, { fillsLast: true }), S: val(LABEL, { effect: "writes" }), T: SWITCH_NONE }, { backup: { arity: "attached", value: LABEL, effect: "writes" }, compare: SWITCH_NONE, directory: SWITCH_WRITES, group: val(LABEL, { effect: "none" }), mode: val(LABEL, { effect: "none" }), owner: val(LABEL, { effect: "none" }), "preserve-timestamps": SWITCH_NONE, strip: SWITCH, suffix: val(LABEL, { effect: "writes" }), "target-directory": val(MOVE_DESTINATION, { fillsLast: true }), "no-target-directory": SWITCH_NONE, verbose: SWITCH_NONE, ...BANNERS }), { afterFirstOperand: "options" }, { lacks: ["-t", "--backup", "--compare", "--directory", "--group", "--mode", "--owner", "--preserve-timestamps", "--strip", "--suffix", "--target-directory", "--no-target-directory", "--verbose", "--help", "--version"], reads: { "-S": SWITCH_NONE, "-T": val(LABEL, { effect: "none" }), "-D": val(LABEL, { effect: "none" }) }, afterFirstOperand: "operands" }), operands: { rest: READ, last: MOVE_DESTINATION, dash: "file" }, witness: BINARY },
664
+ { key: "ln", grammars: implementations(grammar({ b: SWITCH_WRITES, d: SWITCH_NONE, F: SWITCH, f: SWITCH_NONE, i: SWITCH_NONE, L: SWITCH_NONE, n: SWITCH_NONE, P: SWITCH_NONE, r: SWITCH_NONE, s: SWITCH_NONE, v: SWITCH_NONE, h: SWITCH_NONE, w: SWITCH_NONE, t: val(MOVE_DESTINATION, { fillsLast: true }), S: val(LABEL, { effect: "writes" }), T: SWITCH_NONE }, { backup: { arity: "attached", value: LABEL, effect: "writes" }, directory: SWITCH_NONE, force: SWITCH_NONE, interactive: SWITCH_NONE, logical: SWITCH_NONE, "no-dereference": SWITCH_NONE, physical: SWITCH_NONE, relative: SWITCH_NONE, symbolic: SWITCH_NONE, suffix: val(LABEL, { effect: "writes" }), "target-directory": val(MOVE_DESTINATION, { fillsLast: true }), "no-target-directory": SWITCH_NONE, verbose: SWITCH_NONE, ...BANNERS }), { lacks: ["-h", "-w"], afterFirstOperand: "options" }, { lacks: ["-b", "-d", "-r", "-t", "-S", "-T", "--backup", "--directory", "--force", "--interactive", "--logical", "--no-dereference", "--physical", "--relative", "--symbolic", "--suffix", "--target-directory", "--no-target-directory", "--verbose", "--help", "--version"], afterFirstOperand: "operands" }), operands: { rest: NAMES, last: MOVE_DESTINATION, loneOperand: "into-working-directory", dash: "file" }, witness: BINARY },
659
665
  ];
660
666
  const stdinReaders = [
661
667
  { key: "cat", grammars: [], operands: { stdinBelow: 1 }, witness: BINARY },
@@ -665,6 +671,11 @@ const stdinReaders = [
665
671
  const SYNTAX = { declared: "shell syntax, not a program: read by the lexer" };
666
672
  const block = (key, g = []) => ({ key, grammars: g, syntax: "block", witness: SYNTAX });
667
673
  const BLOCK_GRAMMARS = { "[[": [grammar({ v: val(BINDS_NAME) })] };
674
+ const GNU_COREUTILS = new Set([
675
+ "[", "basename", "cat", "chroot", "comm", "cp", "cut", "date", "dd", "dirname", "du", "echo", "env", "expr", "false", "groups", "head", "id", "install", "ln", "ls", "mkdir", "mv",
676
+ "nice", "nohup", "nproc", "printf", "pwd", "rm", "rmdir", "seq", "sleep", "stdbuf", "tail", "tee", "test", "timeout", "touch", "tr", "true", "truncate", "uname", "wc", "whoami",
677
+ ]);
678
+ const spelledByGnuBuilds = (row) => (GNU_COREUTILS.has(row.key) ? { ...row, spellings: [...(row.spellings ?? []), "gnu-prefixed"] } : row);
668
679
  export const PROGRAM_ROWS = [
669
680
  head, tail, cut, grepRow("grep"), grepRow("egrep"), grepRow("fgrep"), diff, cmp, sed, date, tar, find, curl,
670
681
  ls, namesWalker("du"), rg, namesWalker("tree"), ag, ack,
@@ -710,4 +721,4 @@ export const PROGRAM_ROWS = [
710
721
  shellRow("fc", "history", BUILTIN_ONLY, [grammar({ ...switches("nr"), s: { arity: 0, effect: "executes" }, ...switches("l", { mode: "banner" }), e: val(COMMAND, { executesWhenValue: "-" }) }, {}, { afterFirstOperand: "operands" })]),
711
722
  ...codeBodyRows,
712
723
  ...[...shellWordsOf("block")].map((k) => block(k, BLOCK_GRAMMARS[k])),
713
- ];
724
+ ].map(spelledByGnuBuilds);