@astrosheep/keiyaku 4.6.27 → 4.6.28

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 (285) hide show
  1. package/README.md +76 -35
  2. package/build/plugins/claude/.claude-plugin/plugin.json +1 -1
  3. package/build/plugins/claude/skills/keiyaku-akuma/SKILL.md +39 -4
  4. package/build/plugins/claude/skills/keiyaku-akuma/references/automation.md +4 -7
  5. package/build/plugins/claude/skills/keiyaku-babysit/SKILL.md +1 -1
  6. package/build/plugins/claude/skills/keiyaku-bind/SKILL.md +39 -15
  7. package/build/plugins/claude/skills/keiyaku-workflow/SKILL.md +42 -22
  8. package/build/plugins/codex/.codex-plugin/plugin.json +1 -1
  9. package/build/plugins/codex/skills/keiyaku-akuma/SKILL.md +39 -4
  10. package/build/plugins/codex/skills/keiyaku-akuma/references/automation.md +4 -7
  11. package/build/plugins/codex/skills/keiyaku-babysit/SKILL.md +1 -1
  12. package/build/plugins/codex/skills/keiyaku-bind/SKILL.md +39 -15
  13. package/build/plugins/codex/skills/keiyaku-workflow/SKILL.md +42 -22
  14. package/build/plugins/opencode/package.json +1 -1
  15. package/build/plugins/opencode/skills/keiyaku-akuma/SKILL.md +39 -4
  16. package/build/plugins/opencode/skills/keiyaku-akuma/references/automation.md +4 -7
  17. package/build/plugins/opencode/skills/keiyaku-babysit/SKILL.md +1 -1
  18. package/build/plugins/opencode/skills/keiyaku-bind/SKILL.md +39 -15
  19. package/build/plugins/opencode/skills/keiyaku-workflow/SKILL.md +42 -22
  20. package/build/plugins/pi/README.md +7 -12
  21. package/build/plugins/pi/akuma-tools.ts +3 -18
  22. package/build/skills/keiyaku-akuma/SKILL.md +39 -4
  23. package/build/skills/keiyaku-akuma/references/automation.md +4 -7
  24. package/build/skills/keiyaku-babysit/SKILL.md +1 -1
  25. package/build/skills/keiyaku-bind/SKILL.md +39 -15
  26. package/build/skills/keiyaku-workflow/SKILL.md +42 -22
  27. package/build/src/akuma/akuma-call.d.ts +15 -18
  28. package/build/src/akuma/akuma-call.js +55 -112
  29. package/build/src/akuma/akuma-errors.d.ts +0 -5
  30. package/build/src/akuma/akuma-errors.js +0 -9
  31. package/build/src/akuma/akuma-instance.d.ts +0 -2
  32. package/build/src/akuma/akuma-instance.js +18 -14
  33. package/build/src/akuma/akuma-observe.js +0 -1
  34. package/build/src/akuma/akuma-owner.js +0 -1
  35. package/build/src/akuma/akuma.d.ts +10 -26
  36. package/build/src/akuma/akuma.js +0 -2
  37. package/build/src/akuma/archetype.d.ts +0 -2
  38. package/build/src/akuma/archetype.js +3 -9
  39. package/build/src/akuma/body-launch.d.ts +12 -4
  40. package/build/src/akuma/body.d.ts +2 -5
  41. package/build/src/akuma/body.js +5 -49
  42. package/build/src/akuma/call-initial-tell.d.ts +39 -147
  43. package/build/src/akuma/call-initial-tell.js +0 -48
  44. package/build/src/akuma/caller.d.ts +0 -4
  45. package/build/src/akuma/custody.js +1 -57
  46. package/build/src/akuma/heart/facts.d.ts +0 -39
  47. package/build/src/akuma/heart/facts.js +0 -1
  48. package/build/src/akuma/heart/index.d.ts +1 -2
  49. package/build/src/akuma/heart/index.js +0 -1
  50. package/build/src/akuma/heart/schema.js +0 -26
  51. package/build/src/akuma/heart/soul.d.ts +2 -2
  52. package/build/src/akuma/heart/soul.js +2 -4
  53. package/build/src/akuma/identity.d.ts +0 -1
  54. package/build/src/akuma/identity.js +0 -2
  55. package/build/src/akuma/in-process-body.d.ts +1 -1
  56. package/build/src/akuma/index.d.ts +0 -2
  57. package/build/src/akuma/index.js +0 -1
  58. package/build/src/akuma/projection.d.ts +23 -23
  59. package/build/src/akuma/provider.d.ts +0 -5
  60. package/build/src/akuma/provider.js +0 -1
  61. package/build/src/akuma/providers/acp/core.js +1 -1
  62. package/build/src/akuma/providers/claude/index.js +1 -2
  63. package/build/src/akuma/providers/codex-app-server/index.js +1 -1
  64. package/build/src/akuma/providers/execution-environment.d.ts +1 -3
  65. package/build/src/akuma/providers/execution-environment.js +1 -7
  66. package/build/src/akuma/providers/opencode-sdk/index.js +0 -1
  67. package/build/src/akuma/providers/opencode-sdk/session.d.ts +0 -1
  68. package/build/src/akuma/providers/opencode-sdk/session.js +4 -4
  69. package/build/src/akuma/providers/paseo/index.js +2 -9
  70. package/build/src/akuma/providers/pi/index.js +8 -14
  71. package/build/src/akuma/publication.d.ts +24 -59
  72. package/build/src/akuma/publication.js +29 -64
  73. package/build/src/akuma/selection-observation.d.ts +47 -2036
  74. package/build/src/akuma/selection-observation.js +1 -59
  75. package/build/src/akuma/turn-drive.d.ts +0 -8
  76. package/build/src/akuma/turn-drive.js +19 -103
  77. package/build/src/akuma-body.js +3 -6
  78. package/build/src/body-host.d.ts +8 -2
  79. package/build/src/body-host.js +30 -4
  80. package/build/src/cli/commands/akuma-grammar.d.ts +0 -2
  81. package/build/src/cli/commands/akuma-grammar.js +10 -33
  82. package/build/src/cli/commands/akuma.js +31 -49
  83. package/build/src/cli/commands/contract-grammar.d.ts +7 -1
  84. package/build/src/cli/commands/contract-grammar.js +15 -0
  85. package/build/src/cli/commands/contract-help.d.ts +13 -1
  86. package/build/src/cli/commands/contract-help.js +47 -16
  87. package/build/src/cli/commands/contract.js +27 -26
  88. package/build/src/cli/commands/debt.js +3 -3
  89. package/build/src/cli/commands/whoami.d.ts +0 -2
  90. package/build/src/cli/commands/whoami.js +0 -5
  91. package/build/src/cli/coordinates.js +15 -0
  92. package/build/src/cli/delivery-identity.d.ts +3 -0
  93. package/build/src/cli/delivery-identity.js +23 -0
  94. package/build/src/cli/parse.js +1 -0
  95. package/build/src/cli/render/akuma-activity.d.ts +0 -1
  96. package/build/src/cli/render/akuma-activity.js +1 -4
  97. package/build/src/cli/render/catalog.js +7 -1
  98. package/build/src/cli/render/contract-history.js +16 -38
  99. package/build/src/cli/render/contract-observation.d.ts +23 -10
  100. package/build/src/cli/render/contract-observation.js +9 -6
  101. package/build/src/cli/render/contract-wait.d.ts +2 -0
  102. package/build/src/cli/render/contract-wait.js +18 -0
  103. package/build/src/cli/render/contract.d.ts +2 -2
  104. package/build/src/cli/render/contract.js +57 -39
  105. package/build/src/cli/render/delivery-preview.js +13 -26
  106. package/build/src/cli/render/execution-progress.js +9 -9
  107. package/build/src/cli/render/kanshi.js +4 -11
  108. package/build/src/cli/render/receipt.d.ts +18 -0
  109. package/build/src/cli/render/receipt.js +34 -10
  110. package/build/src/cli/render/reconcile.js +3 -0
  111. package/build/src/cli/render/refusal.js +28 -6
  112. package/build/src/cli/render/whoami.js +1 -4
  113. package/build/src/cli/runtime.d.ts +0 -2
  114. package/build/src/cli/runtime.js +3 -7
  115. package/build/src/cli/selectors.d.ts +1 -2
  116. package/build/src/cli/selectors.js +2 -5
  117. package/build/src/contract-guidance.js +4 -2
  118. package/build/src/contract-worktree.d.ts +3 -3
  119. package/build/src/core/facts/codec.js +38 -5
  120. package/build/src/core/facts/fold.js +1 -0
  121. package/build/src/core/facts/gate.d.ts +10 -4
  122. package/build/src/core/facts/gate.js +56 -39
  123. package/build/src/core/facts/observation.d.ts +7 -1
  124. package/build/src/core/facts/observation.js +15 -0
  125. package/build/src/core/facts/offer.d.ts +2 -2
  126. package/build/src/core/facts/types.d.ts +17 -1
  127. package/build/src/core/facts/types.js +6 -0
  128. package/build/src/core/verbs/amend.js +8 -0
  129. package/build/src/core/verbs/bind.d.ts +3 -1
  130. package/build/src/core/verbs/bind.js +9 -1
  131. package/build/src/core/verbs/deliver.d.ts +2 -1
  132. package/build/src/core/verbs/deliver.js +4 -1
  133. package/build/src/core/verbs/placement.d.ts +2 -1
  134. package/build/src/core/verbs/placement.js +7 -4
  135. package/build/src/core/verbs/reintegrate.d.ts +2 -1
  136. package/build/src/core/verbs/reintegrate.js +4 -1
  137. package/build/src/debt/board.d.ts +10 -10
  138. package/build/src/debt/created-observation.d.ts +3 -3
  139. package/build/src/debt/document.d.ts +1 -1
  140. package/build/src/debt/index.d.ts +2 -24
  141. package/build/src/debt/index.js +11 -71
  142. package/build/src/debt/operation-types.d.ts +44 -3
  143. package/build/src/git/admission.js +18 -6
  144. package/build/src/git/integration.d.ts +4 -4
  145. package/build/src/git/integration.js +7 -1
  146. package/build/src/git/observe.d.ts +6 -4
  147. package/build/src/git/observe.js +18 -17
  148. package/build/src/git/reconcile.d.ts +20 -8
  149. package/build/src/git/reconcile.js +94 -45
  150. package/build/src/git/repository.d.ts +3 -1
  151. package/build/src/git/repository.js +26 -4
  152. package/build/src/git/scratch.d.ts +1 -1
  153. package/build/src/git/scratch.js +19 -18
  154. package/build/src/git/target-placement.d.ts +33 -7
  155. package/build/src/git/target-placement.js +67 -18
  156. package/build/src/git/target.d.ts +32 -0
  157. package/build/src/git/target.js +84 -0
  158. package/build/src/git/terminal-reconcile.d.ts +1 -1
  159. package/build/src/git/terminal-reconcile.js +34 -6
  160. package/build/src/index.d.ts +9 -7
  161. package/build/src/index.js +1 -1
  162. package/build/src/library/address.d.ts +1 -20
  163. package/build/src/library/address.js +3 -24
  164. package/build/src/library/akuma-creation.d.ts +2 -5
  165. package/build/src/library/akuma-creation.js +60 -44
  166. package/build/src/library/akumas.d.ts +3 -9
  167. package/build/src/library/akumas.js +12 -25
  168. package/build/src/library/bind.d.ts +21 -9
  169. package/build/src/library/bind.js +5 -1
  170. package/build/src/library/continuation.d.ts +130 -155
  171. package/build/src/library/continuation.js +1 -4
  172. package/build/src/library/contract-composition.d.ts +4 -9
  173. package/build/src/library/contract-composition.js +8 -12
  174. package/build/src/library/contract-creation.d.ts +1 -3
  175. package/build/src/library/contract-creation.js +2 -3
  176. package/build/src/library/contract-execution.d.ts +3 -5
  177. package/build/src/library/contract-execution.js +55 -96
  178. package/build/src/library/contract-outcomes.d.ts +2 -1
  179. package/build/src/library/contract-types.d.ts +5 -0
  180. package/build/src/library/contract-wait.d.ts +35 -0
  181. package/build/src/library/contract-wait.js +141 -0
  182. package/build/src/library/delivery.d.ts +13 -525
  183. package/build/src/library/delivery.js +1 -12
  184. package/build/src/library/input.js +2 -1
  185. package/build/src/library/invocation.d.ts +5 -1
  186. package/build/src/library/invocation.js +9 -2
  187. package/build/src/library/keiyaku.d.ts +7 -6
  188. package/build/src/library/keiyaku.js +12 -7
  189. package/build/src/library/outcome.d.ts +461 -12586
  190. package/build/src/library/outcome.js +15 -234
  191. package/build/src/library/reconcile.d.ts +12 -0
  192. package/build/src/library/reconcile.js +1 -0
  193. package/build/src/library/refusal.d.ts +251 -34
  194. package/build/src/library/refusal.js +10 -5
  195. package/build/src/library/selection.d.ts +9 -35
  196. package/build/src/library/selection.js +59 -129
  197. package/build/src/plugin/akuma-signals.d.ts +2 -2
  198. package/build/src/plugin/akuma-signals.js +2 -2
  199. package/build/src/plugin/public.d.ts +0 -7
  200. package/build/src/plugin/runtime.d.ts +2 -2
  201. package/build/src/plugin/runtime.js +4 -3
  202. package/build/src/protocol/attempt.js +7 -3
  203. package/build/src/protocol/bind.d.ts +18 -4
  204. package/build/src/protocol/bind.js +102 -35
  205. package/build/src/protocol/completion.d.ts +18 -331
  206. package/build/src/protocol/completion.js +17 -130
  207. package/build/src/protocol/deliver.d.ts +3 -3
  208. package/build/src/protocol/deliver.js +64 -74
  209. package/build/src/protocol/delivery-preview.d.ts +85 -28
  210. package/build/src/protocol/delivery-preview.js +34 -22
  211. package/build/src/protocol/execution-observation.d.ts +12 -9
  212. package/build/src/protocol/execution-observation.js +0 -1
  213. package/build/src/protocol/intent.d.ts +20 -50
  214. package/build/src/protocol/intent.js +37 -44
  215. package/build/src/protocol/operations.d.ts +299 -19
  216. package/build/src/protocol/operations.js +68 -27
  217. package/build/src/protocol/outcome.d.ts +1 -1
  218. package/build/src/protocol/placement.d.ts +2 -2
  219. package/build/src/protocol/placement.js +4 -3
  220. package/build/src/protocol/progress.d.ts +35 -2
  221. package/build/src/protocol/progress.js +12 -1
  222. package/build/src/protocol/read/observation.js +15 -4
  223. package/build/src/protocol/read/status.d.ts +9 -14
  224. package/build/src/protocol/read/status.js +15 -22
  225. package/build/src/protocol/reintegrate.d.ts +4 -3
  226. package/build/src/protocol/reintegrate.js +21 -5
  227. package/build/src/protocol/review.d.ts +9 -15
  228. package/build/src/protocol/review.js +2 -6
  229. package/build/src/protocol/run.d.ts +1 -1
  230. package/build/src/protocol/verify.d.ts +51 -0
  231. package/build/src/protocol/verify.js +128 -0
  232. package/build/src/verification/declaration.d.ts +5 -1
  233. package/build/src/verification/declaration.js +19 -2
  234. package/build/src/verification/execution.d.ts +5 -2
  235. package/build/src/verification/execution.js +48 -53
  236. package/build/src/verification/observation.d.ts +10 -6
  237. package/build/src/verification/observation.js +5 -2
  238. package/package.json +3 -3
  239. package/plugins/paseo/plugin/index.server.ts +3 -0
  240. package/plugins/paseo/plugin/server/attach.ts +42 -0
  241. package/plugins/paseo/plugin/server/mirror-identity.ts +51 -0
  242. package/plugins/paseo/plugin/server/model.ts +26 -0
  243. package/plugins/paseo/plugin/server/provider.ts +4 -6
  244. package/plugins/paseo/plugin/server/reopen.ts +4 -39
  245. package/plugins/pi/README.md +7 -12
  246. package/plugins/pi/akuma-tools.ts +3 -18
  247. package/skills/keiyaku-akuma/SKILL.md +39 -4
  248. package/skills/keiyaku-akuma/references/automation.md +4 -7
  249. package/skills/keiyaku-babysit/SKILL.md +1 -1
  250. package/skills/keiyaku-bind/SKILL.md +39 -15
  251. package/skills/keiyaku-workflow/SKILL.md +42 -22
  252. package/build/src/akuma/allowed.d.ts +0 -23
  253. package/build/src/akuma/allowed.js +0 -63
  254. package/build/src/akuma/call-request.d.ts +0 -308
  255. package/build/src/akuma/call-request.js +0 -175
  256. package/build/src/akuma/heart/request-authority.d.ts +0 -16
  257. package/build/src/akuma/heart/request-authority.js +0 -140
  258. package/build/src/akuma/heart/request-rows.d.ts +0 -18
  259. package/build/src/akuma/heart/request-rows.js +0 -107
  260. package/build/src/akuma/request-lifecycle.d.ts +0 -42
  261. package/build/src/akuma/request-lifecycle.js +0 -197
  262. package/build/src/akuma/request-observation.d.ts +0 -45
  263. package/build/src/akuma/request-observation.js +0 -162
  264. package/build/src/akuma/request-rendezvous.d.ts +0 -32
  265. package/build/src/akuma/request-rendezvous.js +0 -189
  266. package/build/src/akuma/request-serve.d.ts +0 -16
  267. package/build/src/akuma/request-serve.js +0 -188
  268. package/build/src/akuma/request-wire.d.ts +0 -143
  269. package/build/src/akuma/request-wire.js +0 -146
  270. package/build/src/akuma/requests.d.ts +0 -20
  271. package/build/src/akuma/requests.js +0 -72
  272. package/build/src/akuma/selection-owner-port.d.ts +0 -14
  273. package/build/src/akuma/selection-owner-port.js +0 -54
  274. package/build/src/akuma/selection-request.d.ts +0 -305
  275. package/build/src/akuma/selection-request.js +0 -307
  276. package/build/src/body-requests.d.ts +0 -13
  277. package/build/src/body-requests.js +0 -131
  278. package/build/src/cli/square-identity.d.ts +0 -10
  279. package/build/src/cli/square-identity.js +0 -130
  280. package/build/src/debt/mutation-result.d.ts +0 -981
  281. package/build/src/debt/mutation-result.js +0 -109
  282. package/build/src/debt/mutation.d.ts +0 -424
  283. package/build/src/debt/mutation.js +0 -223
  284. package/build/src/library/contract-operations.d.ts +0 -382
  285. package/build/src/library/contract-operations.js +0 -300
@@ -7,6 +7,7 @@ import { executeGit, GitPlumbingError, runGitPipe } from "./process.js";
7
7
  import { deliveryEnvironment, materializeSnapshotCommit, } from "./tender.js";
8
8
  import { workspaceMergeStatePresent } from "./workspace.js";
9
9
  import { withGitDecodeChannel } from "./read-observation.js";
10
+ import { resolveContractTarget, targetRef, targetRepository } from "./target.js";
10
11
  export { workspaceMergeStatePresent };
11
12
  const REQUIRED_GIT = "2.38";
12
13
  async function runAllowingNonzero(repository, args, input) {
@@ -265,7 +266,12 @@ export async function planIntegration(repository, input, tender, requireBranches
265
266
  },
266
267
  };
267
268
  }
268
- const observed = await readRef(repository, target);
269
+ if (typeof target !== "string") {
270
+ const resolved = await resolveContractTarget(repository, target.contractId, target);
271
+ if (resolved.kind === "refused")
272
+ return resolved;
273
+ }
274
+ const observed = await readRef(targetRepository(repository, target), targetRef(target));
269
275
  if (observed === null) {
270
276
  return { kind: "refused", refusal: { kind: "target-missing", contractId: input.contractId } };
271
277
  }
@@ -1,4 +1,4 @@
1
- import { type ContractId, type ContractState, type JournalEntry, type SnapshotId } from "../core/facts/types.js";
1
+ import { type ContractId, type ContractState, type ContractTarget, type JournalEntry, type SnapshotId } from "../core/facts/types.js";
2
2
  import type { ContractsObservation } from "../core/facts/observation.js";
3
3
  import { type GitSnapshot, type GitOid } from "./repository.js";
4
4
  import { type GitRepository } from "./process.js";
@@ -31,7 +31,7 @@ export type GitDecisionObservation = Readonly<{
31
31
  }>;
32
32
  export type BindCoordinatesObservation = Readonly<{
33
33
  start: SnapshotId;
34
- target?: string;
34
+ target?: ContractTarget;
35
35
  branch: string | null;
36
36
  }>;
37
37
  type UnbornHeadObservation = Readonly<{
@@ -41,14 +41,16 @@ type UnbornHeadObservation = Readonly<{
41
41
  export type BindTargetSelection = Readonly<{
42
42
  kind: "explicit";
43
43
  target: string;
44
+ }> | Readonly<{
45
+ kind: "contract";
46
+ contractId: ContractId;
47
+ inherited?: Exclude<ContractTarget, string>;
44
48
  }> | Readonly<{
45
49
  kind: "current-branch";
46
50
  }> | Readonly<{
47
51
  kind: "targetless";
48
52
  }>;
49
53
  export declare function normalizeTargetBranch(repository: GitRepository, input: string): Promise<string | null>;
50
- /** Read one worktree's attached branch, or null for detached HEAD. */
51
- export declare function currentBranch(repository: GitRepository, path?: string): Promise<string | null>;
52
54
  /**
53
55
  * Observe bind's tender start and optional reward target without creating persistent state.
54
56
  * `current-branch` reads the observed worktree coordinate's own attached branch; the caller names
@@ -1,15 +1,23 @@
1
1
  import { decodeJournal } from "../core/facts/codec.js";
2
2
  import { AuthorityCorruptionError } from "../core/facts/errors.js";
3
3
  import { foldJournal } from "../core/facts/fold.js";
4
+ import { targetRef, targetRepository, resolveContractTarget } from "./target.js";
4
5
  import { contractJournalPath, contractJournalPaths, mintContractHead, mintSnapshotId, } from "./identity.js";
5
- import { isKeiyakuOwnedRef } from "./repository.js";
6
+ import { currentBranch, isKeiyakuOwnedRef, readRef } from "./repository.js";
6
7
  import { GitPlumbingError, executeGit } from "./process.js";
7
8
  import { readBlobResults, readGitTreeSelection, withGitTargetedReadObservation, } from "./read-observation.js";
8
9
  export async function observeDeliveryTargetAt(observation, state) {
9
10
  const target = state.coordinates.target;
10
11
  if (target === undefined)
11
12
  return null;
12
- const value = await observation.resolveRef(target);
13
+ if (typeof target !== "string") {
14
+ const resolved = await resolveContractTarget(observation.repository, target.contractId, target);
15
+ if (resolved.kind === "refused")
16
+ return { head: null, drift: true };
17
+ }
18
+ const value = typeof target === "string"
19
+ ? await observation.resolveRef(target)
20
+ : await readRef(targetRepository(observation.repository, target), targetRef(target));
13
21
  const head = value === null ? null : mintSnapshotId(value);
14
22
  const integration = state.currentIntegration;
15
23
  if (integration === null)
@@ -38,20 +46,6 @@ export async function normalizeTargetBranch(repository, input) {
38
46
  throw error;
39
47
  }
40
48
  }
41
- /** Read one worktree's attached branch, or null for detached HEAD. */
42
- export async function currentBranch(repository, path) {
43
- try {
44
- const ref = (await executeGit(repository, [...(path === undefined ? [] : ["-C", path]), "symbolic-ref", "--quiet", "HEAD"]))
45
- .toString("utf8")
46
- .trim();
47
- return ref.startsWith("refs/heads/") ? ref : null;
48
- }
49
- catch (error) {
50
- if (error instanceof GitPlumbingError && error.status === 1)
51
- return null;
52
- throw error;
53
- }
54
- }
55
49
  function malformedBindCoordinatesOutput() {
56
50
  throw new Error("malformed structured Git output while observing bind coordinates");
57
51
  }
@@ -83,6 +77,8 @@ async function observeHeadCoordinates(repository) {
83
77
  * which coordinate it wants observed.
84
78
  */
85
79
  export async function observeBindCoordinates(repository, selection) {
80
+ if (selection.kind === "contract")
81
+ throw new Error("contract targets require physical resolution");
86
82
  if (selection.kind === "explicit") {
87
83
  const requestedTarget = selection.target;
88
84
  if (isKeiyakuOwnedRef(requestedTarget)) {
@@ -252,10 +248,15 @@ async function observeTargetedContractsFromSnapshotAt(snapshot, readBlobsAt, ids
252
248
  return { contracts, frozenJournalBytes: blobs };
253
249
  }
254
250
  export async function observeContractsForAdmissionAt(repository, channel, ids, selection = {}) {
255
- return withGitTargetedReadObservation(repository, channel, {
251
+ const observed = await withGitTargetedReadObservation(repository, channel, {
256
252
  paths: [...ids.flatMap(contractJournalPaths), ...(selection.paths ?? [])],
257
253
  ...(selection.subtrees === undefined ? {} : { subtrees: selection.subtrees }),
258
254
  }, async (observation) => await observeContractsForAdmissionInObservationAt(observation, ids));
255
+ const targets = ids.flatMap((id) => {
256
+ const target = observed.decision.get(id)?.coordinates.target;
257
+ return target !== undefined && typeof target !== "string" ? [target.contractId] : [];
258
+ });
259
+ return await extendContractsForAdmissionAt(channel, observed, targets);
259
260
  }
260
261
  /** Observe selected Contract journals and their current direct prerequisites in one Git epoch. */
261
262
  export async function observeGitForAdmissionAt(repository, channel, ids, selection = {}) {
@@ -1,26 +1,26 @@
1
1
  import { z } from "zod";
2
2
  import { type GitRepository } from "./process.js";
3
- import type { ContractId, ContractState, SnapshotId } from "../core/facts/types.js";
3
+ import { type ContractId, type ContractState, type SnapshotId } from "../core/facts/types.js";
4
4
  import type { GitDecodeChannel } from "./read-observation.js";
5
5
  import { type WorktreeHooks } from "./hooks.js";
6
6
  export declare const reconcileEffectSchema: z.ZodUnion<readonly [z.ZodPipe<z.ZodObject<{
7
7
  kind: z.ZodLiteral<"worktree">;
8
8
  path: z.ZodString;
9
9
  action: z.ZodEnum<{
10
- created: "created";
11
- unchanged: "unchanged";
12
10
  removed: "removed";
11
+ unchanged: "unchanged";
12
+ created: "created";
13
13
  }>;
14
14
  before: z.ZodOptional<z.ZodUnknown>;
15
15
  after: z.ZodOptional<z.ZodUnknown>;
16
16
  }, z.core.$strict>, z.ZodTransform<{
17
17
  kind: "worktree";
18
18
  path: string;
19
- action: "created" | "unchanged" | "removed";
19
+ action: "removed" | "unchanged" | "created";
20
20
  }, {
21
21
  kind: "worktree";
22
22
  path: string;
23
- action: "created" | "unchanged" | "removed";
23
+ action: "removed" | "unchanged" | "created";
24
24
  before?: unknown;
25
25
  after?: unknown;
26
26
  }>>, z.ZodObject<{
@@ -48,10 +48,10 @@ export declare const reconcileEffectSchema: z.ZodUnion<readonly [z.ZodPipe<z.Zod
48
48
  before: z.ZodNullable<z.ZodString>;
49
49
  after: z.ZodNullable<z.ZodString>;
50
50
  action: z.ZodEnum<{
51
- created: "created";
52
- updated: "updated";
53
- unchanged: "unchanged";
54
51
  removed: "removed";
52
+ unchanged: "unchanged";
53
+ updated: "updated";
54
+ created: "created";
55
55
  }>;
56
56
  }, z.core.$strict>]>;
57
57
  export type Effect = z.infer<typeof reconcileEffectSchema>;
@@ -91,6 +91,18 @@ export declare const gitReconcileLagSchema: z.ZodUnion<readonly [z.ZodObject<{
91
91
  path: z.ZodString;
92
92
  target: z.ZodString;
93
93
  diagnostic: z.ZodString;
94
+ }, z.core.$strict>, z.ZodObject<{
95
+ kind: z.ZodLiteral<"target-workspace-retained">;
96
+ contractId: z.ZodPipe<z.ZodString, z.ZodTransform<ContractId, string>>;
97
+ reason: z.ZodEnum<{
98
+ missing: "missing";
99
+ replaced: "replaced";
100
+ unappointed: "unappointed";
101
+ association: "association";
102
+ attached: "attached";
103
+ uncommitted: "uncommitted";
104
+ operation: "operation";
105
+ }>;
94
106
  }, z.core.$strict>, z.ZodObject<{
95
107
  kind: z.ZodLiteral<"worktree-hook-failed">;
96
108
  phase: z.ZodEnum<{
@@ -1,6 +1,6 @@
1
1
  import { snapshotIdSchema, mintedSnapshotInputSchema } from "./identity.js";
2
2
  import { z } from "zod";
3
- import { targetCheckoutEffectSchema, targetCheckoutLagSchema } from "./target-placement.js";
3
+ import { targetCheckoutEffectSchema, targetCheckoutLagSchema, targetWorkspaceLagSchema } from "./target-placement.js";
4
4
  import { worktreeHookLagSchema } from "./hooks.js";
5
5
  import { unsealedBytesSchema } from "./terminal-seal.js";
6
6
  import { access, mkdir } from "node:fs/promises";
@@ -9,8 +9,11 @@ import { acquireSqliteTransactionLock, SqliteTransactionLockError, } from "../co
9
9
  import { AuthorityCorruptionError } from "../core/facts/errors.js";
10
10
  import { CANDIDATE_PIN_REF_NAMESPACE, commonGitDirectory, DELIVERY_REF_NAMESPACE, registeredWorktreePaths, } from "./repository.js";
11
11
  import { executeGit, GitPlumbingError } from "./process.js";
12
+ import { targetName } from "../core/facts/types.js";
13
+ import { appointmentFor, readPlaceRegister } from "../workspace-place.js";
12
14
  import { contractLocator, contractPhysicalName, gitObjectIdForSnapshot } from "./identity.js";
13
15
  import { observeContractAt } from "./observe.js";
16
+ import { GitPrivateStateSeatContentionError, withPrivateStatePublicationSeat } from "./private-state-seat.js";
14
17
  import { acquireTargetPlacementFence, recoverTargetPlacement } from "./target-placement.js";
15
18
  import { runCreateHooks } from "./hooks.js";
16
19
  import { followDependentManagedWorktree, retireConflictHandoff, worktreePath } from "./workspace.js";
@@ -91,6 +94,7 @@ export const gitReconcileLagSchema = z.union([
91
94
  .strict(),
92
95
  unsealedBytesSchema,
93
96
  targetCheckoutLagSchema,
97
+ targetWorkspaceLagSchema,
94
98
  worktreeHookLagSchema,
95
99
  reconcileFailureSchema,
96
100
  ]);
@@ -138,6 +142,7 @@ function reconcileAccumulation(onPhysical) {
138
142
  }
139
143
  function failed(stage, error, effects = [], lag = []) {
140
144
  if (!(error instanceof WorktreeCustodyError ||
145
+ error instanceof GitPrivateStateSeatContentionError ||
141
146
  error instanceof GitPlumbingError ||
142
147
  error instanceof SqliteTransactionLockError ||
143
148
  (error instanceof Error &&
@@ -187,7 +192,7 @@ async function reconcileTargetCheckouts(repository, state, onPhysical) {
187
192
  }
188
193
  let held;
189
194
  try {
190
- held = await acquireTargetPlacementFence(repository, state.coordinates.target);
195
+ held = await acquireTargetPlacementFence(repository, targetName(state.coordinates.target));
191
196
  }
192
197
  catch (error) {
193
198
  return failed("effect", error);
@@ -221,7 +226,7 @@ async function reconcileTargetCheckouts(repository, state, onPhysical) {
221
226
  result = failed("effect", releaseFailure, result.effects, result.lag);
222
227
  return result;
223
228
  }
224
- async function reconcileActiveManagedWorktree({ repository, hooks, retryHooks, place }, state, topology, acc) {
229
+ async function reconcileActiveManagedWorktree({ repository, channel, hooks, retryHooks, place }, state, topology, acc) {
225
230
  const { effects, lag, hookRuns } = acc;
226
231
  if (place === undefined) {
227
232
  acc.recordLag(missingPlaceLag(repository));
@@ -229,7 +234,18 @@ async function reconcileActiveManagedWorktree({ repository, hooks, retryHooks, p
229
234
  }
230
235
  const path = worktreePath(repository, place);
231
236
  const desired = state.delivery?.data.tenderSnapshot ?? state.coordinates.start;
232
- acc.recordEffect(await updateRef(repository, deliveryRefFor(state.id), desired));
237
+ const pins = await withPrivateStatePublicationSeat(repository, async () => {
238
+ const current = (await observeContractAt(repository, channel, state.id)).state;
239
+ if (current?.head !== state.head)
240
+ return undefined;
241
+ acc.recordEffect(await updateRef(repository, deliveryRefFor(state.id), desired));
242
+ acc.recordEffect(state.delivery
243
+ ? await updateRef(repository, candidatePinRefFor(state.id), state.currentIntegration?.snapshot ?? state.delivery.data.integration.snapshot)
244
+ : await removeRef(repository, candidatePinRefFor(state.id)));
245
+ return true;
246
+ });
247
+ if (pins.value === undefined)
248
+ throw new WorktreeCustodyError(`Contract moved during workspace reconciliation: ${state.id}`);
233
249
  const projection = await worktree(repository, topology, path, desired);
234
250
  acc.recordEffect(projection);
235
251
  const handoff = await retireConflictHandoff(repository, {
@@ -251,9 +267,6 @@ async function reconcileActiveManagedWorktree({ repository, hooks, retryHooks, p
251
267
  if (hookRun.lag !== null)
252
268
  acc.recordLag(hookRun.lag);
253
269
  }
254
- acc.recordEffect(await (state.delivery
255
- ? await updateRef(repository, candidatePinRefFor(state.id), state.currentIntegration?.snapshot ?? state.delivery.data.integration.snapshot)
256
- : await removeRef(repository, candidatePinRefFor(state.id))));
257
270
  return complete(effects, lag, hookRuns);
258
271
  }
259
272
  async function terminalHandoffRetained(input, state, topology, acc) {
@@ -293,9 +306,6 @@ async function reconcileWithTopology(input, state, topology) {
293
306
  await removeCollectableScratch(repository, topology, acc, state?.terminal ? state.id : undefined);
294
307
  if (!state)
295
308
  return complete(effects, lag);
296
- const targetCheckouts = await reconcileTargetCheckouts(repository, state, input.onPhysical);
297
- acc.recordEffect(...targetCheckouts.effects);
298
- acc.recordLag(...targetCheckouts.lag);
299
309
  if (state.terminal) {
300
310
  if (await terminalHandoffRetained(input, state, topology, acc))
301
311
  return complete(effects, lag, hookRuns);
@@ -324,6 +334,37 @@ function releaseFailure(held, observation) {
324
334
  };
325
335
  }
326
336
  }
337
+ async function reconcileFreshEffects(input, cursor) {
338
+ for (let attempt = 0; attempt < 4; attempt += 1) {
339
+ const before = (await observeContractAt(input.repository, input.channel, input.contractId)).state;
340
+ cursor.before = before;
341
+ const recovered = before === null ? complete() : await reconcileTargetCheckouts(input.repository, before, input.onPhysical);
342
+ const outgoing = {
343
+ effects: [...(cursor.outgoing?.effects ?? []), ...recovered.effects],
344
+ lag: [...(cursor.outgoing?.lag ?? []), ...recovered.lag],
345
+ };
346
+ cursor.outgoing = outgoing;
347
+ const incoming = await acquireTargetPlacementFence(input.repository, input.contractId);
348
+ try {
349
+ const state = (await observeContractAt(input.repository, input.channel, input.contractId)).state;
350
+ if (state?.head !== before?.head)
351
+ continue;
352
+ const topology = await acquireWorktreeTopology(input.repository);
353
+ const place = appointmentFor(await readPlaceRegister(input.repository), input.contractId)?.place;
354
+ const { place: _previousPlace, ...base } = input;
355
+ const result = await reconcileWithTopology({ ...base, ...(place === undefined ? {} : { place }) }, state, topology);
356
+ cursor.observation = {
357
+ state,
358
+ result: { ...result, effects: [...outgoing.effects, ...result.effects], lag: [...outgoing.lag, ...result.lag] },
359
+ };
360
+ }
361
+ finally {
362
+ incoming.close();
363
+ }
364
+ return;
365
+ }
366
+ throw new WorktreeCustodyError(`Contract moved during reconciliation: ${input.contractId}`);
367
+ }
327
368
  export async function reconcile(input) {
328
369
  let held;
329
370
  try {
@@ -335,36 +376,35 @@ export async function reconcile(input) {
335
376
  catch (error) {
336
377
  return { state: null, result: failed("observation", error) };
337
378
  }
338
- let observation;
379
+ const cursor = { before: null };
339
380
  let exceptional;
340
381
  try {
341
- const state = (await observeContractAt(input.repository, input.channel, input.contractId)).state;
342
- const topology = await acquireWorktreeTopology(input.repository);
343
- observation = {
344
- state,
345
- result: await reconcileWithTopology(input, state, topology),
346
- };
347
- input.onPhysical?.(observation.result);
382
+ await reconcileFreshEffects(input, cursor);
383
+ input.onPhysical?.(cursor.observation.result);
348
384
  }
349
385
  catch (error) {
350
386
  try {
351
- observation = { state: null, result: failed("observation", error) };
387
+ const prior = cursor.observation?.result ?? cursor.outgoing;
388
+ cursor.observation = {
389
+ state: cursor.observation?.state ?? cursor.before,
390
+ result: failed(cursor.outgoing === undefined ? "observation" : "effect", error, prior?.effects, prior?.lag),
391
+ };
352
392
  }
353
393
  catch (unexpected) {
354
394
  exceptional = { error: unexpected };
355
395
  }
356
396
  }
357
397
  try {
358
- observation = releaseFailure(held, observation);
398
+ cursor.observation = releaseFailure(held, cursor.observation);
359
399
  }
360
400
  catch (error) {
361
401
  exceptional ??= { error };
362
402
  }
363
403
  if (exceptional !== undefined)
364
404
  throw exceptional.error;
365
- if (observation === undefined)
405
+ if (cursor.observation === undefined)
366
406
  throw new Error("reconcile produced no observation");
367
- return observation;
407
+ return cursor.observation;
368
408
  }
369
409
  /** Reconcile one retained dependent worktree under its normal per-Contract lock. */
370
410
  export async function reconcileDependentWorktree(repository, contractId, path, target) {
@@ -377,30 +417,39 @@ export async function reconcileDependentWorktree(repository, contractId, path, t
377
417
  }
378
418
  let result;
379
419
  try {
380
- const follow = await followDependentManagedWorktree(repository, path, target);
381
- if (follow.kind === "followed") {
382
- result = {
383
- effects: [{ kind: "worktree", path, action: "followed", before: follow.before, after: follow.after }],
384
- lag: [],
385
- };
386
- }
387
- else if (follow.kind === "unchanged") {
388
- result = { effects: [], lag: [] };
420
+ const incoming = await acquireTargetPlacementFence(repository, contractId);
421
+ try {
422
+ const appointed = appointmentFor(await readPlaceRegister(repository), contractId);
423
+ if (appointed === undefined || worktreePath(repository, appointed.place) !== path)
424
+ throw new WorktreeCustodyError(`dependent Contract workspace appointment changed: ${contractId}`);
425
+ const follow = await followDependentManagedWorktree(repository, path, target);
426
+ if (follow.kind === "followed") {
427
+ result = {
428
+ effects: [{ kind: "worktree", path, action: "followed", before: follow.before, after: follow.after }],
429
+ lag: [],
430
+ };
431
+ }
432
+ else if (follow.kind === "unchanged") {
433
+ result = { effects: [], lag: [] };
434
+ }
435
+ else {
436
+ result = {
437
+ effects: [{ kind: "worktree", path, action: "unchanged" }],
438
+ lag: [
439
+ {
440
+ kind: "worktree-follow-retained",
441
+ path,
442
+ tender: target,
443
+ head: follow.head,
444
+ reason: follow.reason,
445
+ ...(follow.paths.length === 0 ? {} : { paths: follow.paths }),
446
+ },
447
+ ],
448
+ };
449
+ }
389
450
  }
390
- else {
391
- result = {
392
- effects: [{ kind: "worktree", path, action: "unchanged" }],
393
- lag: [
394
- {
395
- kind: "worktree-follow-retained",
396
- path,
397
- tender: target,
398
- head: follow.head,
399
- reason: follow.reason,
400
- ...(follow.paths.length === 0 ? {} : { paths: follow.paths }),
401
- },
402
- ],
403
- };
451
+ finally {
452
+ incoming.close();
404
453
  }
405
454
  }
406
455
  catch (error) {
@@ -38,6 +38,8 @@ export declare function registeredWorktrees(repository: GitRepository): Promise<
38
38
  export declare function registeredWorktreePaths(repository: GitRepository): Promise<readonly string[]>;
39
39
  export declare function repositoryAt(cwd: string, gitPath?: string): Promise<GitRepository>;
40
40
  export declare function commonGitDirectory(repository: GitRepository): string;
41
+ /** Read one worktree's attached branch, or null for detached HEAD. */
42
+ export declare function currentBranch(repository: GitRepository, path?: string): Promise<string | null>;
41
43
  export declare function worktreeGitDirectory(repository: GitRepository, worktree: string): Promise<string>;
42
44
  export declare function readRef(repository: GitRepository, ref: string): Promise<GitOid | null>;
43
45
  /** Read an explicit set of asserted refs from one fresh Git observation. */
@@ -68,7 +70,7 @@ export declare function updateRefsAtomically(repository: GitRepository, updates:
68
70
  } | {
69
71
  readonly ref: string;
70
72
  readonly newOid: GitOid;
71
- readonly expectedOid: GitOid;
73
+ readonly expectedOid: GitOid | null;
72
74
  })[], assertions?: readonly GitRefAssertion[]): Promise<RefPublication>;
73
75
  type GitDiffStat = Readonly<{
74
76
  filesChanged: number;
@@ -121,6 +121,20 @@ async function absoluteGitPath(repository, args, label) {
121
121
  export function commonGitDirectory(repository) {
122
122
  return repository.commonDirectory;
123
123
  }
124
+ /** Read one worktree's attached branch, or null for detached HEAD. */
125
+ export async function currentBranch(repository, path) {
126
+ try {
127
+ const ref = (await executeGit(repository, [...(path === undefined ? [] : ["-C", path]), "symbolic-ref", "--quiet", "HEAD"]))
128
+ .toString("utf8")
129
+ .trim();
130
+ return ref.startsWith("refs/heads/") ? ref : null;
131
+ }
132
+ catch (error) {
133
+ if (error instanceof GitPlumbingError && error.status === 1)
134
+ return null;
135
+ throw error;
136
+ }
137
+ }
124
138
  export async function worktreeGitDirectory(repository, worktree) {
125
139
  const scoped = { ...repository, effectiveCwd: worktree };
126
140
  return await absoluteGitPath(scoped, ["--git-dir"], "worktree Git directory");
@@ -129,7 +143,9 @@ async function worktreeRoot(repository) {
129
143
  return await absoluteGitPath(repository, ["--show-toplevel"], "worktree root");
130
144
  }
131
145
  function assertRef(ref) {
132
- if (!ref.startsWith("refs/") || /[\s\0]/.test(ref) || ref.endsWith("/") || ref.includes("..")) {
146
+ const linkedWorktreeHead = /^worktrees\/(?!\.)(?![^/]*\.lock\/)(?![^/]*\.\.)[^/\s\0~^:?*\[\\]+\/HEAD$/u.test(ref);
147
+ if (!linkedWorktreeHead &&
148
+ (!ref.startsWith("refs/") || /[\s\0]/.test(ref) || ref.endsWith("/") || ref.includes(".."))) {
133
149
  throw new Error(`invalid Git ref: ${ref}`);
134
150
  }
135
151
  }
@@ -383,14 +399,20 @@ export async function writeStateCommit(input) {
383
399
  function refAssertionLine(assertion) {
384
400
  assertAssertionRef(assertion.ref);
385
401
  gitObjectId(assertion.oid, `expected oid for ${assertion.ref}`);
402
+ if (assertion.ref.startsWith("worktrees/")) {
403
+ // Git accepts a cross-worktree HEAD as an update but not as a verify command.
404
+ return `option no-deref\nupdate ${assertion.ref} ${assertion.oid} ${assertion.oid}`;
405
+ }
386
406
  return `${assertion.ref === "HEAD" ? "" : "option no-deref\n"}verify ${assertion.ref} ${assertion.oid}`;
387
407
  }
388
408
  function refUpdateLine(update, index) {
389
409
  assertRef(update.ref);
390
410
  if (index > 0 && update.ref === GIT_REF)
391
411
  throw new Error(`duplicate ref update: ${update.ref}`);
392
- if (index > 0 && update.expectedOid === null)
412
+ if (index === 1 && update.expectedOid === null)
393
413
  throw new Error("target ref updates require non-null OIDs");
414
+ if (index === 2 && !update.ref.startsWith(`${CANDIDATE_PIN_REF_NAMESPACE}/`))
415
+ throw new Error("third atomic update must be a candidate pin");
394
416
  gitObjectId(update.newOid, `new oid for ${update.ref}`);
395
417
  if (update.expectedOid !== null)
396
418
  gitObjectId(update.expectedOid, `expected oid for ${update.ref}`);
@@ -399,8 +421,8 @@ function refUpdateLine(update, index) {
399
421
  export async function updateRefsAtomically(repository, updates, assertions = []) {
400
422
  if (updates.length === 0)
401
423
  throw new Error("an atomic ref transaction needs a Git update");
402
- if (updates.length > 2)
403
- throw new Error("an atomic ref transaction accepts at most one target ref update");
424
+ if (updates.length > 3)
425
+ throw new Error("an atomic ref transaction accepts at most one target and candidate pin");
404
426
  const git = updates[0];
405
427
  if (git === undefined || git.ref !== GIT_REF) {
406
428
  throw new Error(`the first atomic update must be the Git ref: ${GIT_REF}`);
@@ -23,5 +23,5 @@ type CollectableScratchRemoval = Readonly<{
23
23
  /** Remove only abandoned Verification scratch worktrees whose ownership locks are held. */
24
24
  export declare function removeCollectableScratchWorktrees(repository: GitRepository, paths: Set<string>, terminalContract?: ContractId): Promise<readonly CollectableScratchRemoval[]>;
25
25
  /** Materialize a disposable candidate worktree and own only its removal. */
26
- export declare function materializeScratchCandidate(repository: GitRepository, candidate: SnapshotId, contract?: ContractId): Promise<MaterializedScratchCandidate>;
26
+ export declare function materializeScratchCandidate(repository: GitRepository, candidate: SnapshotId, contract: ContractId, requirement: string): Promise<MaterializedScratchCandidate>;
27
27
  export {};
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  import { lstat, realpath, unlink } from "node:fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { basename, dirname, join } from "node:path";
@@ -9,7 +9,7 @@ import { executeGit } from "./process.js";
9
9
  import { registeredWorktreePaths } from "./repository.js";
10
10
  const SCRATCH_PREFIX = "keiyaku-v4-verify-";
11
11
  const SCRATCH_ROOT = await realpath(tmpdir());
12
- const SCRATCH_PATTERN = /^keiyaku-v4-verify-([0-9a-f]{24}|[0-9a-f]{64}-[0-9a-f]{64})$/;
12
+ const SCRATCH_PATTERN = /^keiyaku-v4-verify-([0-9a-f]{24}|[0-9a-f]{64}-[0-9a-f]{64}-[0-9a-f]{64})$/;
13
13
  /** One bounded removal attempt per scratch; expiry is reported, never retried inside this call. */
14
14
  const SCRATCH_REMOVAL_TIMEOUT_MS = 120_000;
15
15
  export const worktreeLeakSchema = z.object({ path: z.string().optional(), diagnostic: z.string() }).strict();
@@ -24,8 +24,12 @@ export class ScratchMaterializationError extends Error {
24
24
  function scratchPath() {
25
25
  return join(SCRATCH_ROOT, `${SCRATCH_PREFIX}${randomBytes(12).toString("hex")}`);
26
26
  }
27
- function retainedScratchPath(repository, contract) {
28
- return join(SCRATCH_ROOT, `${SCRATCH_PREFIX}${gitRefLocator(repository.commonDirectory)}-${contractLocator(contract)}`);
27
+ function retainedScratchPrefix(repository, contract) {
28
+ return `${SCRATCH_PREFIX}${gitRefLocator(repository.commonDirectory)}-${contractLocator(contract)}-`;
29
+ }
30
+ function retainedScratchPath(repository, contract, requirement) {
31
+ const locator = createHash("sha256").update(requirement, "utf8").digest("hex");
32
+ return join(SCRATCH_ROOT, `${retainedScratchPrefix(repository, contract)}${locator}`);
29
33
  }
30
34
  function ownershipLockPath(path) {
31
35
  if (dirname(path) !== SCRATCH_ROOT)
@@ -39,19 +43,18 @@ async function removeOwnershipLock(lockPath) {
39
43
  throw error;
40
44
  });
41
45
  }
42
- async function collectableScratchWorktrees(paths, terminalScratch) {
43
- const collectable = [];
46
+ async function* collectableScratchWorktrees(paths, terminalPrefix) {
44
47
  for (const path of paths) {
45
48
  const lockPath = ownershipLockPath(path);
46
49
  if (lockPath === null)
47
50
  continue;
48
- if (basename(path).length !== SCRATCH_PREFIX.length + 24 && path !== terminalScratch)
51
+ if (basename(path).length !== SCRATCH_PREFIX.length + 24 &&
52
+ (terminalPrefix === undefined || !basename(path).startsWith(terminalPrefix)))
49
53
  continue;
50
54
  const lock = await tryAcquireSqliteTransactionLock({ path: lockPath, mode: "exclusive" });
51
55
  if (lock !== null)
52
- collectable.push({ path, lockPath, release: () => lock.close() });
56
+ yield { path, lockPath, release: () => lock.close() };
53
57
  }
54
- return collectable;
55
58
  }
56
59
  /** Absence is ENOENT on the path entry itself: a dangling symlink is present residue, not a missing path. */
57
60
  async function pathExists(path) {
@@ -99,8 +102,8 @@ async function removeScratch(repository, path) {
99
102
  /** Remove only abandoned Verification scratch worktrees whose ownership locks are held. */
100
103
  export async function removeCollectableScratchWorktrees(repository, paths, terminalContract) {
101
104
  const removals = [];
102
- const terminalScratch = terminalContract === undefined ? undefined : retainedScratchPath(repository, terminalContract);
103
- for (const scratch of await collectableScratchWorktrees(paths, terminalScratch)) {
105
+ const terminalPrefix = terminalContract === undefined ? undefined : retainedScratchPrefix(repository, terminalContract);
106
+ for await (const scratch of collectableScratchWorktrees(paths, terminalPrefix)) {
104
107
  let removed = false;
105
108
  try {
106
109
  const leak = await removeScratch(repository, scratch.path);
@@ -114,14 +117,14 @@ export async function removeCollectableScratchWorktrees(repository, paths, termi
114
117
  }
115
118
  finally {
116
119
  scratch.release();
117
- if (removed && scratch.path !== terminalScratch)
120
+ if (removed && basename(scratch.path).length === SCRATCH_PREFIX.length + 24)
118
121
  await removeOwnershipLock(scratch.lockPath);
119
122
  }
120
123
  }
121
124
  return removals;
122
125
  }
123
- async function retainScratch(repository, cwd, contract) {
124
- const retained = retainedScratchPath(repository, contract);
126
+ async function retainScratch(repository, cwd, contract, requirement) {
127
+ const retained = retainedScratchPath(repository, contract, requirement);
125
128
  const lockPath = ownershipLockPath(retained);
126
129
  if (lockPath === null)
127
130
  throw new Error("scratch ownership lock path is invalid");
@@ -165,7 +168,7 @@ async function retainScratch(repository, cwd, contract) {
165
168
  }
166
169
  }
167
170
  /** Materialize a disposable candidate worktree and own only its removal. */
168
- export async function materializeScratchCandidate(repository, candidate, contract) {
171
+ export async function materializeScratchCandidate(repository, candidate, contract, requirement) {
169
172
  const cwd = scratchPath();
170
173
  const lockPath = ownershipLockPath(cwd);
171
174
  if (lockPath === null)
@@ -201,9 +204,7 @@ export async function materializeScratchCandidate(repository, candidate, contrac
201
204
  try {
202
205
  if (!retain)
203
206
  return await removeScratch(repository, cwd);
204
- if (contract === undefined)
205
- return { path: cwd, diagnostic: "failed Verification scratch retained for diagnosis" };
206
- return await retainScratch(repository, cwd, contract);
207
+ return await retainScratch(repository, cwd, contract, requirement);
207
208
  }
208
209
  finally {
209
210
  ownership.close();