@sema-agent/core 7.63.0 → 7.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/CHANGELOG.md +725 -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 +25 -5
  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/auto-promote.d.ts +3 -2
  30. package/dist/core/background-agent-store.d.ts +14 -0
  31. package/dist/core/background-agent-store.js +3 -0
  32. package/dist/core/checkpoint-queries.d.ts +9 -6
  33. package/dist/core/checkpoint-queries.js +8 -3
  34. package/dist/core/checkpoint-store.d.ts +7 -4
  35. package/dist/core/context-settings.d.ts +39 -9
  36. package/dist/core/context-settings.js +32 -10
  37. package/dist/core/engine-attestation.d.ts +26 -6
  38. package/dist/core/engine-attestation.js +5 -1
  39. package/dist/core/engine-notice.d.ts +37 -2
  40. package/dist/core/engine-notice.js +3 -1
  41. package/dist/core/extension-requester.d.ts +9 -0
  42. package/dist/core/extension-requester.js +7 -0
  43. package/dist/core/file-history-store.d.ts +30 -2
  44. package/dist/core/file-history-store.js +48 -9
  45. package/dist/core/fs-write-gate-policy.js +1 -1
  46. package/dist/core/gate-fold.js +5 -1
  47. package/dist/core/gate-lanes.js +2 -0
  48. package/dist/core/gate-outcome.d.ts +39 -2
  49. package/dist/core/gate-outcome.js +20 -1
  50. package/dist/core/governance-codes.d.ts +8 -4
  51. package/dist/core/governance-codes.js +8 -3
  52. package/dist/core/leg-identity.d.ts +35 -1
  53. package/dist/core/leg-identity.js +10 -0
  54. package/dist/core/mailbox-store.d.ts +39 -4
  55. package/dist/core/mailbox-store.js +14 -2
  56. package/dist/core/memory-engine/consolidation.d.ts +13 -6
  57. package/dist/core/memory-engine/consolidation.js +26 -0
  58. package/dist/core/memory-engine/control-objects.d.ts +58 -0
  59. package/dist/core/memory-engine/control-objects.js +273 -0
  60. package/dist/core/memory-engine/control-plane-adoption.d.ts +51 -0
  61. package/dist/core/memory-engine/control-plane-adoption.js +161 -0
  62. package/dist/core/memory-engine/delegation-settlement.d.ts +73 -40
  63. package/dist/core/memory-engine/delegation-settlement.js +271 -107
  64. package/dist/core/memory-engine/dual-root.d.ts +3 -2
  65. package/dist/core/memory-engine/dual-root.js +7 -3
  66. package/dist/core/memory-engine/engine.d.ts +54 -33
  67. package/dist/core/memory-engine/engine.js +150 -157
  68. package/dist/core/memory-engine/file-backend.d.ts +58 -76
  69. package/dist/core/memory-engine/file-backend.js +111 -268
  70. package/dist/core/memory-engine/index.d.ts +3 -2
  71. package/dist/core/memory-engine/index.js +2 -1
  72. package/dist/core/memory-engine/layout.d.ts +135 -50
  73. package/dist/core/memory-engine/layout.js +214 -89
  74. package/dist/core/memory-engine/memory-age.d.ts +12 -0
  75. package/dist/core/memory-engine/memory-age.js +17 -0
  76. package/dist/core/memory-engine/memory-backend-contract.d.ts +10 -3
  77. package/dist/core/memory-engine/memory-backend-contract.js +159 -2
  78. package/dist/core/memory-engine/memory-deployment.d.ts +12 -4
  79. package/dist/core/memory-engine/memory-deployment.js +31 -6
  80. package/dist/core/memory-engine/origin-clearance.d.ts +12 -3
  81. package/dist/core/memory-engine/origin-clearance.js +64 -9
  82. package/dist/core/memory-engine/session-write-home.d.ts +34 -1
  83. package/dist/core/memory-engine/session-write-home.js +37 -10
  84. package/dist/core/memory-engine/tools.d.ts +2 -2
  85. package/dist/core/memory-engine/tools.js +7 -7
  86. package/dist/core/memory-engine/types.d.ts +55 -12
  87. package/dist/core/memory-engine/types.js +2 -1
  88. package/dist/core/memory-vector.d.ts +6 -14
  89. package/dist/core/memory.d.ts +0 -462
  90. package/dist/core/memory.js +0 -333
  91. package/dist/core/mode-policy.js +3 -3
  92. package/dist/core/mods/agent-stations.d.ts +18 -0
  93. package/dist/core/mods/agent-stations.js +8 -6
  94. package/dist/core/mods/extension-call.d.ts +4 -0
  95. package/dist/core/mods/extension-call.js +8 -0
  96. package/dist/core/mods/tool-call.js +3 -4
  97. package/dist/core/parent-spec-seat.d.ts +2 -2
  98. package/dist/core/peer-channel.d.ts +5 -0
  99. package/dist/core/permission-rule-consent.d.ts +64 -22
  100. package/dist/core/permission-rule-consent.js +106 -58
  101. package/dist/core/permission-rule-store.d.ts +56 -21
  102. package/dist/core/permission-rule-store.js +2 -0
  103. package/dist/core/refusal-echo.d.ts +20 -0
  104. package/dist/core/refusal-echo.js +33 -0
  105. package/dist/core/retention.d.ts +175 -10
  106. package/dist/core/retention.js +44 -0
  107. package/dist/core/retired-keys.d.ts +5 -0
  108. package/dist/core/retired-keys.js +3 -0
  109. package/dist/core/rule-offer-read.d.ts +0 -4
  110. package/dist/core/rule-offer-read.js +2 -18
  111. package/dist/core/runner/classifier-ladder.d.ts +10 -2
  112. package/dist/core/runner/classifier-ladder.js +4 -2
  113. package/dist/core/runner/compact-session.js +10 -7
  114. package/dist/core/runner/compaction-call-options.d.ts +7 -7
  115. package/dist/core/runner/compaction-call-options.js +3 -2
  116. package/dist/core/runner/contracts.d.ts +28 -9
  117. package/dist/core/runner/delegation-owner.d.ts +2 -3
  118. package/dist/core/runner/delegation-owner.js +2 -1
  119. package/dist/core/runner/gate-exit.d.ts +6 -0
  120. package/dist/core/runner/gate-exit.js +11 -2
  121. package/dist/core/runner/memory-consolidation-driver.d.ts +4 -2
  122. package/dist/core/runner/memory-consolidation-driver.js +8 -5
  123. package/dist/core/runner/prepare-ask-lane.js +3 -3
  124. package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -1
  125. package/dist/core/runner/prepare-caps-and-workflow.js +2 -2
  126. package/dist/core/runner/prepare-config-doors.js +4 -0
  127. package/dist/core/runner/prepare-delegation-surface.d.ts +3 -0
  128. package/dist/core/runner/prepare-delegation-surface.js +2 -2
  129. package/dist/core/runner/prepare-gate-stations.d.ts +8 -0
  130. package/dist/core/runner/prepare-gate-stations.js +15 -7
  131. package/dist/core/runner/prepare-hands-readface.js +1 -1
  132. package/dist/core/runner/prepare-inherited-gate.d.ts +3 -1
  133. package/dist/core/runner/prepare-inherited-gate.js +4 -2
  134. package/dist/core/runner/prepare-memory-engine-session.js +1 -1
  135. package/dist/core/runner/prepare-memory.d.ts +4 -0
  136. package/dist/core/runner/prepare-memory.js +22 -28
  137. package/dist/core/runner/prepare-policy-chain.js +18 -10
  138. package/dist/core/runner/prepare-prompt-inputs.js +1 -1
  139. package/dist/core/runner/prepare-task.d.ts +5 -1
  140. package/dist/core/runner/prepare-task.js +16 -11
  141. package/dist/core/runner/prepare-wiring-manifest.d.ts +3 -1
  142. package/dist/core/runner/prepare-wiring-manifest.js +3 -2
  143. package/dist/core/runner/resume-admission.d.ts +2 -2
  144. package/dist/core/runner/resume-admission.js +2 -23
  145. package/dist/core/runner/role-resolution-table.d.ts +98 -0
  146. package/dist/core/runner/role-resolution-table.js +62 -0
  147. package/dist/core/runner/run-compaction-machinery.js +2 -2
  148. package/dist/core/runner/run-identity-wiring.js +12 -9
  149. package/dist/core/runner/run-leg.js +8 -4
  150. package/dist/core/runner/run-notification-lane.js +23 -23
  151. package/dist/core/runner/run-recovery-lanes.js +3 -3
  152. package/dist/core/runner/run-terminal-adoption.js +1 -1
  153. package/dist/core/runner/run-turn-boundary.js +14 -15
  154. package/dist/core/runner/runtask.js +1 -1
  155. package/dist/core/runner/sub-agent-deny-lists.d.ts +19 -0
  156. package/dist/core/runner/sub-agent-deny-lists.js +25 -0
  157. package/dist/core/runner/tool-occurrence.d.ts +4 -2
  158. package/dist/core/runner/tool-occurrence.js +2 -2
  159. package/dist/core/runner-deps.d.ts +1 -1
  160. package/dist/core/secret-env.d.ts +2 -2
  161. package/dist/core/secret-env.js +6 -20
  162. package/dist/core/session-checkout.d.ts +63 -3
  163. package/dist/core/session-checkout.js +152 -58
  164. package/dist/core/session-store.d.ts +6 -6
  165. package/dist/core/session-store.js +3 -3
  166. package/dist/core/shell-read-silence.js +8 -0
  167. package/dist/core/store-contracts/background-agent-store-contract.js +13 -0
  168. package/dist/core/store-contracts/peer-directory-contract.js +8 -1
  169. package/dist/core/task-event.d.ts +9 -5
  170. package/dist/core/task-notification.d.ts +137 -31
  171. package/dist/core/task-notification.js +198 -100
  172. package/dist/core/task-registry-agent.d.ts +11 -0
  173. package/dist/core/task-registry-agent.js +12 -3
  174. package/dist/core/task-registry-shared.d.ts +11 -0
  175. package/dist/core/task-registry.d.ts +18 -0
  176. package/dist/core/task-registry.js +27 -8
  177. package/dist/core/task-spec.d.ts +7 -2
  178. package/dist/core/tool-errors.d.ts +17 -9
  179. package/dist/core/tool-errors.js +1 -1
  180. package/dist/core/tool-policy.d.ts +18 -1
  181. package/dist/core/tool-policy.js +16 -7
  182. package/dist/core/tool-result-store.d.ts +20 -0
  183. package/dist/core/tool-spec.d.ts +10 -6
  184. package/dist/core/trace.d.ts +3 -2
  185. package/dist/core/workflow-journal-store.d.ts +11 -0
  186. package/dist/core/workflow-journal-store.js +7 -0
  187. package/dist/core/workflow-run-store.d.ts +9 -0
  188. package/dist/core/workflow-run-store.js +6 -0
  189. package/dist/core/write-protect.d.ts +16 -0
  190. package/dist/core/write-protect.js +10 -0
  191. package/dist/engine/compaction/compaction.d.ts +2 -1
  192. package/dist/engine/harness/types.d.ts +1 -0
  193. package/dist/engine/session/repo-utils.d.ts +14 -4
  194. package/dist/engine/session/repo-utils.js +5 -4
  195. package/dist/engine/session/session.d.ts +7 -1
  196. package/dist/engine/session/session.js +5 -2
  197. package/dist/index.d.ts +13 -11
  198. package/dist/index.js +13 -11
  199. package/dist/orchestration/run-workflow-tool.d.ts +4 -0
  200. package/dist/orchestration/run-workflow-tool.js +7 -0
  201. package/dist/orchestration/workflow-types.d.ts +2 -1
  202. package/dist/orchestration/workflow.d.ts +3 -0
  203. package/dist/orchestration/workflow.js +2 -1
  204. package/dist/prompts/default.d.ts +1 -2
  205. package/dist/scenarios/full-body.d.ts +1 -1
  206. package/dist/stores/file/adoption/adopt.d.ts +1 -1
  207. package/dist/stores/file/checkpoint-store.d.ts +6 -0
  208. package/dist/stores/file/checkpoint-store.js +4 -1
  209. package/dist/stores/file/file-history-store.d.ts +13 -0
  210. package/dist/stores/file/file-history-store.js +75 -13
  211. package/dist/stores/file/index.d.ts +12 -16
  212. package/dist/stores/file/index.js +7 -25
  213. package/dist/stores/file/permission-rule-store.d.ts +34 -0
  214. package/dist/stores/file/permission-rule-store.js +104 -9
  215. package/dist/stores/file/session-store.js +1 -1
  216. package/dist/stores/file/tool-result-store.d.ts +14 -0
  217. package/dist/stores/file/tool-result-store.js +39 -2
  218. package/dist/stores/file/workflow-journal-store.d.ts +4 -0
  219. package/dist/stores/file/workflow-journal-store.js +17 -0
  220. package/dist/stores/file/workflow-run-store.d.ts +3 -0
  221. package/dist/stores/file/workflow-run-store.js +15 -0
  222. package/dist/tools/fs/read-deny.d.ts +15 -2
  223. package/dist/tools/fs/read-deny.js +10 -2
  224. package/dist/tools/fs/shell-read-check.d.ts +8 -2
  225. package/dist/tools/fs/shell-read-check.js +7 -7
  226. package/package.json +2 -2
  227. package/test/export-surface.snapshot.json +71 -73
  228. package/wire-changes/core-stores-sql@7.64.0.json +30 -0
  229. package/wire-changes/core-stores-sql@7.65.0.json +30 -0
  230. package/wire-changes/core@7.64.0.json +2653 -0
  231. package/wire-changes/core@7.65.0.json +1650 -0
  232. package/wire-changes/mods-kernel@7.64.0.json +30 -0
  233. package/wire-changes/mods-kernel@7.65.0.json +30 -0
  234. package/wire-changes/primitives@7.64.0.json +30 -0
  235. package/wire-changes/primitives@7.65.0.json +337 -0
  236. package/dist/core/memory-recall.d.ts +0 -208
  237. package/dist/core/memory-recall.js +0 -136
  238. package/dist/stores/file/memory-store.d.ts +0 -124
  239. package/dist/stores/file/memory-store.js +0 -353
@@ -114,7 +114,7 @@ export interface RunnerDeps {
114
114
  models?: Record<string, Model>;
115
115
  /**
116
116
  * The deployment's per-model CONTEXT-WINDOW overlay, keyed by CATALOG WORD ({@link ContextSettings}):
117
- * `contextTokens` / `autoCompactTokens` / `enabled` over what the model card declares.
117
+ * `contextTokens` / `autoCompactTokens` over what the model card declares, `autoCompact` / `manualCompact` the task seats' twins.
118
118
  *
119
119
  * It is the ONE hot-swappable seat an IN-FLIGHT leg re-reads. Every other seat follows the snapshot law
120
120
  * (a running task keeps the deps object it prepared under) because those seats are the routing card —
@@ -23,8 +23,8 @@ import { type RedactionConfidence, type RedactionSource } from "@sema-agent/prim
23
23
  import { type EngineNotice } from "./engine-notice.js";
24
24
  /** Does a value carry a credential? A URL userinfo (after every `scheme://`, and a leading `//`) with a password or a
25
25
  * token-like user; a scheme-less `user:password@host`; a credential assignment; a webhook URL; a Sonar login; a
26
- * private-key header; an `Authorization` header, `token …`, `Bearer …` or `Basic …` with credential-shaped content.
27
- * Reads the first {@link VALUE_SCAN_LIMIT} code units. The value half of the judgment, exported apart from the env
26
+ * private-key header; an `Authorization` header, `token …`, `Bearer …` or `Basic …` with credential-shaped content (the
27
+ * value forms are the vocabulary's rows, {@link ENV_VALUES}). Reads the first {@link VALUE_SCAN_LIMIT} code units. The value half of the judgment, exported apart from the env
28
28
  * entry's exemptions ({@link isExemptEnvName}): a caller holding a value that is no environment variable asks this. */
29
29
  export declare function looksLikeCredentialValue(value: string): boolean;
30
30
  /** Which rule withheld an entry: one of the scrub's rules, or `own-credential` — the entry is one of the engine's own
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { types } from "node:util";
3
- import { CREDENTIAL_MIN_CHARS, envNameView, isSensitiveHeaderName, splitCamelCase } from "@sema-agent/primitives";
3
+ import { CREDENTIAL_MIN_CHARS, envNameView, envValueView, isSensitiveHeaderName, splitCamelCase } from "@sema-agent/primitives";
4
4
  import { DEFAULT_INHERITED_ENV_VARS } from "@modelcontextprotocol/client/stdio";
5
5
  import { deliverEngineNotice } from "./engine-notice.js";
6
6
  import { optionKeys, receiveMembers } from "./own-property-receipt.js";
@@ -10,6 +10,7 @@ function isExemptEnvName(name) {
10
10
  return GIT_CONFIG_ENV_RE.test(name) || PROXY_ENV_RE.test(name);
11
11
  }
12
12
  const ENV_NAMES = envNameView();
13
+ const ENV_VALUES = envValueView();
13
14
  const OTEL_ENV_RE = /^(?:INPUT_)?OTEL_/i;
14
15
  const SEMA_NAMESPACE_SECRET_RE = ENV_NAMES.anySegmentUnder("SEMA_");
15
16
  const BUNDLER_SETTINGS = ["BUILD", "LOCAL", "MIRROR", "PATH", "WITH", "WITHOUT", "CACHE", "DISABLE", "IGNORE", "ONLY"];
@@ -33,7 +34,7 @@ function nameIsCredentialShaped(name) {
33
34
  }
34
35
  const VALUE_SCAN_LIMIT = 8192;
35
36
  function looksLikeToken(user) {
36
- return ENV_NAMES.tokenPrefix.test(user) || (user.length >= 20 && /[0-9]/.test(user) && /[a-z]/i.test(user));
37
+ return ENV_VALUES.tokenHead.test(user) || (user.length >= 20 && /[0-9]/.test(user) && /[a-z]/i.test(user));
37
38
  }
38
39
  const HOST_RE = /^(?:localhost|[a-z0-9_-]+(?:\.[a-z0-9_-]+)*\.(?=[a-z0-9-]*[a-z])[a-z0-9-]+|[a-z0-9_.-]+(?=:\d+(?:[/?#]|$))|\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i;
39
40
  const HOSTLIKE_RE = /^(?:(?=[a-z0-9._-]*[a-z])[a-z0-9._-]+|\d{1,3}(?:\.\d{1,3}){3}|\[[0-9a-f:.]+\])(?::\d+)?(?:[/?#]|$)/i;
@@ -69,14 +70,6 @@ function carriesSchemelessUserinfo(text) {
69
70
  const at = text.lastIndexOf("@", text.search(/\s|$/));
70
71
  return !isHostPortPathBeforeAt(text.slice(0, at), text.slice(at + 1)) && !/^(?:mailto|sips?|xmpp|im|acct):/i.test(text);
71
72
  }
72
- const FLAG_WORDS = ["true", "false", "none", "null", "yes", "no", "on", "off", "enabled", "disabled", "required", "optional"];
73
- const CREDENTIAL_ASSIGNMENT_RE = new RegExp(String.raw `(?:(?:^|[;&?#,{]|\/:)\s*|\s)["']?(?!-*jobserver-auth\s*[=:])(?:[a-z0-9_.-]{0,64}(?:password|passwd|pwd|secret|token|(?:account|access|api|private|subscription)[-_]?key|signature|sig|credential)|[a-z0-9_.-]{0,63}[_.-]auth)["']?\s*[=:]\s*["']?(?!(?:${FLAG_WORDS.join("|")})(?:$|[;&,\s"']))[^;&,\s"']+`, "i");
74
- const WEBHOOK_URL_RE = /https:\/\/(?:hooks\.slack\.com\/(?:services|workflows|triggers)\/|(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/|[\w.-]+\.webhook\.office\.com\/webhookb2\/)[\w\/@.~-]{16,}/i;
75
- const SONAR_LOGIN_RE = new RegExp(String.raw `["']?sonar\.login["']?\s*[:=]\s*["']?[^\s"',}]{${CREDENTIAL_MIN_CHARS},}`);
76
- const PRIVATE_KEY_HEADER_RE = /-----BEGIN [A-Z ]*PRIVATE KEY(?: BLOCK)?-----/;
77
- const AUTHORIZATION_HEADER_RE = new RegExp(String.raw `\bauthorization\s*[:=]\s*["']?[a-z][a-z0-9_-]*\s+[A-Za-z0-9._~+\/=-]{${CREDENTIAL_MIN_CHARS},}`, "i");
78
- const TOKEN_WORD_RE = /\b(?:[Tt]oken|TOKEN)\s+(?=[A-Za-z0-9_~+=-]*[0-9])(?=[A-Za-z0-9_~+=-]*[A-Z])(?=([A-Za-z0-9_~+=-]{20,}))\1(?![\/.])/;
79
- const BEARER_BASIC_RE = new RegExp(String.raw `\b(?:Bearer|Basic)\s+(?=[A-Za-z._~+\/=-]*[0-9]|(?:[A-Za-z0-9._~+\/=-]*?[a-z][A-Z](?![a-z])){2}|[A-Za-z0-9.-]*[_~+\/=])[A-Za-z0-9._~+\/=-]{${CREDENTIAL_MIN_CHARS},}`);
80
73
  export function looksLikeCredentialValue(value) {
81
74
  const text = value.length > VALUE_SCAN_LIMIT ? value.slice(0, VALUE_SCAN_LIMIT) : value;
82
75
  for (let at = text.indexOf("://"); at !== -1; at = text.indexOf("://", at + 3)) {
@@ -85,14 +78,7 @@ export function looksLikeCredentialValue(value) {
85
78
  }
86
79
  if (text.startsWith("//") && authorityCarriesCredential(text.slice(2)))
87
80
  return true;
88
- return (carriesSchemelessUserinfo(text) ||
89
- CREDENTIAL_ASSIGNMENT_RE.test(text) ||
90
- WEBHOOK_URL_RE.test(text) ||
91
- SONAR_LOGIN_RE.test(text) ||
92
- PRIVATE_KEY_HEADER_RE.test(text) ||
93
- AUTHORIZATION_HEADER_RE.test(text) ||
94
- TOKEN_WORD_RE.test(text) ||
95
- BEARER_BASIC_RE.test(text));
81
+ return carriesSchemelessUserinfo(text) || ENV_VALUES.forms.some((form) => form.re.test(text));
96
82
  }
97
83
  const OWN_CREDENTIAL = "the engine's own service credential";
98
84
  const SECRET_ENV_KIND_CONFIDENCE = {
@@ -197,7 +183,7 @@ function runtimeSuppliedHolderOf(value) {
197
183
  const supplied = policyArm([...runtimeSuppliedEnv()]);
198
184
  return Object.keys(supplied).find((k) => supplied[k] === value);
199
185
  }
200
- const PLACEHOLDER_KEY_WORDS = new Set([...FLAG_WORDS, "undefined", "placeholder", "lm-studio", "not-needed", "sk-no-key-required"]);
186
+ const PLACEHOLDER_KEY_WORDS = new Set([...ENV_VALUES.flagWords, "undefined", "placeholder", "lm-studio", "not-needed", "sk-no-key-required"]);
201
187
  const ONE_REPEATED_CHARACTER_RE = /^(\S)\1{2,}$/u;
202
188
  export function isBlankCredential(value) {
203
189
  return value.trim() === "";
@@ -210,7 +196,7 @@ function notACredentialReason(value) {
210
196
  return `a string of fewer than ${CREDENTIAL_MIN_CHARS} characters, which names no secret`;
211
197
  if (PLACEHOLDER_KEY_WORDS.has(text.toLowerCase()))
212
198
  return "a flag or placeholder word, which names no secret";
213
- if (ONE_REPEATED_CHARACTER_RE.test(text.replace(ENV_NAMES.tokenPrefix, "")))
199
+ if (ONE_REPEATED_CHARACTER_RE.test(text.replace(ENV_VALUES.tokenHead, "")))
214
200
  return "one character repeated, which names no secret";
215
201
  return undefined;
216
202
  }
@@ -84,8 +84,9 @@ export interface OpenedSessionCheckout {
84
84
  /**
85
85
  * THE per-leg judge of a session's checkout (see the module header): reads the record, compares the leg's declaration with it,
86
86
  * mints the allocation on the session's first leg, and answers the leg's task root. Throws a coded refusal; the first leg's
87
- * allocation is all or nothing (every check runs before the mint, a tree minted for a refused allocation is removed while it is
88
- * still clean, and the record is written only once everything succeeded — immediately, not at settle).
87
+ * allocation records nothing unless everything succeeded (every path check runs before the mint; a tree minted for a refused
88
+ * allocation is removed while still clean only when its allocation mark is proved absent, else kept and named; the record is
89
+ * written only once everything succeeded — immediately, not at settle).
89
90
  */
90
91
  export declare function openSessionCheckout(input: OpenSessionCheckoutInput): Promise<OpenedSessionCheckout>;
91
92
  /**
@@ -97,12 +98,71 @@ export declare function openSessionCheckout(input: OpenSessionCheckoutInput): Pr
97
98
  * again re-reports and never removes a tree another allocation took over.
98
99
  *
99
100
  * `onExit`: `"keep-if-dirty"` (default) | `"keep"` (keep every tree; only record the release). A discarding removal is not
100
- * offered. A session with no checkout answers an empty list.
101
+ * offered. A session with no checkout answers an empty list; a tree its first leg kept because the record could not be written
102
+ * is no record's to release — {@link listOrphanSessionTrees} lists it.
101
103
  */
102
104
  export declare function releaseSessionCheckout(env: ExecutionEnv, session: Session, opts?: {
103
105
  readonly onExit?: "keep-if-dirty" | "keep";
104
106
  }): Promise<{
105
107
  readonly trees: readonly ReleasedTree[];
106
108
  }>;
109
+ /** Why a session tree whose allocation mark reads is no record's ({@link OrphanSessionTree.why}). */
110
+ export type OrphanSessionTreeWhy = "unrecorded" | "record_unreadable" | "record_elsewhere";
111
+ /** A session tree no record holds — what {@link listOrphanSessionTrees} lists. */
112
+ export interface OrphanSessionTree {
113
+ /** `<repository root>/.sema/worktrees/<name>`, the list's spelling — the path {@link releaseOrphanSessionTree} takes. */
114
+ readonly path: string;
115
+ /** The tree's branch (`sema/<name>`), present while it exists. */
116
+ readonly branch?: string;
117
+ /** The session its allocation mark names. */
118
+ readonly sessionId: string;
119
+ /** The allocation its mark names. */
120
+ readonly allocationId: string;
121
+ /** The commit it was minted at (its mark). */
122
+ readonly baseSha: string;
123
+ /** `unrecorded`: the host's lookup says that session does not exist, or its log holds no checkout record · `record_unreadable`:
124
+ * the lookup threw, the session's record cannot be read, or its log is loaded from a bounded window that may hold the record
125
+ * below its floor · `record_elsewhere`: the session's record holds another allocation (a first leg refused while another leg
126
+ * recorded kept the tree it minted). */
127
+ readonly why: OrphanSessionTreeWhy;
128
+ /** `record_unreadable`: why; `record_elsewhere`: the allocation the record holds. */
129
+ readonly detail?: string;
130
+ /** The tree directory's modification time (ms since the epoch): a hint for a host's retention policy, not liveness. */
131
+ readonly modifiedAt: number;
132
+ }
133
+ /**
134
+ * The host's lookup of a session by id, handed to the orphan doors.
135
+ *
136
+ * @contract session_checkout.session_of.absence_is_authority — `undefined` asserts that the host's DURABLE session store holds no
137
+ * session with that id (a cache miss is not absence), and the lookup throws whenever it cannot tell. The doors read `undefined` as
138
+ * "no leg of that session will take the tree back" (the host never reuses a session id) and a throw as `record_unreadable`, which
139
+ * neither door removes.
140
+ */
141
+ export type OrphanSessionLookup = (sessionId: string) => Promise<Session | undefined>;
142
+ /**
143
+ * List the session trees under the repository at `root` that no record holds: each managed tree whose allocation mark reads and
144
+ * whose session ({@link OrphanSessionLookup}) holds no record of that allocation — the tree a first leg kept when its record could
145
+ * not be written, or one whose session the host deleted without releasing it. Reads only. A tree its session's record holds is
146
+ * not listed ({@link releaseSessionCheckout} is its door), nor a directory with no readable mark (no session tree, or one neither
147
+ * door touches). Answers `{ repository, trees }`; a repository with no managed parent answers no trees.
148
+ */
149
+ export declare function listOrphanSessionTrees(env: ExecutionEnv, root: string, opts: {
150
+ readonly sessionOf: OrphanSessionLookup;
151
+ }): Promise<{
152
+ readonly repository: string;
153
+ readonly trees: readonly OrphanSessionTree[];
154
+ }>;
155
+ /**
156
+ * Release one orphan session tree — the host's door for a tree no record holds (as {@link listOrphanSessionTrees} lists it).
157
+ * The tree is judged again: a tree a session's record holds now answers `kept: "not_owned"` (release that session's checkout
158
+ * instead), one whose record cannot be read `kept: "unverifiable"`, one with no allocation mark `not_owned`; an orphan is then
159
+ * removed by the same judgment as {@link releaseSessionCheckout} (clean, no commit past its base, the mark read again right
160
+ * before the removal, no `--force`; the branch only while it sits at the base commit). Removes nothing on its own initiative,
161
+ * appends to no session. The host runs the removals of one repository one at a time — this door's, the release's, a deleted
162
+ * session's cascade (a removal and a mint of the same name between two of them is the known window, KNOWN-LIMITS KL-3462-a).
163
+ */
164
+ export declare function releaseOrphanSessionTree(env: ExecutionEnv, path: string, opts: {
165
+ readonly sessionOf: OrphanSessionLookup;
166
+ }): Promise<ReleasedTree>;
107
167
  /** The frame's `session` member: the record's cells as the leg reports them (`undefined` when the session has no checkout). */
108
168
  export declare function sessionFrameOf(record: SessionCheckoutRecord | undefined): ReadonlyArray<SessionCheckoutCell> | undefined;
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { appendSessionCheckout, readSessionCheckout } from "../engine/session/session.js";
3
3
  import { isSensitiveRecordKey } from "@sema-agent/primitives";
4
- import { managedAnchorOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
4
+ import { managedAnchorOf, managedWorktreeBaseOf, managedWorktreeBranchOf, managedWorktreeDir, mintManagedWorktree, removeManagedWorktree, repositoryRootOf, resolveBaseCommit, shq, symlinkedLevel, WORKTREE_PARENT, worktreeNameProblem, } from "./git-worktree-env.js";
5
5
  import { strayMembersOf } from "./own-property-receipt.js";
6
6
  import { thrownText } from "./thrown-value.js";
7
7
  export const WORKTREE_INCAPABLE_REASONS = Object.freeze([
@@ -178,23 +178,31 @@ async function birthRecordPath(env, dir) {
178
178
  const gitDir = await run(env, "git rev-parse --absolute-git-dir", dir);
179
179
  return gitDir !== undefined && gitDir.exitCode === 0 && gitDir.stdout.trim().startsWith("/") ? `${gitDir.stdout.trim()}/sema-allocation` : undefined;
180
180
  }
181
- async function readBirthRecord(env, dir) {
181
+ async function readBirthMark(env, dir) {
182
+ const unreadable = (detail) => ({ kind: "unreadable", detail });
183
+ const own = await env.canonicalPath(dir);
184
+ const top = await checkoutTopOf(env, dir);
185
+ if (!own.ok || top === undefined)
186
+ return unreadable(`git cannot say which checkout ${dir} is`);
187
+ if (top !== own.value)
188
+ return { kind: "absent" };
182
189
  const at = await birthRecordPath(env, dir);
183
190
  if (at === undefined)
184
- return undefined;
191
+ return unreadable(`git does not name the private directory of ${dir}`);
185
192
  const text = await env.readTextFile(at);
186
193
  if (!text.ok)
187
- return undefined;
194
+ return text.error.code === "not_found" ? { kind: "absent" } : unreadable(`its allocation mark cannot be read (${thrownText(text.error).slice(0, 200)})`);
188
195
  try {
189
196
  const v = JSON.parse(text.value);
190
- return typeof v.allocationId === "string" && typeof v.sessionId === "string" && typeof v.baseSha === "string" && FULL_SHA.test(v.baseSha) && typeof v.declared === "string"
191
- ? { allocationId: v.allocationId, sessionId: v.sessionId, baseSha: v.baseSha, declared: v.declared }
192
- : undefined;
197
+ if (typeof v.allocationId === "string" && typeof v.sessionId === "string" && typeof v.baseSha === "string" && FULL_SHA.test(v.baseSha) && typeof v.declared === "string") {
198
+ return { kind: "marked", mark: { allocationId: v.allocationId, sessionId: v.sessionId, baseSha: v.baseSha, declared: v.declared } };
199
+ }
193
200
  }
194
201
  catch {
195
- return undefined;
196
202
  }
203
+ return unreadable("its allocation mark is not a valid record");
197
204
  }
205
+ const recordHoldsMark = (holder, mark) => holder.allocationId === mark.allocationId;
198
206
  const overlaps = (path, top) => path === top || path.startsWith(`${top}/`) || top.startsWith(`${path === "/" ? "" : path}/`);
199
207
  async function refuseOverlap(env, base, additional) {
200
208
  const top = await canonicalOf(env, base);
@@ -261,8 +269,8 @@ async function reopen(input, declared, record) {
261
269
  }
262
270
  if (info.value.kind !== "directory")
263
271
  throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer a directory; the leg was not started.`);
264
- const birth = await readBirthRecord(env, cell.dir);
265
- if (birth === undefined || birth.allocationId !== record.allocationId) {
272
+ const birth = await readBirthMark(env, cell.dir);
273
+ if (birth.kind !== "marked" || !recordHoldsMark(record, birth.mark)) {
266
274
  throw refusal("workspace.checkout_missing", `This session's tree ${cell.dir} is no longer the tree this session minted (its allocation mark is missing or names another allocation); the leg was not started. Release the session's checkout and start a new session.`);
267
275
  }
268
276
  if (cell.root === "taskRoot") {
@@ -320,12 +328,16 @@ async function allocate(input, declared, observedLeaf) {
320
328
  }
321
329
  isolatedRepository = probe.gitRoot;
322
330
  const dir = managedWorktreeDir(isolatedRepository, name);
331
+ const placed = await placeInTree(env, baseRoot, dir);
332
+ if (placed === undefined)
333
+ throw refusal("workspace.isolation_unavailable", `The task root ${baseRoot} has no place in the session's tree ${dir}.`);
323
334
  let tree;
324
335
  const existing = await env.fileInfo(dir);
325
336
  if (existing.ok || existing.error.code !== "not_found") {
326
- const birth = await readBirthRecord(env, dir);
337
+ const read = await readBirthMark(env, dir);
338
+ const birth = read.kind === "marked" ? read.mark : undefined;
327
339
  if (birth === undefined || birth.sessionId !== sessionId) {
328
- throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name.`);
340
+ throw refusal("workspace.isolation_unavailable", `The session's tree cannot be made: a tree named "${name}" already exists at ${dir} and was not minted by this session (name_in_use). Declare another name — or, when no session's record holds that tree, release it with releaseOrphanSessionTree (listOrphanSessionTrees lists such trees).`);
329
341
  }
330
342
  if (birth.declared !== declaredDigest(declared)) {
331
343
  const atOtherCommit = taskRootSource !== undefined && birth.baseSha !== taskRootSource.sha;
@@ -356,6 +368,9 @@ async function allocate(input, declared, observedLeaf) {
356
368
  throw refusal(taskRootSource !== undefined ? "workspace.source_mismatch" : "workspace.isolation_unavailable", `The session's tree cannot be made${taskRootSource !== undefined ? ` at the declared commit ${taskRootSource.sha}` : ""}: ${why.slice(0, 600)}`);
357
369
  }
358
370
  const undo = async (why, code) => {
371
+ const mark = await readBirthMark(env, minted.worktreeDir);
372
+ if (mark.kind !== "absent")
373
+ throw refusal(code, `${why} The tree is kept at ${minted.worktreeDir} (its allocation mark ${mark.kind === "marked" ? "was written" : "cannot be read"}); a tree no record holds is listed by listOrphanSessionTrees.`);
359
374
  const removed = await removeManagedWorktree(env, minted.anchor, minted.worktreeDir, minted.baseSha !== undefined ? { name: minted.branch, baseSha: minted.baseSha } : undefined, undefined, "clean");
360
375
  throw refusal(code, `${why}${removed.ok ? "" : ` The tree minted for it was left at ${minted.worktreeDir} (${removed.detail.trim().slice(0, 200)}).`}`);
361
376
  };
@@ -366,7 +381,7 @@ async function allocate(input, declared, observedLeaf) {
366
381
  const wrote = birthAt === undefined ? undefined : await env.writeFile(birthAt, JSON.stringify({ allocationId, sessionId, baseSha: minted.baseSha, declared: declaredDigest(declared) }));
367
382
  if (wrote === undefined || !wrote.ok)
368
383
  return undo("The session's tree could not be marked as this session's; the leg was not started.", "workspace.isolation_unavailable");
369
- tree = { dir: minted.worktreeDir, branch: minted.branch, baseSha: minted.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId, undo };
384
+ tree = { dir: minted.worktreeDir, branch: minted.branch, baseSha: minted.baseSha, baseRef: taskRootSource !== undefined ? "source" : declared.baseRef ?? "fresh", allocationId };
370
385
  }
371
386
  checkouts.push({
372
387
  repository: isolatedRepository,
@@ -378,38 +393,23 @@ async function allocate(input, declared, observedLeaf) {
378
393
  baseRef: tree.baseRef,
379
394
  ...(taskRootSource !== undefined ? { source: { remote: taskRootSource.remote, sha: taskRootSource.sha, ...(taskRootSource.ref !== undefined ? { ref: taskRootSource.ref } : {}) } } : {}),
380
395
  });
381
- const placed = await placeInTree(env, baseRoot, tree.dir);
382
- if (placed === undefined) {
383
- const why = `The task root ${baseRoot} has no place in the session's tree ${tree.dir}.`;
384
- if (tree.undo !== undefined)
385
- return tree.undo(why, "workspace.isolation_unavailable");
386
- throw refusal("workspace.isolation_unavailable", why);
387
- }
388
- taskRoot = placed;
396
+ taskRoot = `${tree.dir}${placed.slice(dir.length)}`;
389
397
  const record = { allocationId: tree.allocationId, sessionId, declared, checkouts: [...checkouts, ...sourceCells] };
390
- return { taskRoot, record: await recordNow(input.session, record, observedLeaf, tree.undo) };
398
+ return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
391
399
  }
392
400
  const record = { allocationId, sessionId, declared, checkouts: sourceCells };
393
401
  return { taskRoot, record: await recordNow(input.session, record, observedLeaf) };
394
402
  }
395
- async function recordNow(session, record, observedLeaf, undo) {
403
+ async function recordNow(session, record, observedLeaf) {
396
404
  try {
397
405
  await appendSessionCheckout(session, record, observedLeaf);
398
406
  }
399
407
  catch (err) {
400
- const why = `This session's checkout could not be recorded (${thrownText(err).slice(0, 300)}); the leg was not started.`;
401
- const back = await readSessionCheckout(session, record.sessionId).catch((e) => ({ kind: "unreadable", detail: thrownText(e) }));
402
408
  const dirs = record.checkouts.flatMap((cell) => (cell.dir === undefined ? [] : [cell.dir]));
403
- const named = back.kind === "record" ? back.record : undefined;
404
- const holds = named !== undefined && (named.allocationId === record.allocationId || named.checkouts.some((cell) => cell.dir !== undefined && dirs.includes(cell.dir)));
405
- if (undo !== undefined && back.kind !== "unreadable" && !holds)
406
- return undo(why, "workspace.checkout_unavailable");
407
- const note = back.kind === "unreadable"
408
- ? ` The allocation record could not be read back${dirs.length > 0 ? `; the tree is kept at ${dirs.join(", ")}` : ""} (${back.detail.slice(0, 200)}).`
409
- : named !== undefined && holds && named.allocationId !== record.allocationId
410
- ? ` Another record names this tree; the tree is kept at ${dirs.join(", ")}.`
411
- : "";
412
- throw refusal("workspace.checkout_unavailable", `${why}${note}`);
409
+ const kept = dirs.length === 0
410
+ ? ""
411
+ : ` The tree is kept at ${dirs.join(", ")}. If the record was written, the next leg reopens it and releaseSessionCheckout releases it; if not, the next leg of this session with the same declaration takes it back; a tree no record holds is listed by listOrphanSessionTrees.`;
412
+ throw refusal("workspace.checkout_unavailable", `This session's checkout could not be recorded (${thrownText(err).slice(0, 300)}); the leg was not started.${kept}`);
413
413
  }
414
414
  return record;
415
415
  }
@@ -429,7 +429,7 @@ export async function releaseSessionCheckout(env, session, opts) {
429
429
  for (const cell of record.checkouts) {
430
430
  if (cell.dir === undefined || cell.branch === undefined)
431
431
  continue;
432
- trees.push(await releaseTree(env, record, cell, onExit));
432
+ trees.push(await releaseTree(env, { path: cell.dir, repository: cell.repository, branch: cell.branch, baseSha: cell.baseSha }, record, onExit));
433
433
  }
434
434
  if (record.released !== true)
435
435
  await appendSessionCheckout(session, { ...record, released: true });
@@ -441,42 +441,136 @@ function ignoredDetail(paths) {
441
441
  const more = paths.length > IGNORED_NAMED ? ` and ${paths.length - IGNORED_NAMED} more` : "";
442
442
  return `the tree holds files git ignores (${named}${more}), which removing it would delete — delete or move them, then release again`;
443
443
  }
444
- async function releaseTree(env, record, cell, onExit) {
445
- const path = cell.dir;
446
- const branchLeft = async () => {
447
- const ref = await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${cell.branch}`)}`, cell.repository);
448
- return ref !== undefined && ref.exitCode === 0 ? { branch: cell.branch } : {};
449
- };
444
+ async function branchLeftOf(env, tree) {
445
+ const ref = await run(env, `git rev-parse --verify --quiet ${shq(`refs/heads/${tree.branch}`)}`, tree.repository);
446
+ return ref !== undefined && ref.exitCode === 0 ? { branch: tree.branch } : {};
447
+ }
448
+ async function goneTree(env, tree) {
449
+ await run(env, "git worktree prune", tree.repository);
450
+ return { path: tree.path, removed: true, ...(await branchLeftOf(env, tree)) };
451
+ }
452
+ async function releaseTree(env, tree, holder, onExit) {
453
+ const { path, repository, branch, baseSha } = tree;
450
454
  const at = await env.fileInfo(path);
451
455
  if (!at.ok) {
452
456
  if (at.error.code !== "not_found")
453
- return { path, removed: false, kept: "unverifiable", branch: cell.branch, detail: thrownText(at.error).slice(0, 300) };
454
- await run(env, "git worktree prune", cell.repository);
455
- return { path, removed: true, ...(await branchLeft()) };
457
+ return { path, removed: false, kept: "unverifiable", branch, detail: thrownText(at.error).slice(0, 300) };
458
+ return goneTree(env, tree);
456
459
  }
457
- const birth = await readBirthRecord(env, path);
458
- if (birth === undefined || birth.allocationId !== record.allocationId)
459
- return { path, removed: false, kept: "not_owned", ...(await branchLeft()) };
460
+ const held = async () => {
461
+ const mark = await readBirthMark(env, path);
462
+ return mark.kind === "marked" && recordHoldsMark(holder, mark.mark);
463
+ };
464
+ if (!(await held()))
465
+ return { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, tree)) };
460
466
  if (onExit === "keep")
461
- return { path, removed: false, kept: "requested", branch: cell.branch };
467
+ return { path, removed: false, kept: "requested", branch };
462
468
  const status = await run(env, "git status --porcelain --ignored --untracked-files=normal", path);
463
469
  if (status === undefined || status.exitCode !== 0)
464
- return { path, removed: false, kept: "unverifiable", branch: cell.branch };
470
+ return { path, removed: false, kept: "unverifiable", branch };
465
471
  const entries = status.stdout.split("\n").filter((line) => line !== "");
466
472
  if (entries.some((line) => !line.startsWith("!! ")))
467
- return { path, removed: false, kept: "dirty", branch: cell.branch };
473
+ return { path, removed: false, kept: "dirty", branch };
468
474
  if (entries.length > 0)
469
- return { path, removed: false, kept: "ignored", branch: cell.branch, detail: ignoredDetail(entries.map((line) => line.slice(3))) };
470
- const ahead = await run(env, `git rev-list --count ${shq(`${cell.baseSha}..HEAD`)}`, path);
475
+ return { path, removed: false, kept: "ignored", branch, detail: ignoredDetail(entries.map((line) => line.slice(3))) };
476
+ const ahead = await run(env, `git rev-list --count ${shq(`${baseSha}..HEAD`)}`, path);
471
477
  const commits = ahead !== undefined && ahead.exitCode === 0 ? Number.parseInt(ahead.stdout.trim(), 10) : Number.NaN;
472
478
  if (!Number.isFinite(commits))
473
- return { path, removed: false, kept: "unverifiable", branch: cell.branch };
479
+ return { path, removed: false, kept: "unverifiable", branch };
474
480
  if (commits > 0)
475
- return { path, removed: false, kept: "commits", branch: cell.branch };
476
- const removed = await removeManagedWorktree(env, cell.repository, path, { name: cell.branch, baseSha: cell.baseSha }, undefined, "clean");
481
+ return { path, removed: false, kept: "commits", branch };
482
+ if (!(await held()))
483
+ return { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, tree)) };
484
+ const removed = await removeManagedWorktree(env, repository, path, { name: branch, baseSha }, undefined, "clean");
477
485
  if (!removed.ok)
478
- return { path, removed: false, kept: "unverifiable", branch: cell.branch, detail: removed.detail.trim().slice(0, 300) };
479
- return { path, removed: true, ...(await branchLeft()) };
486
+ return { path, removed: false, kept: "unverifiable", branch, detail: removed.detail.trim().slice(0, 300) };
487
+ return { path, removed: true, ...(await branchLeftOf(env, tree)) };
488
+ }
489
+ async function standingOf(env, dir, sessionOf) {
490
+ const read = await readBirthMark(env, dir);
491
+ if (read.kind !== "marked")
492
+ return { kind: "unmarked", read };
493
+ const mark = read.mark;
494
+ const orphan = (why, detail) => ({ kind: "orphan", mark, why, ...(detail !== undefined ? { detail: detail.slice(0, 300) } : {}) });
495
+ let checkout;
496
+ try {
497
+ const session = await sessionOf(mark.sessionId);
498
+ if (session === undefined)
499
+ return orphan("unrecorded");
500
+ checkout = await readSessionCheckout(session, mark.sessionId);
501
+ }
502
+ catch (err) {
503
+ return orphan("record_unreadable", `the session ${mark.sessionId} could not be read (${thrownText(err)})`);
504
+ }
505
+ if (checkout.kind === "unreadable")
506
+ return orphan("record_unreadable", checkout.detail);
507
+ if (checkout.kind === "none") {
508
+ return checkout.window === undefined ? orphan("unrecorded") : orphan("record_unreadable", `the session's log is loaded from a bounded window (floor ${checkout.window.floor}); a checkout record below the floor cannot be ruled out`);
509
+ }
510
+ return recordHoldsMark(checkout.record, mark) ? { kind: "held", mark } : orphan("record_elsewhere", `the session's record holds allocation ${checkout.record.allocationId}`);
511
+ }
512
+ function lookupOf(door, opts) {
513
+ const sessionOf = opts !== null && typeof opts === "object" ? opts.sessionOf : undefined;
514
+ if (typeof sessionOf !== "function")
515
+ throw refusal("config.invalid_argument", `${door}: opts.sessionOf must be a function (the host's lookup of a session by id in its durable store)`);
516
+ return sessionOf;
517
+ }
518
+ export async function listOrphanSessionTrees(env, root, opts) {
519
+ const sessionOf = lookupOf("listOrphanSessionTrees", opts);
520
+ if (typeof root !== "string" || !root.startsWith("/"))
521
+ throw refusal("config.invalid_argument", "listOrphanSessionTrees: root must be an absolute path");
522
+ const repository = await managedAnchorOf(env, root);
523
+ const parent = `${repository}/${WORKTREE_PARENT}`;
524
+ const listed = await env.listDir(parent);
525
+ if (!listed.ok) {
526
+ if (listed.error.code === "not_found")
527
+ return { repository, trees: [] };
528
+ throw refusal("workspace.checkout_unavailable", `listOrphanSessionTrees: the managed parent ${parent} cannot be listed (${thrownText(listed.error).slice(0, 200)}); nothing was judged.`);
529
+ }
530
+ const trees = [];
531
+ for (const child of [...listed.value].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))) {
532
+ if (child.kind !== "directory")
533
+ continue;
534
+ const path = managedWorktreeDir(repository, child.name);
535
+ const standing = await standingOf(env, path, sessionOf);
536
+ if (standing.kind !== "orphan")
537
+ continue;
538
+ const { mark, why, detail } = standing;
539
+ const branch = managedWorktreeBranchOf(path);
540
+ trees.push({
541
+ path,
542
+ ...(branch !== undefined ? await branchLeftOf(env, { repository, branch }) : {}),
543
+ sessionId: mark.sessionId,
544
+ allocationId: mark.allocationId,
545
+ baseSha: mark.baseSha,
546
+ why,
547
+ ...(detail !== undefined ? { detail } : {}),
548
+ modifiedAt: child.mtimeMs,
549
+ });
550
+ }
551
+ return { repository, trees };
552
+ }
553
+ export async function releaseOrphanSessionTree(env, path, opts) {
554
+ const sessionOf = lookupOf("releaseOrphanSessionTree", opts);
555
+ const repository = typeof path === "string" ? managedWorktreeBaseOf(path) : undefined;
556
+ const branch = repository !== undefined ? managedWorktreeBranchOf(path) : undefined;
557
+ if (repository === undefined || branch === undefined) {
558
+ throw refusal("config.invalid_argument", `releaseOrphanSessionTree: ${String(path).slice(0, 200)} is not a managed tree path (<repository root>/${WORKTREE_PARENT}/<name>)`);
559
+ }
560
+ const at = await env.fileInfo(path);
561
+ if (!at.ok)
562
+ return at.error.code === "not_found" ? goneTree(env, { path, repository, branch }) : { path, removed: false, kept: "unverifiable", branch, detail: thrownText(at.error).slice(0, 300) };
563
+ const standing = await standingOf(env, path, sessionOf);
564
+ if (standing.kind === "unmarked") {
565
+ return standing.read.kind === "absent"
566
+ ? { path, removed: false, kept: "not_owned", ...(await branchLeftOf(env, { repository, branch })), detail: "it carries no allocation mark: it is no session tree" }
567
+ : { path, removed: false, kept: "unverifiable", branch, detail: standing.read.detail };
568
+ }
569
+ if (standing.kind === "held")
570
+ return { path, removed: false, kept: "not_owned", branch, detail: "a session's record holds this tree; releaseSessionCheckout releases it" };
571
+ if (standing.why === "record_unreadable")
572
+ return { path, removed: false, kept: "unverifiable", branch, ...(standing.detail !== undefined ? { detail: standing.detail } : {}) };
573
+ return releaseTree(env, { path, repository, branch, baseSha: standing.mark.baseSha }, standing.mark, "keep-if-dirty");
480
574
  }
481
575
  export function sessionFrameOf(record) {
482
576
  if (record === undefined || record.checkouts.length === 0)
@@ -182,12 +182,12 @@ export declare class TtlSessionStore implements SessionStore {
182
182
  placement?: SessionPlacement;
183
183
  }): Promise<AcquiredSession>;
184
184
  /** The one judgement of "does this cached view still stand for this row": `shown` is the view's session metadata and `row` the row as
185
- * a read of it answered (a listed row, or the repo's head; `undefined` = no row, or no read of one). A row naming the view's
186
- * occupant (`compareOccupants`) stands for it; a row naming another does not; and a row naming a different owner does not either —
187
- * the owner is recorded once, by the write that creates the row, so another owner's row is another row whatever it names. When
188
- * the evidence says neither (unknown) the answer is the repo's: over one with a head read the row can always be read again, so a
189
- * view without positive proof is dropped and the id resolved from the row; over one with no head read (it mints no occupant token)
190
- * the cached view is the only evidence of the occupant, and it stands. */
185
+ * a read of it answered (a listed row, or the repo's head; `undefined` = no row, or no read of one). A row naming another occupant
186
+ * (`compareOccupants` — the same token, or no token on either side, is one occupant) does not stand for it; neither does a row
187
+ * naming a different owner — the owner is recorded once, by the write that creates the row, so another owner's row is another row
188
+ * whatever it names; any other row does. With no row to judge (unknown) the answer is the repo's: over one with a head read the row
189
+ * can always be read again, so the view is dropped and the id resolved from the row; over one with no head read the cached view is
190
+ * the only evidence of the occupant, and it stands. */
191
191
  private viewStandsFor;
192
192
  /** Whether a cached view is still the occupant the row holds ({@link viewStandsFor}, over the row's head read in one read) and still
193
193
  * the log it holds — the row's leaf is the view's: a log replaced under the same occupant (a cross-backend move's commit, through
@@ -139,11 +139,11 @@ export class TtlSessionStore {
139
139
  }
140
140
  viewStandsFor(shown, row) {
141
141
  const verdict = compareOccupants(shown, row);
142
- if (verdict !== "unknown")
143
- return verdict === "same";
142
+ if (verdict === "different")
143
+ return false;
144
144
  if (row !== undefined && (shown.owner ?? null) !== (row.owner ?? null))
145
145
  return false;
146
- return this.repoHead === undefined;
146
+ return verdict === "same" || this.repoHead === undefined;
147
147
  }
148
148
  async standingRow(sessionId, cached) {
149
149
  if (this.repoHead === undefined)
@@ -1,6 +1,7 @@
1
1
  import { types } from "node:util";
2
2
  import { dispositionsOfRow, SHELL_READ_FINDINGS } from "../tools/fs/shell-read-judge.js";
3
3
  import { receiveContract } from "./decision-receipt.js";
4
+ import { refusalEchoDefects } from "./refusal-echo.js";
4
5
  import { egressThrownText } from "./untrusted-egress.js";
5
6
  import { receive } from "./mods/kernel/receive.js";
6
7
  import { attest, attestationOf } from "./engine-attestation.js";
@@ -13,6 +14,7 @@ const MEMBER_KINDS = {
13
14
  face: "face",
14
15
  sentence: "word",
15
16
  details: "record",
17
+ echoed: "list",
16
18
  readRootCandidate: "record",
17
19
  unestablished: "mark",
18
20
  writesPlaced: "mark",
@@ -43,6 +45,12 @@ function receivedAnswer(answer, call) {
43
45
  return undefined;
44
46
  v = data.value;
45
47
  }
48
+ if (kind === "list") {
49
+ const data = receive(v, OWNED_DATA_MODE);
50
+ if (!data.ok || !Array.isArray(data.value) || refusalEchoDefects(data.value).length > 0)
51
+ return undefined;
52
+ v = Object.freeze(data.value);
53
+ }
46
54
  if (kind === "admission") {
47
55
  const admission = v;
48
56
  v = () => {
@@ -99,6 +99,19 @@ export async function backgroundAgentStoreContract(mk, runAssertion) {
99
99
  assert.deepEqual(after.policyFloor, before.policyFloor, `a CAS update must carry the floor it did not change (${handle})`);
100
100
  }
101
101
  });
102
+ run("the root anchor's occupant round-trips beside the anchor — ABSENT stays absent, a CAS carries it", async (make) => {
103
+ const store = make();
104
+ await store.put(record({ handle: "a1", rootSessionId: "sess-root", rootSessionIncarnation: "occ-root-1" }));
105
+ const withOccupant = await held(store, "a1");
106
+ assert.equal(withOccupant.rootSessionId, "sess-root");
107
+ assert.equal(withOccupant.rootSessionIncarnation, "occ-root-1");
108
+ await store.put(record({ handle: "a2", rootSessionId: "sess-root" }));
109
+ const without = await held(store, "a2");
110
+ assert.equal(without.rootSessionIncarnation, undefined, "a row that records no root occupant must not read back with one");
111
+ const after = { ...withOccupant, status: "completed", settledAt: 2_000 };
112
+ assert.equal(await store.update("a1", S, after, { rev: withOccupant.rev }), true);
113
+ assert.equal((await held(store, "a1")).rootSessionIncarnation, "occ-root-1", "a CAS update must carry the root occupant it did not change");
114
+ });
102
115
  run("put refuses a scopeless row (a row with no tenant partition would be world-readable)", async (make) => {
103
116
  const store = make();
104
117
  await assert.rejects(store.put(record({ scope: "" })), "an empty scope must be refused loudly, not stored");
@@ -3,7 +3,7 @@ import { readPeerSessionRecord, resolvePeerSessions } from "../../agents/peer-di
3
3
  import { beginContract } from "./contract-harness.js";
4
4
  export const PEER_DIRECTORY_CONTRACT_SCOPE = "peer-kit-A";
5
5
  function row(name, sessionId, over = {}) {
6
- return { schemaVersion: 1, sessionId, scope: PEER_DIRECTORY_CONTRACT_SCOPE, name, startedAt: 1_000, updatedAt: 2_000, liveness: "live", where: "hosted", ...over };
6
+ return { schemaVersion: 1, sessionId, occupant: `occ-${sessionId}`, scope: PEER_DIRECTORY_CONTRACT_SCOPE, name, startedAt: 1_000, updatedAt: 2_000, liveness: "live", where: "hosted", ...over };
7
7
  }
8
8
  async function withDirs(mk, fn) {
9
9
  const live = [];
@@ -90,5 +90,12 @@ export async function peerDirectoryContract(mk, hooks) {
90
90
  assert.ok(read.ok, `listed row ${r.sessionId} is refused by the engine's reader (${read.ok ? "" : `${read.reason}${read.field !== undefined ? `: ${read.field}` : ""}`})`);
91
91
  }
92
92
  });
93
+ run("a row's occupant is listed as written — a token and null (a row with no token) alike", async (make) => {
94
+ const d = make();
95
+ await hooks.write(d, row("alpha", "sess-a"));
96
+ await hooks.write(d, row("beta", "sess-b", { occupant: null }));
97
+ const listed = await d.listPeerSessions({ scope: S });
98
+ assert.deepEqual(Object.fromEntries(listed.map((r) => [r.sessionId, r.occupant])), { "sess-a": "occ-sess-a", "sess-b": null }, "the occupant is what a sender stamps on what it parks in that session's box; a directory that loses or rewrites it misaddresses every message");
99
+ });
93
100
  await settle();
94
101
  }