@aviaratech/ai-delivery 0.3.34 → 0.3.36

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 (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -506
  3. package/dist/agent.d.ts +0 -2
  4. package/dist/agent.js +76 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1746 -0
  9. package/dist/boardReconcile.test.js.map +7 -0
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +105 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +406 -485
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -25
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +434 -297
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +320 -14
  22. package/dist/config/deliveryConfig.js +472 -385
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +775 -584
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -477
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.d.ts +1 -0
  53. package/dist/deliveryBoard.test.js +649 -0
  54. package/dist/deliveryBoard.test.js.map +7 -0
  55. package/dist/deliveryHealth.test.js +179 -155
  56. package/dist/deliveryHealth.test.js.map +7 -1
  57. package/dist/dependencyCompatibility.test.js +154 -140
  58. package/dist/dependencyCompatibility.test.js.map +7 -1
  59. package/dist/directoryIndependent.test.js +417 -383
  60. package/dist/directoryIndependent.test.js.map +7 -1
  61. package/dist/dispatch.d.ts +17 -12
  62. package/dist/dispatch.js +330 -322
  63. package/dist/dispatch.js.map +7 -1
  64. package/dist/errors.d.ts +16 -3
  65. package/dist/errors.js +104 -82
  66. package/dist/errors.js.map +7 -1
  67. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  68. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  69. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  70. package/dist/fixtures/discovery.d.ts +59 -19
  71. package/dist/fixtures/discovery.js +96 -90
  72. package/dist/fixtures/discovery.js.map +7 -1
  73. package/dist/fixtures/inertEntrypointChild.js +57 -56
  74. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  75. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  76. package/dist/fixtures/inertEntrypoints.js +321 -276
  77. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  78. package/dist/fixtures/inertTarget.d.ts +78 -7
  79. package/dist/fixtures/inertTarget.js +769 -691
  80. package/dist/fixtures/inertTarget.js.map +7 -1
  81. package/dist/fixtures/issue63.d.ts +4 -3
  82. package/dist/fixtures/issue63.js +260 -274
  83. package/dist/fixtures/issue63.js.map +7 -1
  84. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  85. package/dist/fixtures/issueProjectItems.js +15 -0
  86. package/dist/fixtures/issueProjectItems.js.map +7 -0
  87. package/dist/fixtures/readView.d.ts +120 -0
  88. package/dist/fixtures/readView.js +172 -0
  89. package/dist/fixtures/readView.js.map +7 -0
  90. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  91. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  92. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  93. package/dist/genericCompatibility.test.js +64 -55
  94. package/dist/genericCompatibility.test.js.map +7 -1
  95. package/dist/git.js +73 -67
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +44 -51
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +3 -0
  106. package/dist/github/discovery.js +197 -201
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +53 -1
  121. package/dist/github/projectDelivery.js +623 -460
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.d.ts +5 -2
  124. package/dist/github/relationships.js +434 -333
  125. package/dist/github/relationships.js.map +7 -1
  126. package/dist/github/repo.d.ts +1 -0
  127. package/dist/github/repo.js +123 -96
  128. package/dist/github/repo.js.map +7 -1
  129. package/dist/index.js +3 -3
  130. package/dist/index.js.map +7 -1
  131. package/dist/issue.d.ts +103 -7
  132. package/dist/issue.js +2104 -1547
  133. package/dist/issue.js.map +7 -1
  134. package/dist/issue63History.test.js +40 -42
  135. package/dist/issue63History.test.js.map +7 -1
  136. package/dist/issue63Routes.test.js +154 -143
  137. package/dist/issue63Routes.test.js.map +7 -1
  138. package/dist/issueBatchUpdate.test.js +1004 -683
  139. package/dist/issueBatchUpdate.test.js.map +7 -1
  140. package/dist/issueBlockerGuard.test.js +262 -226
  141. package/dist/issueBlockerGuard.test.js.map +7 -1
  142. package/dist/issueContract.d.ts +23 -4
  143. package/dist/issueContract.js +416 -395
  144. package/dist/issueContract.js.map +7 -1
  145. package/dist/issueContract.test.d.ts +4 -3
  146. package/dist/issueContract.test.js +358 -321
  147. package/dist/issueContract.test.js.map +7 -1
  148. package/dist/issueDates.test.js +235 -233
  149. package/dist/issueDates.test.js.map +7 -1
  150. package/dist/issueInfoReadback.test.js +304 -190
  151. package/dist/issueInfoReadback.test.js.map +7 -1
  152. package/dist/issueIntake.test.js +1945 -1732
  153. package/dist/issueIntake.test.js.map +7 -1
  154. package/dist/issueJournal.d.ts +40 -19
  155. package/dist/issueJournal.js +229 -138
  156. package/dist/issueJournal.js.map +7 -1
  157. package/dist/issueJournal.test.js +605 -422
  158. package/dist/issueJournal.test.js.map +7 -1
  159. package/dist/issueRollup.test.d.ts +1 -0
  160. package/dist/issueRollup.test.js +476 -0
  161. package/dist/issueRollup.test.js.map +7 -0
  162. package/dist/issueTracking.test.js +1088 -593
  163. package/dist/issueTracking.test.js.map +7 -1
  164. package/dist/issueWriteRecovery.test.d.ts +1 -0
  165. package/dist/issueWriteRecovery.test.js +260 -0
  166. package/dist/issueWriteRecovery.test.js.map +7 -0
  167. package/dist/lifecycle.test.js +112 -441
  168. package/dist/lifecycle.test.js.map +7 -1
  169. package/dist/logger.js +80 -74
  170. package/dist/logger.js.map +7 -1
  171. package/dist/mcp/index.js +116 -90
  172. package/dist/mcp/index.js.map +7 -1
  173. package/dist/mcp/tools.d.ts +790 -220
  174. package/dist/mcp/tools.js +267 -333
  175. package/dist/mcp/tools.js.map +7 -1
  176. package/dist/pluginAuthProbe.js +63 -52
  177. package/dist/pluginAuthProbe.js.map +7 -1
  178. package/dist/pluginAuthProbe.test.js +85 -62
  179. package/dist/pluginAuthProbe.test.js.map +7 -1
  180. package/dist/pluginCredentials.test.js +282 -259
  181. package/dist/pluginCredentials.test.js.map +7 -1
  182. package/dist/pluginDoctor.test.js +653 -588
  183. package/dist/pluginDoctor.test.js.map +7 -1
  184. package/dist/pluginInstaller.d.ts +7 -5
  185. package/dist/pluginInstaller.js +1173 -1231
  186. package/dist/pluginInstaller.js.map +7 -1
  187. package/dist/pluginInstaller.test.js +1822 -1283
  188. package/dist/pluginInstaller.test.js.map +7 -1
  189. package/dist/pluginPackaging.test.js +485 -305
  190. package/dist/pluginPackaging.test.js.map +7 -1
  191. package/dist/pr.d.ts +132 -94
  192. package/dist/pr.js +1521 -1323
  193. package/dist/pr.js.map +7 -1
  194. package/dist/pr.test.js +1678 -632
  195. package/dist/pr.test.js.map +7 -1
  196. package/dist/prAssociation.test.js +2419 -1788
  197. package/dist/prAssociation.test.js.map +7 -1
  198. package/dist/prDispatch.test.js +150 -89
  199. package/dist/prDispatch.test.js.map +7 -1
  200. package/dist/readView.d.ts +183 -0
  201. package/dist/readView.js +217 -0
  202. package/dist/readView.js.map +7 -0
  203. package/dist/readView.test.d.ts +1 -0
  204. package/dist/readView.test.js +119 -0
  205. package/dist/readView.test.js.map +7 -0
  206. package/dist/releaseReconciliation.test.js +267 -288
  207. package/dist/releaseReconciliation.test.js.map +7 -1
  208. package/dist/releaseWorkflow.test.js +2493 -422
  209. package/dist/releaseWorkflow.test.js.map +7 -1
  210. package/dist/review.d.ts +738 -2
  211. package/dist/review.js +601 -348
  212. package/dist/review.js.map +7 -1
  213. package/dist/review.test.js +1218 -812
  214. package/dist/review.test.js.map +7 -1
  215. package/dist/reviewSubmit.test.d.ts +1 -0
  216. package/dist/reviewSubmit.test.js +747 -0
  217. package/dist/reviewSubmit.test.js.map +7 -0
  218. package/dist/services/agentReadinessService.js +42 -37
  219. package/dist/services/agentReadinessService.js.map +7 -1
  220. package/dist/services/blockerGuardService.js +188 -188
  221. package/dist/services/blockerGuardService.js.map +7 -1
  222. package/dist/services/boardReconcileService.d.ts +1204 -0
  223. package/dist/services/boardReconcileService.js +1445 -0
  224. package/dist/services/boardReconcileService.js.map +7 -0
  225. package/dist/services/deliveryAdmission.d.ts +2 -0
  226. package/dist/services/deliveryAdmission.js +129 -152
  227. package/dist/services/deliveryAdmission.js.map +7 -1
  228. package/dist/services/deliveryHealthService.js +197 -199
  229. package/dist/services/deliveryHealthService.js.map +7 -1
  230. package/dist/services/legacyIssueMigration.js +263 -277
  231. package/dist/services/legacyIssueMigration.js.map +7 -1
  232. package/dist/services/worktreeRegistry.d.ts +27 -119
  233. package/dist/services/worktreeRegistry.js +765 -1182
  234. package/dist/services/worktreeRegistry.js.map +7 -1
  235. package/dist/stagedChecks.test.js +396 -194
  236. package/dist/stagedChecks.test.js.map +7 -1
  237. package/dist/start.test.js +99 -95
  238. package/dist/start.test.js.map +7 -1
  239. package/dist/stdoutRegression.test.js +354 -350
  240. package/dist/stdoutRegression.test.js.map +7 -1
  241. package/dist/targetPolicyDiscovery.test.js +141 -143
  242. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  243. package/dist/targetPolicyEntrypoints.test.js +308 -269
  244. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  245. package/dist/targetPolicyLocal.test.js +580 -1051
  246. package/dist/targetPolicyLocal.test.js.map +7 -1
  247. package/dist/targetPolicyRoutes.test.js +305 -281
  248. package/dist/targetPolicyRoutes.test.js.map +7 -1
  249. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  250. package/dist/targetRepositoryExecution.test.js +463 -0
  251. package/dist/targetRepositoryExecution.test.js.map +7 -0
  252. package/dist/terminalMessages.js +41 -35
  253. package/dist/terminalMessages.js.map +7 -1
  254. package/dist/toolOutput.d.ts +2 -0
  255. package/dist/toolOutput.js +36 -0
  256. package/dist/toolOutput.js.map +7 -0
  257. package/dist/toolOutput.test.d.ts +1 -0
  258. package/dist/toolOutput.test.js +240 -0
  259. package/dist/toolOutput.test.js.map +7 -0
  260. package/dist/utils/atomicJson.js +84 -76
  261. package/dist/utils/atomicJson.js.map +7 -1
  262. package/dist/utils/filesystem.js +15 -18
  263. package/dist/utils/filesystem.js.map +7 -1
  264. package/dist/utils/lockfile.js +68 -71
  265. package/dist/utils/lockfile.js.map +7 -1
  266. package/dist/verification.d.ts +1 -19
  267. package/dist/verification.js +1020 -1929
  268. package/dist/verification.js.map +7 -1
  269. package/dist/verificationGate.test.js +127 -117
  270. package/dist/verificationGate.test.js.map +7 -1
  271. package/dist/version.d.ts +6 -0
  272. package/dist/version.js +24 -10
  273. package/dist/version.js.map +7 -1
  274. package/dist/worktree.d.ts +3 -15
  275. package/dist/worktree.js +97 -177
  276. package/dist/worktree.js.map +7 -1
  277. package/package.json +10 -8
  278. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  279. package/plugins/ai-delivery/README.md +47 -156
  280. package/plugins/ai-delivery/plugin.json +1 -1
  281. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +261 -43
  282. package/plugins/ai-delivery/runtime/dist/cli.js +369 -125
  283. package/plugins/ai-delivery/runtime/package.json +1 -1
  284. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  285. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  286. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  287. package/dist/investigationCompletion.test.js +0 -728
  288. package/dist/investigationCompletion.test.js.map +0 -1
  289. package/dist/setup.d.ts +0 -60
  290. package/dist/setup.js +0 -585
  291. package/dist/setup.js.map +0 -1
  292. package/dist/setup.test.js +0 -3058
  293. package/dist/setup.test.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → boardReconcile.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → build.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → callerErrors.test.d.ts} +0 -0
@@ -1,1191 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync, } from 'node:fs';
4
- import { spawnSync } from 'node:child_process';
5
- import { tmpdir } from 'node:os';
6
- import { dirname, join } from 'node:path';
7
- import { fileURLToPath } from 'node:url';
8
- import { test, vi } from 'vitest';
9
- import { digestBytes, digestValue, stableJson } from './delivery/common.js';
10
- import { classifyRepositoryExactRange, createRepositoryStageInput, createRepositoryStageReceipt, createRepositoryStageAggregate, writeRepositoryStageCheckpoint, } from './delivery/legacy.js';
11
- import { buildRuntimeAdmission } from './services/deliveryAdmission.js';
12
- import { gitCommonDir } from './git.js';
13
- import { addWorktreeEntry, assertNativeIssueTrackingAdmission, getIssueWorktreeStrict, listWorktreesStrict, withWorktreeTransitionRegistry, } from './services/worktreeRegistry.js';
14
- import { prepareIssueWorktree } from './worktree.js';
15
- import { withWorktreeTransitionWriterLease } from './verification.js';
16
- import { applyWorktreeTransition, assertWorktreeTransitionNativeAuthority, inspectWorktreeTransition, inventoryTransitionEvidence, preserveTransitionEvidence, worktreeAcceptanceBody, worktreeRelinquishmentBody, } from './worktreeTransition.js';
17
- import { assertWorktreeTransitionWriterQuiescent, retainedWorktreeTransitionProducerDigest } from './verification.js';
18
- const nativeAuthority = vi.hoisted(() => ({
19
- reviewer: 'configured-reviewer[bot]',
20
- comments: new Map(),
21
- revoked: [],
22
- }));
23
- vi.mock('./github/client.js', async (original) => ({
24
- ...(await original()),
25
- createDeliveryGitHubClients: async () => ({
26
- authSource: 'app',
27
- role: 'reviewer',
28
- appActorLogin: async () => nativeAuthority.reviewer,
29
- rest: {
30
- issues: {
31
- getComment: async ({ comment_id }) => ({
32
- data: nativeAuthority.comments.get(comment_id),
33
- }),
34
- },
35
- },
36
- }),
37
- }));
38
- function authorityFixture(root) {
39
- nativeAuthority.comments.clear();
40
- nativeAuthority.revoked = [];
41
- nativeAuthority.reviewer = 'configured-reviewer[bot]';
42
- // Authority-unit tests deliberately isolate native identity/body validation from installed producer and Git proof.
43
- const digest = digestValue('synthetic immutable bytes');
44
- const runtimeContent = {
45
- schemaVersion: 'ai-delivery.runtime-admission@2',
46
- capability: { cli: 2, mcp: 2 },
47
- repository: 'example/widget',
48
- cliPath: join(root, 'synthetic-runtime/dist/cli.js'),
49
- cliSha256: digest,
50
- configDigest: digest,
51
- mcpLauncherPath: join(root, 'synthetic-runtime/plugins/ai-delivery/dist/mcp-launcher.js'),
52
- mcpLauncherSha256: digest,
53
- pluginManifestPath: join(root, 'synthetic-runtime/plugins/ai-delivery/.claude-plugin/plugin.json'),
54
- pluginManifestSha256: digest,
55
- packageDistSha256: digest,
56
- packageManifestSha256: digest,
57
- packageVersion: '0.3.5',
58
- sourceArchiveSha256: digest,
59
- sourceCommit: 'a'.repeat(40),
60
- };
61
- const admission = { ...runtimeContent, admissionId: digestValue(runtimeContent) };
62
- const content = {
63
- schemaVersion: 'ai-delivery.worktree-transition-plan@1',
64
- repository: 'example/widget',
65
- repoRoot: root,
66
- row: entry(root),
67
- purpose: 'active-resume',
68
- disposition: 'retain',
69
- terminalPrNumber: null,
70
- head: { sha: 'a'.repeat(40), tree: 'b'.repeat(40) },
71
- lineage: [],
72
- remoteRefs: null,
73
- retainedHoldCommentIds: [],
74
- holdEvidence: [],
75
- inventory: [],
76
- inventoryId: digestValue([]),
77
- historicalProducer: 'UNKNOWN',
78
- closure: {
79
- family: 'public-ai-delivery-0.3.5-posix@1',
80
- admissionPath: join(root, 'synthetic-admission.json'),
81
- archivePath: join(root, 'synthetic-archive.tar.gz'),
82
- admission,
83
- admissionBytesDigest: digest,
84
- producerDigest: digest,
85
- runManifestIds: [digest],
86
- },
87
- currentRuntime: admission,
88
- policyDigest: digest,
89
- operator: { actorLogin: 'configured-host', credentialIdentity: 'user:37' },
90
- reviewerActor: nativeAuthority.reviewer,
91
- };
92
- const plan = { ...content, planId: digestValue(content) };
93
- const context = {
94
- root,
95
- repo: { owner: 'example', repo: 'widget' },
96
- config: { roles: { reviewer: { identity: 'configured-reviewer' } } },
97
- clients: {
98
- authSource: 'personal',
99
- role: 'author',
100
- authenticatedAuthor: async () => plan.operator,
101
- rest: {
102
- issues: {
103
- getComment: async ({ comment_id }) => ({
104
- data: nativeAuthority.comments.get(comment_id),
105
- }),
106
- listComments: async () => ({ data: nativeAuthority.revoked }),
107
- },
108
- },
109
- },
110
- };
111
- const issue_url = 'https://api.github.com/repos/example/widget/issues/17';
112
- nativeAuthority.comments.set(101, {
113
- id: 101,
114
- issue_url,
115
- user: { id: 37, login: 'configured-host', type: 'User' },
116
- body: worktreeRelinquishmentBody(plan),
117
- });
118
- nativeAuthority.comments.set(102, {
119
- id: 102,
120
- issue_url,
121
- user: { id: 38, login: nativeAuthority.reviewer, type: 'Bot' },
122
- body: worktreeAcceptanceBody(plan, 101),
123
- });
124
- return { plan, context, ids: { relinquishmentCommentId: 101, acceptanceCommentId: 102 } };
125
- }
126
- function approvedFixturePlan(f, plan) {
127
- const planPath = join(f.root, 'approved-plan.json');
128
- writeFileSync(planPath, stableJson(plan));
129
- nativeAuthority.comments.get(101).body = worktreeRelinquishmentBody(plan);
130
- nativeAuthority.comments.get(102).body = worktreeAcceptanceBody(plan, 101);
131
- return {
132
- authority: 'worktree:transition',
133
- planPath,
134
- expectedPlanId: plan.planId,
135
- relinquishmentCommentId: 101,
136
- acceptanceCommentId: 102,
137
- runtimeEntryPath: f.runtimeEntryPath,
138
- };
139
- }
140
- function interruptedApply(f, plan, event) {
141
- const input = approvedFixturePlan(f, plan);
142
- const commonUrl = new URL('./delivery/common.js', import.meta.url).href;
143
- const clientUrl = new URL('./github/client.js', import.meta.url).href;
144
- const inputPath = join(f.root, 'child-transition-input.json');
145
- writeFileSync(inputPath, stableJson({
146
- input,
147
- event,
148
- plan,
149
- context: { root: f.root, repo: f.context.repo, config: f.context.config, configuration: f.context.configuration },
150
- comments: [...nativeAuthority.comments],
151
- nativePr: f.nativePr,
152
- }));
153
- // Only GitHub HTTP/auth is substituted. Files, admission, producer hashing, Git and process identities stay real.
154
- const script = `
155
- import { registerHooks } from 'node:module';
156
- import { readFileSync } from 'node:fs';
157
- const f=JSON.parse(readFileSync(process.argv[1],'utf8'));
158
- const comments=new Map(f.comments);
159
- const issues={getComment:async({comment_id})=>({data:comments.get(comment_id)}),listComments:async()=>({data:[]}),get:async()=>({data:{state:f.plan.purpose==='merged-cleanup'?'closed':'open'}})};
160
- globalThis.__transitionReviewer={authSource:'app',role:'reviewer',appActorLogin:async()=>f.plan.reviewerActor,rest:{issues}};
161
- registerHooks({load(url,context,next){
162
- if(url===${JSON.stringify(clientUrl)})return {format:'module',shortCircuit:true,source:
163
- 'export * from '+JSON.stringify(url+'?original')+'; export async function createDeliveryGitHubClients(){return globalThis.__transitionReviewer;}'};
164
- if(url===${JSON.stringify(commonUrl)})return {format:'module',shortCircuit:true,source:
165
- 'export * from '+JSON.stringify(url+'?original')+'; import {writeCreateOnly as original} from '+JSON.stringify(url+'?original')+'; export function writeCreateOnly(path,bytes,digest){const value=original(path,bytes,digest);if(globalThis.__transitionCrash(path))process.exit(73);return value;}'};
166
- return next(url,context);
167
- }});
168
- globalThis.__transitionCrash=(path)=> f.event==='intent' ? path.endsWith('.transition.json') : f.event==='completion' ? path.endsWith('/completion.json') : path.endsWith('.'+f.event+'.json');
169
- const {applyWorktreeTransition}=await import(${JSON.stringify(new URL('./worktreeTransition.js', import.meta.url).href)});
170
- const context={...f.context,clients:{authSource:'personal',role:'author',authenticatedAuthor:async()=>f.plan.operator,
171
- graphql:async()=>({repository:{pullRequest:{closingIssuesReferences:{nodes:[{number:17,repository:{nameWithOwner:'example/widget'}}],pageInfo:{hasNextPage:false}}}}}),
172
- rest:{issues,pulls:{get:async()=>({data:f.nativePr})},repos:{getBranch:async({branch})=>({data:{name:branch,commit:{sha:f.plan.remoteRefs?.baseSha??f.plan.head.sha}}})}}}};
173
- await applyWorktreeTransition(context,f.input);
174
- process.exit(9);
175
- `;
176
- const child = spawnSync(process.execPath, ['--input-type=module', '-e', script, inputPath], {
177
- encoding: 'utf8',
178
- maxBuffer: 1024 * 1024,
179
- });
180
- assert.equal(child.status, 73, `Fictional transition event=${event}; expected interruption=73.\n${child.stderr}`);
181
- // The child is confirmed exited. Advance only its synthetic fixture lock mtimes to exercise stale-lock recovery promptly.
182
- const common = gitCommonDir(f.root);
183
- for (const lock of [
184
- join(f.root, '.issue-cli/worktrees.json.lock'),
185
- join(common, 'ai-delivery/writers@1', `${digestValue(f.row.path).slice(7)}.json.lock`),
186
- ])
187
- if (existsSync(lock))
188
- utimesSync(lock, new Date(0), new Date(0));
189
- return input;
190
- }
191
- test('real process interruption resumes original capture, claim, witness, row and release without losing originals', { timeout: 0 }, async () => {
192
- for (const event of ['intent', 'authority', 'claim', 'claimed', 'owner', 'row', 'release', 'released']) {
193
- const f = await transitionFixture();
194
- try {
195
- const original = previousWriter(f.root);
196
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
197
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
198
- const plan = inspected.plan;
199
- const input = interruptedApply(f, plan, event);
200
- assert.throws(() => getIssueWorktreeStrict(17, f.root), /transition.*incomplete/iu);
201
- const completed = await applyWorktreeTransition(f.context, input);
202
- assert.equal(completed.result, 'active-resumed', event);
203
- assert.equal(getIssueWorktreeStrict(17, f.root).identity, f.row.identity);
204
- const evidence = join(dirname(completed.receiptPath), 'bytes', `${digestBytes(original.bytes).slice(7)}.bin`);
205
- assert.deepEqual(readFileSync(evidence), original.bytes, event);
206
- assert.equal(existsSync(original.path), false, event);
207
- }
208
- finally {
209
- rmSync(f.root, { force: true, recursive: true });
210
- }
211
- }
212
- });
213
- test('terminal interruption resumes removal intent, physical absence and row removal without recreating source', { timeout: 0 }, async () => {
214
- for (const event of ['removal-intent', 'removed', 'released', 'completion']) {
215
- const f = await transitionFixture({ purpose: 'merged-cleanup', disposition: 'remove' });
216
- try {
217
- const local = join(f.row.path, '.issue-cli', 'receipts');
218
- mkdirSync(local, { recursive: true });
219
- const original = Buffer.from('synthetic original terminal accounting and failed diagnostic\n');
220
- writeFileSync(join(local, 'original.json'), original);
221
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
222
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
223
- const plan = inspected.plan;
224
- const input = interruptedApply(f, plan, event);
225
- const applied = await applyWorktreeTransition(f.context, input);
226
- assert.equal(applied.result, 'removed', event);
227
- assert.equal(existsSync(f.row.path), false, event);
228
- assert.deepEqual(listWorktreesStrict(f.root), [], event);
229
- assert.deepEqual(readFileSync(join(dirname(applied.receiptPath), 'bytes', `${digestBytes(original).slice(7)}.bin`)), original, event);
230
- assert.throws(() => assertNativeIssueTrackingAdmission(17, f.root), /terminal/iu);
231
- }
232
- finally {
233
- rmSync(f.root, { force: true, recursive: true });
234
- }
235
- }
236
- });
237
- test('an earlier released attempt cannot authorize absence after a later acknowledged claim', { timeout: 0 }, async () => {
238
- const f = await transitionFixture();
239
- try {
240
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
241
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
242
- const plan = inspected.plan;
243
- interruptedApply(f, plan, 'released');
244
- const input = interruptedApply(f, plan, 'claimed');
245
- const writerPath = join(gitCommonDir(f.root), 'ai-delivery/writers@1', `${digestValue(f.row.path).slice(7)}.json`);
246
- assert.equal(existsSync(writerPath), true);
247
- const originalClaim = readFileSync(writerPath);
248
- unlinkSync(writerPath);
249
- await assert.rejects(applyWorktreeTransition(f.context, input), /latest exact.*lineage/iu);
250
- // Restore only the exact recorded claim, then resume successfully; no fabricated witness is accepted.
251
- writeFileSync(writerPath, originalClaim, { mode: 0o600 });
252
- assert.equal((await applyWorktreeTransition(f.context, input)).result, 'active-resumed');
253
- }
254
- finally {
255
- rmSync(f.root, { force: true, recursive: true });
256
- }
257
- });
258
- test('transition authority requires exact native personal and configured App identities and whole bodies', async () => {
259
- const root = repository();
260
- try {
261
- for (const change of [
262
- 'operator-id',
263
- 'operator-body',
264
- 'reviewer-actor',
265
- 'acceptance-body',
266
- 'subject',
267
- 'comment-id',
268
- ]) {
269
- const { plan, context, ids } = authorityFixture(root);
270
- const operator = nativeAuthority.comments.get(101);
271
- const reviewer = nativeAuthority.comments.get(102);
272
- if (change === 'operator-id')
273
- operator.user = { id: 99, login: 'configured-host', type: 'User' };
274
- if (change === 'operator-body')
275
- operator.body = `${String(operator.body)}\n`;
276
- if (change === 'reviewer-actor')
277
- reviewer.user = { id: 39, login: 'caller-selected-reviewer[bot]', type: 'Bot' };
278
- if (change === 'acceptance-body')
279
- reviewer.body = worktreeAcceptanceBody(plan, 999);
280
- if (change === 'subject')
281
- reviewer.issue_url = 'https://api.github.com/repos/example/widget/issues/99';
282
- if (change === 'comment-id')
283
- reviewer.id = 999;
284
- await assert.rejects(assertWorktreeTransitionNativeAuthority(context, plan, ids), /Native .* (?:missing|changed)/u);
285
- }
286
- const { plan, context, ids } = authorityFixture(root);
287
- await assertWorktreeTransitionNativeAuthority(context, plan, ids);
288
- }
289
- finally {
290
- rmSync(root, { force: true, recursive: true });
291
- }
292
- });
293
- test('only authenticated exact relinquishment revocations invalidate native acceptance', async () => {
294
- const root = repository();
295
- try {
296
- const { plan, context, ids } = authorityFixture(root);
297
- const body = JSON.stringify({
298
- schemaVersion: 'ai-delivery.worktree-relinquishment-revocation@1',
299
- planId: plan.planId,
300
- relinquishmentCommentId: 101,
301
- });
302
- const stableBody = Object.fromEntries(Object.entries(JSON.parse(body)).sort(([a], [b]) => a.localeCompare(b)));
303
- nativeAuthority.revoked = [{ body: JSON.stringify(stableBody), user: { id: 99, login: 'forged-host' } }];
304
- await assertWorktreeTransitionNativeAuthority(context, plan, ids);
305
- nativeAuthority.revoked[0].user = { id: 37, login: 'configured-host' };
306
- await assert.rejects(assertWorktreeTransitionNativeAuthority(context, plan, ids), /revoked/u);
307
- }
308
- finally {
309
- rmSync(root, { force: true, recursive: true });
310
- }
311
- });
312
- function repository() {
313
- const root = realpathSync(mkdtempSync(join(tmpdir(), 'ai-delivery-transition-')));
314
- const git = (...args) => execFileSync('git', args, { cwd: root, stdio: 'pipe' });
315
- git('init', '-b', 'main');
316
- git('config', 'user.name', 'Synthetic Operator');
317
- git('config', 'user.email', 'operator@example.test');
318
- writeFileSync(join(root, 'source.txt'), 'synthetic source\n');
319
- git('add', 'source.txt');
320
- git('commit', '-m', 'synthetic source');
321
- writeFileSync(join(root, '.git', 'info', 'exclude'), '.issue-cli/\n');
322
- git('worktree', 'add', '-b', 'issue/17', join(root, '.worktrees', 'issue-17'));
323
- return root;
324
- }
325
- async function transitionFixture(options = {}) {
326
- const root = repository();
327
- const row = entry(root);
328
- const { context } = authorityFixture(root);
329
- const configuration = {
330
- config: { ...context.config, repository: 'example/widget' },
331
- configDigest: digestValue('synthetic current configuration'),
332
- policyModulePath: join(root, 'source.txt'),
333
- remote: 'origin',
334
- };
335
- context.config = configuration.config;
336
- context.configuration = configuration;
337
- context.clients.rest.issues.get = (async () => ({
338
- data: { state: 'open' },
339
- }));
340
- mkdirSync(join(root, '.issue-cli'), { recursive: true });
341
- writeFileSync(join(root, '.issue-cli', 'worktrees.json'), JSON.stringify({ worktrees: [row] }), { mode: 0o600 });
342
- const oldDirectory = join(root, '.retained-producer');
343
- mkdirSync(oldDirectory);
344
- // Official npm 0.3.5 distribution, fixed SHA-256; only unpack/read its bytes. Never execute retained code.
345
- const archivePath = fileURLToPath(new URL('../src/fixtures/public-ai-delivery-0.3.5.tar.gz', import.meta.url));
346
- execFileSync('tar', ['-xzf', archivePath, '-C', oldDirectory]);
347
- const packageRoot = join(oldDirectory, 'package');
348
- const thisPackage = dirname(dirname(fileURLToPath(import.meta.url)));
349
- symlinkSync(join(thisPackage, 'node_modules'), join(root, 'node_modules'));
350
- const admission = buildRuntimeAdmission({
351
- cliPath: join(packageRoot, 'dist', 'cli.js'),
352
- mcpLauncherPath: join(packageRoot, 'plugins/ai-delivery/dist/mcp-launcher.js'),
353
- pluginManifestPath: join(packageRoot, 'plugins/ai-delivery/.claude-plugin/plugin.json'),
354
- packageVersion: '0.3.5',
355
- sourceArchiveSha256: digestBytes(readFileSync(archivePath)),
356
- sourceCommit: 'a'.repeat(40),
357
- configuration,
358
- });
359
- const admissionPath = join(root, '.retained-admission.json');
360
- writeFileSync(admissionPath, JSON.stringify(admission), { mode: 0o600 });
361
- const runtimeEntryPath = join(thisPackage, 'dist', 'cli.js');
362
- const currentRuntime = buildRuntimeAdmission({
363
- cliPath: runtimeEntryPath,
364
- mcpLauncherPath: join(thisPackage, 'plugins/ai-delivery/dist/mcp-launcher.js'),
365
- pluginManifestPath: join(thisPackage, 'plugins/ai-delivery/.claude-plugin/plugin.json'),
366
- packageVersion: JSON.parse(readFileSync(join(thisPackage, 'package.json'), 'utf8'))
367
- .version,
368
- sourceArchiveSha256: digestValue('synthetic reviewed current archive'),
369
- sourceCommit: 'b'.repeat(40),
370
- configuration,
371
- });
372
- const common = gitCommonDir(root);
373
- mkdirSync(join(common, 'ai-delivery'), { recursive: true, mode: 0o700 });
374
- writeFileSync(join(common, 'ai-delivery', 'runtime-admission.json'), JSON.stringify(currentRuntime), { mode: 0o600 });
375
- const sha = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: row.path, encoding: 'utf8' }).trim();
376
- const tree = execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { cwd: row.path, encoding: 'utf8' }).trim();
377
- const sourceDigest = digestBytes(readFileSync(join(row.path, 'source.txt')));
378
- const policy = {
379
- schemaVersion: 'RepositoryDeliveryPolicy@1',
380
- classifyExactRange: () => {
381
- const content = {
382
- schemaVersion: 'ai-delivery.policy-evidence@1',
383
- repository: 'example/widget',
384
- base: { sha, tree },
385
- head: { sha, tree },
386
- configDigest: configuration.configDigest,
387
- policyDigest: sourceDigest,
388
- producer: 'synthetic-history-policy',
389
- opaquePayload: 'synthetic history',
390
- artifacts: [{ digest: sourceDigest, path: 'source.txt', producer: 'synthetic-history-policy' }],
391
- };
392
- return {
393
- policyDigest: sourceDigest,
394
- policyEvidence: { ...content, evidenceId: digestValue(content) },
395
- risk: 'standard',
396
- requiredStages: [
397
- {
398
- id: 'source',
399
- resourceClass: 'source_only',
400
- commands: [],
401
- attestationKey: 'source.txt',
402
- dependsOn: [],
403
- semanticInputKeys: ['source'],
404
- },
405
- ],
406
- };
407
- },
408
- };
409
- const classification = classifyRepositoryExactRange({
410
- repoRoot: row.path,
411
- repository: 'example/widget',
412
- base: { sha, tree },
413
- head: { sha, tree },
414
- changedPaths: [],
415
- configDigest: configuration.configDigest,
416
- policySourcePath: 'source.txt',
417
- policy,
418
- });
419
- const producerDigest = retainedWorktreeTransitionProducerDigest(join(packageRoot, 'dist'));
420
- const stageInput = createRepositoryStageInput({
421
- classification,
422
- stageId: 'source',
423
- semanticInputs: [{ key: 'source', digest: sourceDigest }],
424
- upstream: [],
425
- environmentDigest: digestValue({
426
- arch: process.arch,
427
- node: process.version,
428
- path: process.env.PATH ?? '',
429
- platform: process.platform,
430
- worktreeDigest: digestValue(row.path),
431
- producerDigest,
432
- }),
433
- });
434
- const receipt = createRepositoryStageReceipt({
435
- classification,
436
- stageInput,
437
- commands: [],
438
- artifacts: [{ digest: sourceDigest, path: 'source.txt' }],
439
- startedAt: '2026-01-01T00:00:00.000Z',
440
- completedAt: '2026-01-01T00:00:00.000Z',
441
- });
442
- writeRepositoryStageCheckpoint({ gitCommonDir: common, repoRoot: row.path, receipt });
443
- const runContent = {
444
- schemaVersion: 'ai-delivery.run@3',
445
- completedAt: '2026-01-01T00:00:00.000Z',
446
- classification,
447
- aggregate: createRepositoryStageAggregate({ classification, receipts: [receipt] }),
448
- stageReceipts: [receipt],
449
- writer: { worktreeDigest: digestValue(row.path), producerDigest },
450
- };
451
- const runs = join(common, 'ai-delivery', 'runs@2', digestValue(row.path).slice(7));
452
- mkdirSync(runs, { recursive: true, mode: 0o700 });
453
- writeFileSync(join(runs, `${sha}.json`), JSON.stringify({ ...runContent, manifestId: digestValue(runContent) }), {
454
- mode: 0o600,
455
- });
456
- const nativePr = {
457
- number: 23,
458
- head: { sha, ref: row.branch, repo: { full_name: 'example/widget' } },
459
- base: { sha, ref: 'main', repo: { full_name: 'example/widget' } },
460
- merge_commit_sha: sha,
461
- merged: true,
462
- user: { login: 'synthetic-original-author' },
463
- };
464
- if (options.purpose === 'merged-cleanup') {
465
- row.status = 'pr-published';
466
- row.prNumber = 23;
467
- writeFileSync(join(root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [row] }), { mode: 0o600 });
468
- execFileSync('git', ['remote', 'add', 'origin', 'https://github.com/example/widget.git'], { cwd: root });
469
- execFileSync('git', ['update-ref', 'refs/remotes/origin/main', sha], { cwd: root });
470
- context.clients.rest.issues.get = (async () => ({
471
- data: { state: 'closed' },
472
- }));
473
- context.clients.rest.pulls = {
474
- get: async () => ({ data: nativePr }),
475
- };
476
- context.clients.rest.repos = {
477
- getBranch: async ({ branch }) => ({ data: { name: branch, commit: { sha } } }),
478
- };
479
- context.clients.graphql = (async () => ({
480
- repository: {
481
- pullRequest: {
482
- closingIssuesReferences: {
483
- nodes: [{ number: 17, repository: { nameWithOwner: 'example/widget' } }],
484
- pageInfo: { hasNextPage: false },
485
- },
486
- },
487
- },
488
- }));
489
- for (const id of [101, 102])
490
- nativeAuthority.comments.get(id).issue_url = 'https://api.github.com/repos/example/widget/issues/23';
491
- if (options.held)
492
- nativeAuthority.comments.set(103, {
493
- id: 103,
494
- issue_url: 'https://api.github.com/repos/example/widget/issues/23',
495
- body: 'Synthetic retained source hold; transition does not release it.',
496
- user: { id: 37, login: 'configured-host', type: 'User' },
497
- });
498
- }
499
- return {
500
- root,
501
- row,
502
- context,
503
- runtimeEntryPath,
504
- admissionPath,
505
- archivePath,
506
- nativePr,
507
- inspectInput: {
508
- issueNumber: 17,
509
- purpose: options.purpose ?? 'active-resume',
510
- disposition: options.disposition ?? 'retain',
511
- ...(options.held ? { retainedHoldCommentIds: [103] } : {}),
512
- retainedAdmissionPath: admissionPath,
513
- retainedArchivePath: archivePath,
514
- runtimeEntryPath,
515
- },
516
- };
517
- }
518
- test('actual retained public bytes support one explicit independently accepted active resume', async () => {
519
- const f = await transitionFixture();
520
- try {
521
- const inspection = await inspectWorktreeTransition(f.context, f.inspectInput);
522
- assert.equal(inspection.ready, true, inspection.blockers.join('; '));
523
- const plan = inspection.plan;
524
- assert.ok(worktreeRelinquishmentBody(plan).length < 65_000, 'native authority body must fit the comment boundary while binding the full plan');
525
- for (const path of [f.admissionPath, f.archivePath, plan.closure.admission.cliPath])
526
- assert.ok(plan.inventory.some((file) => file.source === path), `retained operational producer original omitted: ${path}`);
527
- const planPath = join(f.root, 'approved-plan.json');
528
- writeFileSync(planPath, stableJson(plan));
529
- nativeAuthority.comments.get(101).body = worktreeRelinquishmentBody(plan);
530
- nativeAuthority.comments.get(102).body = worktreeAcceptanceBody(plan, 101);
531
- const applied = await applyWorktreeTransition(f.context, {
532
- authority: 'worktree:transition',
533
- planPath,
534
- expectedPlanId: plan.planId,
535
- relinquishmentCommentId: 101,
536
- acceptanceCommentId: 102,
537
- runtimeEntryPath: f.runtimeEntryPath,
538
- });
539
- assert.equal(applied.result, 'active-resumed');
540
- assert.equal(getIssueWorktreeStrict(17, f.root).identity, f.row.identity);
541
- assert.equal(digestBytes(readFileSync(f.admissionPath)), plan.closure.admissionBytesDigest);
542
- const replayed = await applyWorktreeTransition(f.context, {
543
- authority: 'worktree:transition',
544
- planPath,
545
- expectedPlanId: plan.planId,
546
- relinquishmentCommentId: 101,
547
- acceptanceCommentId: 102,
548
- runtimeEntryPath: f.runtimeEntryPath,
549
- });
550
- assert.equal(replayed.replayed, true);
551
- }
552
- finally {
553
- rmSync(f.root, { force: true, recursive: true });
554
- }
555
- });
556
- test('completed replay checks original attempt bytes, actual writer absence, row and owner witness', { timeout: 0 }, async () => {
557
- const f = await transitionFixture();
558
- try {
559
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
560
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
561
- const plan = inspected.plan;
562
- const input = approvedFixturePlan(f, plan);
563
- const completed = await applyWorktreeTransition(f.context, input);
564
- const directory = dirname(completed.receiptPath);
565
- const attempt = readdirSync(join(directory, 'attempts')).find((name) => name.endsWith('.authority.json'));
566
- const authority = JSON.parse(readFileSync(join(directory, 'attempts', attempt), 'utf8'));
567
- const bytesPath = join(directory, 'bytes', `${authority.data.bytesDigest.slice(7)}.bin`);
568
- const bytes = readFileSync(bytesPath);
569
- writeFileSync(bytesPath, 'corrupt preserved native authority', { mode: 0o600 });
570
- await assert.rejects(applyWorktreeTransition(f.context, input), /preserved.*corrupt/iu);
571
- writeFileSync(bytesPath, bytes, { mode: 0o600 });
572
- const writer = previousWriter(f.root);
573
- await assert.rejects(applyWorktreeTransition(f.context, input), /writer absence postcondition/iu);
574
- assert.deepEqual(readFileSync(writer.path), writer.bytes, 'replay must not signal or replace a writer');
575
- unlinkSync(writer.path);
576
- const registry = join(f.root, '.issue-cli/worktrees.json');
577
- const registryBytes = readFileSync(registry);
578
- writeFileSync(registry, JSON.stringify({ worktrees: [{ ...f.row, status: 'stale' }] }), { mode: 0o600 });
579
- await assert.rejects(applyWorktreeTransition(f.context, input), /row|registry/iu);
580
- writeFileSync(registry, registryBytes, { mode: 0o600 });
581
- const owners = join(gitCommonDir(f.root), 'ai-delivery/worktree-owners');
582
- const witness = readdirSync(owners).find((name) => name.endsWith('.json') && !name.includes('.transition.'));
583
- const witnessPath = join(owners, witness);
584
- const witnessBytes = readFileSync(witnessPath);
585
- writeFileSync(witnessPath, '{}', { mode: 0o600 });
586
- await assert.rejects(applyWorktreeTransition(f.context, input), /owner witness/iu);
587
- writeFileSync(witnessPath, witnessBytes, { mode: 0o600 });
588
- assert.equal((await applyWorktreeTransition(f.context, input)).replayed, true);
589
- }
590
- finally {
591
- rmSync(f.root, { force: true, recursive: true });
592
- }
593
- });
594
- test('inspection and accepted apply refuse dirty source, wrong repository and changed canonical row without writing intent', { timeout: 0 }, async () => {
595
- const f = await transitionFixture();
596
- try {
597
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
598
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
599
- const input = approvedFixturePlan(f, inspected.plan);
600
- writeFileSync(join(f.row.path, 'untracked.txt'), 'dirty source\n');
601
- assert.equal((await inspectWorktreeTransition(f.context, f.inspectInput)).ready, false);
602
- await assert.rejects(applyWorktreeTransition(f.context, input), /dirty|clean|uncommitted/iu);
603
- unlinkSync(join(f.row.path, 'untracked.txt'));
604
- const repository = f.context.config.repository;
605
- f.context.config.repository = 'example/another';
606
- assert.match((await inspectWorktreeTransition(f.context, f.inspectInput)).blockers.join('; '), /repository/iu);
607
- await assert.rejects(applyWorktreeTransition(f.context, input), /repository/iu);
608
- f.context.config.repository = repository;
609
- writeFileSync(join(f.root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [{ ...f.row, identity: 'another-owner' }] }), { mode: 0o600 });
610
- await assert.rejects(applyWorktreeTransition(f.context, input), /row|ownership|owner/iu);
611
- assert.equal(existsSync(join(gitCommonDir(f.root), 'ai-delivery/worktree-owners/issue-17.transition.json')), false);
612
- }
613
- finally {
614
- rmSync(f.root, { force: true, recursive: true });
615
- }
616
- });
617
- test('inspection reports unsupported operative v2 and missing or corrupt required historical originals', { timeout: 0 }, async () => {
618
- const f = await transitionFixture();
619
- try {
620
- const unsupported = join(gitCommonDir(f.root), 'issue-cli/verification-stages/v2');
621
- mkdirSync(unsupported, { recursive: true });
622
- assert.match((await inspectWorktreeTransition(f.context, f.inspectInput)).blockers.join('; '), /unsupported operative.*v2/iu);
623
- rmSync(unsupported, { recursive: true });
624
- const directory = join(f.root, '.issue-cli/issues/17/terminal');
625
- mkdirSync(directory, { recursive: true });
626
- const original = Buffer.from('original failed diagnostic\n');
627
- writeFileSync(join(directory, 'manifest.json'), JSON.stringify({
628
- schemaVersion: 'issue-cli.terminal-evidence@1',
629
- files: [{ name: 'failed.txt', size: original.length, sha256: digestBytes(original).slice(7) }],
630
- }));
631
- assert.equal((await inspectWorktreeTransition(f.context, f.inspectInput)).ready, false, 'missing original');
632
- writeFileSync(join(directory, 'failed.txt'), 'corrupt');
633
- assert.match((await inspectWorktreeTransition(f.context, f.inspectInput)).blockers.join('; '), /original bytes/iu);
634
- writeFileSync(join(directory, 'failed.txt'), original);
635
- assert.equal((await inspectWorktreeTransition(f.context, f.inspectInput)).ready, true);
636
- }
637
- finally {
638
- rmSync(f.root, { force: true, recursive: true });
639
- }
640
- });
641
- test('terminal inspection and accepted apply reject wrong native repository and PR lineage drift', { timeout: 0 }, async () => {
642
- const f = await transitionFixture({ purpose: 'merged-cleanup' });
643
- try {
644
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
645
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
646
- const input = approvedFixturePlan(f, inspected.plan);
647
- f.nativePr.head.repo.full_name = 'example/another';
648
- assert.match((await inspectWorktreeTransition(f.context, f.inspectInput)).blockers.join('; '), /repository.*closing issue/iu);
649
- await assert.rejects(applyWorktreeTransition(f.context, input), /repository.*closing issue/iu);
650
- f.nativePr.head.repo.full_name = 'example/widget';
651
- f.nativePr.user.login = 'changed-original-author';
652
- await assert.rejects(applyWorktreeTransition(f.context, input), /native PR lineage.*drifted/iu);
653
- f.nativePr.user.login = 'synthetic-original-author';
654
- Object.assign(f.nativePr, { body: 'Refs #17' });
655
- f.context.clients.graphql = (async () => ({
656
- repository: { pullRequest: { closingIssuesReferences: { nodes: [], pageInfo: { hasNextPage: false } } } },
657
- }));
658
- let timelineReads = 0;
659
- f.context.clients.rest.issues.listEventsForTimeline = (async () => {
660
- timelineReads += 1;
661
- return { data: [] };
662
- });
663
- assert.match((await inspectWorktreeTransition(f.context, f.inspectInput)).blockers.join('; '), /repository.*closing issue/iu);
664
- await assert.rejects(applyWorktreeTransition(f.context, input), /repository.*closing issue/iu);
665
- assert.equal(timelineReads, 0, 'legacy transition purposes never use the continuation-specific Refs alternative');
666
- }
667
- finally {
668
- rmSync(f.root, { force: true, recursive: true });
669
- }
670
- });
671
- test('closure check refuses live owners, reused root PIDs and live process groups without signaling', () => {
672
- const root = repository();
673
- try {
674
- const original = previousWriter(root);
675
- const previous = JSON.parse(original.bytes.toString('utf8'));
676
- const { stateId: _id, ...content } = previous;
677
- const identity = execFileSync('/bin/ps', ['-p', String(process.pid), '-o', 'lstart='], {
678
- encoding: 'utf8',
679
- env: { ...process.env, LC_ALL: 'C' },
680
- }).trim();
681
- for (const reason of ['owner', 'reused-pid', 'group']) {
682
- const state = {
683
- ...content,
684
- owner: reason === 'owner' ? { pid: process.pid, identity } : content.owner,
685
- command: reason === 'owner'
686
- ? { phase: 'idle' }
687
- : {
688
- phase: 'running',
689
- root: { pid: reason === 'reused-pid' ? process.pid : 2_000_000_000, identity: 'unrelated old birth' },
690
- tracked: reason === 'group'
691
- ? [
692
- {
693
- pid: 2_000_000_001,
694
- identity: 'old birth',
695
- pgid: Number(execFileSync('/bin/ps', ['-p', String(process.pid), '-o', 'pgid='], {
696
- encoding: 'utf8',
697
- }).trim()),
698
- },
699
- ]
700
- : [],
701
- },
702
- };
703
- assert.throws(() => assertWorktreeTransitionWriterQuiescent(entry(root).path, Buffer.from(stableJson({ ...state, stateId: digestValue(state) }))), /live verification|process-group absence/iu);
704
- process.kill(process.pid, 0);
705
- }
706
- assert.deepEqual(readFileSync(original.path), original.bytes);
707
- }
708
- finally {
709
- rmSync(root, { force: true, recursive: true });
710
- }
711
- });
712
- test('supported closure requires a run for the exact retained head and tree', async () => {
713
- const f = await transitionFixture();
714
- try {
715
- writeFileSync(join(f.row.path, 'new-source.txt'), 'a newer synthetic retained source\n');
716
- execFileSync('git', ['add', 'new-source.txt'], { cwd: f.row.path });
717
- execFileSync('git', ['commit', '-m', 'new synthetic head'], { cwd: f.row.path });
718
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
719
- assert.equal(inspected.ready, false, 'old producer-bound run cannot close a newer unverified retained source');
720
- assert.match(inspected.blockers.join('; '), /exact.*(?:head|source)|closure/iu);
721
- }
722
- finally {
723
- rmSync(f.root, { force: true, recursive: true });
724
- }
725
- });
726
- test('apply revalidates the exact operational run inventory despite native acceptance of local JSON', async () => {
727
- const f = await transitionFixture();
728
- try {
729
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
730
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
731
- const { planId: _originalId, ...content } = inspected.plan;
732
- content.closure = { ...content.closure, runManifestIds: [digestValue('unrelated run')] };
733
- const plan = { ...content, planId: digestValue(content) };
734
- const planPath = join(f.root, 'changed-plan.json');
735
- writeFileSync(planPath, stableJson(plan));
736
- nativeAuthority.comments.get(101).body = worktreeRelinquishmentBody(plan);
737
- nativeAuthority.comments.get(102).body = worktreeAcceptanceBody(plan, 101);
738
- await assert.rejects(applyWorktreeTransition(f.context, {
739
- authority: 'worktree:transition',
740
- planPath,
741
- expectedPlanId: plan.planId,
742
- relinquishmentCommentId: 101,
743
- acceptanceCommentId: 102,
744
- runtimeEntryPath: f.runtimeEntryPath,
745
- }), /run.*inventory|operational.*closure/iu);
746
- }
747
- finally {
748
- rmSync(f.root, { force: true, recursive: true });
749
- }
750
- });
751
- test('terminal transition retains source, holds and original PR identity and permanently rejects ordinary resume', async () => {
752
- const f = await transitionFixture({ purpose: 'merged-cleanup', held: true });
753
- try {
754
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
755
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
756
- const plan = inspected.plan;
757
- const applied = await applyWorktreeTransition(f.context, approvedFixturePlan(f, plan));
758
- assert.equal(applied.result, 'retained');
759
- assert.equal(existsSync(f.row.path), true);
760
- assert.deepEqual(listWorktreesStrict(f.root), [{ ...f.row, status: 'merged' }]);
761
- assert.deepEqual(plan.retainedHoldCommentIds, [103]);
762
- assert.match(String(nativeAuthority.comments.get(103).body), /does not release/);
763
- await assert.rejects(prepareIssueWorktree({ repoRoot: f.root, issueNumber: 17, identity: 'configured-host' }), /terminal/iu);
764
- const hold = plan.holdEvidence[0];
765
- assert.equal(digestBytes(readFileSync(join(dirname(applied.receiptPath), 'bytes', `${hold.digest.slice(7)}.bin`))), hold.digest);
766
- }
767
- finally {
768
- rmSync(f.root, { force: true, recursive: true });
769
- }
770
- });
771
- test('unheld terminal removal checks native remote refs and completed replay rejects recreated source', { timeout: 0 }, async () => {
772
- const f = await transitionFixture({ purpose: 'merged-cleanup', disposition: 'remove' });
773
- try {
774
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
775
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
776
- const plan = inspected.plan;
777
- const input = approvedFixturePlan(f, plan);
778
- const applied = await applyWorktreeTransition(f.context, input);
779
- assert.equal(applied.result, 'removed');
780
- assert.equal(existsSync(f.row.path), false);
781
- assert.deepEqual(listWorktreesStrict(f.root), []);
782
- assert.equal((await applyWorktreeTransition(f.context, input)).replayed, true);
783
- execFileSync('git', ['worktree', 'add', f.row.path, f.row.branch], { cwd: f.root });
784
- await assert.rejects(applyWorktreeTransition(f.context, input), /recreated|absence postcondition/iu);
785
- assert.throws(() => assertNativeIssueTrackingAdmission(17, f.root), /terminal/iu);
786
- }
787
- finally {
788
- rmSync(f.root, { force: true, recursive: true });
789
- }
790
- });
791
- test('terminal inspection rejects held removal and configured reviewer matching the native PR author', async () => {
792
- for (const reason of ['held', 'reviewer-author']) {
793
- const f = await transitionFixture({ purpose: 'merged-cleanup', disposition: 'remove', held: reason === 'held' });
794
- try {
795
- if (reason === 'reviewer-author')
796
- f.nativePr.user.login = nativeAuthority.reviewer;
797
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
798
- assert.equal(inspected.ready, false, reason);
799
- assert.match(inspected.blockers.join('; '), reason === 'held' ? /disposition/iu : /native PR author/iu);
800
- assert.equal(existsSync(join(gitCommonDir(f.root), 'ai-delivery/worktree-owners/issue-17.transition.json')), false);
801
- }
802
- finally {
803
- rmSync(f.root, { force: true, recursive: true });
804
- }
805
- }
806
- });
807
- function entry(root, status = 'active') {
808
- return {
809
- branch: 'issue/17',
810
- createdAt: '2026-01-01T00:00:00.000Z',
811
- identity: 'synthetic-author',
812
- issueNumber: 17,
813
- path: join(root, '.worktrees', 'issue-17'),
814
- status,
815
- type: 'issue',
816
- updatedAt: '2026-01-01T00:00:00.000Z',
817
- };
818
- }
819
- function interruptTransition(root, row) {
820
- // A truncated intent is also an incomplete transition and must fail closed.
821
- const path = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', `issue-${String(row.issueNumber)}.transition.json`);
822
- writeFileSync(path, '{', { mode: 0o600 });
823
- }
824
- test('ordinary ownership and resume refuse an interrupted transition even after the owner witness exists', async () => {
825
- const root = repository();
826
- try {
827
- const row = entry(root);
828
- await addWorktreeEntry(row, root);
829
- assert.equal(getIssueWorktreeStrict(17, root).path, row.path);
830
- interruptTransition(root, row);
831
- assert.throws(() => getIssueWorktreeStrict(17, root), /Worktree transition.*(?:pending|incomplete|terminal)/iu);
832
- await assert.rejects(prepareIssueWorktree({ identity: row.identity, issueNumber: 17, repoRoot: root }), /Worktree transition.*(?:pending|incomplete|terminal)/iu);
833
- assert.deepEqual(listWorktreesStrict(root), [row]);
834
- }
835
- finally {
836
- rmSync(root, { force: true, recursive: true });
837
- }
838
- });
839
- test('registration cannot reactivate a merged issue through an interrupted transition', async () => {
840
- const root = repository();
841
- try {
842
- const row = { ...entry(root, 'merged'), prNumber: 23 };
843
- await addWorktreeEntry(row, root);
844
- const registry = join(root, '.issue-cli', 'worktrees.json');
845
- const original = readFileSync(registry);
846
- interruptTransition(root, row);
847
- await assert.rejects(addWorktreeEntry(entry(root), root), /Worktree transition.*(?:pending|incomplete|terminal)/iu);
848
- assert.deepEqual(readFileSync(registry), original);
849
- }
850
- finally {
851
- rmSync(root, { force: true, recursive: true });
852
- }
853
- });
854
- test('ordinary ownership still refuses a legacy row without a witness', () => {
855
- const root = repository();
856
- try {
857
- mkdirSync(join(root, '.issue-cli'), { mode: 0o700 });
858
- writeFileSync(join(root, '.issue-cli', 'worktrees.json'), JSON.stringify({ worktrees: [entry(root)] }), {
859
- mode: 0o600,
860
- });
861
- assert.throws(() => getIssueWorktreeStrict(17, root), /ownership witness/iu);
862
- }
863
- finally {
864
- rmSync(root, { force: true, recursive: true });
865
- }
866
- });
867
- test('direct tracking admission refuses pending intent after its canonical row is absent', async () => {
868
- const root = repository();
869
- try {
870
- const row = entry(root);
871
- await addWorktreeEntry(row, root);
872
- writeFileSync(join(root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [] }), { mode: 0o600 });
873
- interruptTransition(root, row);
874
- assert.throws(() => assertNativeIssueTrackingAdmission(17, root), /Worktree transition.*(?:pending|incomplete|terminal)/iu);
875
- await assert.rejects(prepareIssueWorktree({ identity: row.identity, issueNumber: 17, repoRoot: root }), /Worktree transition.*(?:pending|incomplete|terminal)/iu);
876
- }
877
- finally {
878
- rmSync(root, { force: true, recursive: true });
879
- }
880
- });
881
- test('absent-row admission refuses valid JSON with a non-issue or mismatched embedded row', async () => {
882
- const root = repository();
883
- try {
884
- const row = entry(root);
885
- await addWorktreeEntry(row, root);
886
- writeFileSync(join(root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [] }), { mode: 0o600 });
887
- const path = join(gitCommonDir(root), 'ai-delivery/worktree-owners/issue-17.transition.json');
888
- for (const invalid of [{ type: 'pr' }, { ...row, issueNumber: 18 }, { ...row, issueNumber: undefined }]) {
889
- writeFileSync(path, JSON.stringify({ plan: { row: invalid } }), { mode: 0o600 });
890
- assert.throws(() => assertNativeIssueTrackingAdmission(17, root), /transition.*(?:incomplete|unreadable)/iu);
891
- await assert.rejects(prepareIssueWorktree({ identity: row.identity, issueNumber: 17, repoRoot: root }), /transition.*(?:incomplete|unreadable)/iu);
892
- }
893
- }
894
- finally {
895
- rmSync(root, { recursive: true, force: true });
896
- }
897
- });
898
- test('native acceptance cannot bypass terminal or active purpose and complete PR-set predicates', { timeout: 0 }, async () => {
899
- for (const reason of ['empty-terminal-lineage', 'active-merged-lineage', 'active-merged-row']) {
900
- const f = await transitionFixture({ purpose: 'merged-cleanup' });
901
- try {
902
- const inspected = await inspectWorktreeTransition(f.context, f.inspectInput);
903
- assert.equal(inspected.ready, true, inspected.blockers.join('; '));
904
- const { planId: _id, ...content } = inspected.plan;
905
- if (reason === 'empty-terminal-lineage')
906
- content.lineage = [];
907
- else {
908
- content.purpose = 'active-resume';
909
- content.terminalPrNumber = null;
910
- f.context.clients.rest.issues.get = (async () => ({
911
- data: { state: 'open' },
912
- }));
913
- for (const id of [101, 102])
914
- nativeAuthority.comments.get(id).issue_url = 'https://api.github.com/repos/example/widget/issues/17';
915
- if (reason === 'active-merged-row') {
916
- content.row = { ...content.row, status: 'merged' };
917
- content.lineage = [];
918
- writeFileSync(join(f.root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [content.row] }), {
919
- mode: 0o600,
920
- });
921
- }
922
- }
923
- const plan = { ...content, planId: digestValue(content) };
924
- await assert.rejects(applyWorktreeTransition(f.context, approvedFixturePlan(f, plan)), /lineage|active resume|terminal|PR.*set/iu, reason);
925
- assert.equal(existsSync(join(gitCommonDir(f.root), 'ai-delivery/worktree-owners/issue-17.transition.json')), false);
926
- }
927
- finally {
928
- rmSync(f.root, { recursive: true, force: true });
929
- }
930
- }
931
- });
932
- test('transition registry rejects a foreign issue row sharing its exact path or branch', async () => {
933
- const root = repository();
934
- try {
935
- const { plan } = authorityFixture(root);
936
- mkdirSync(join(root, '.issue-cli'), { recursive: true });
937
- for (const conflict of ['path', 'branch']) {
938
- const other = { ...entry(root), issueNumber: 18, path: join(root, '.worktrees', 'issue-18'), branch: 'issue/18' };
939
- if (conflict === 'path')
940
- other.path = plan.row.path;
941
- else
942
- other.branch = plan.row.branch;
943
- writeFileSync(join(root, '.issue-cli/worktrees.json'), JSON.stringify({ worktrees: [plan.row, other] }), {
944
- mode: 0o600,
945
- });
946
- await assert.rejects(withWorktreeTransitionRegistry(plan, async () => undefined), /colli|conflict/iu);
947
- }
948
- }
949
- finally {
950
- rmSync(root, { force: true, recursive: true });
951
- }
952
- });
953
- test('historical inventory preserves unknown schemas and failed diagnostics byte for byte', () => {
954
- const root = repository();
955
- try {
956
- const historical = join(root, '.issue-cli', 'issues', '17', 'review', 'historical-head');
957
- mkdirSync(historical, { recursive: true });
958
- const original = Buffer.from('{"schemaVersion":"historical.unknown@7","failed":true,"accounting":{"elapsed":51}}\n');
959
- writeFileSync(join(historical, 'failed-diagnostic.json'), original);
960
- const inventory = inventoryTransitionEvidence(root, entry(root));
961
- const item = inventory.find((file) => file.path.endsWith('failed-diagnostic.json'));
962
- assert.ok(item);
963
- const output = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', 'preserved');
964
- preserveTransitionEvidence(output, inventory);
965
- assert.deepEqual(readFileSync(join(output, `${item.digest.slice(7)}.bin`)), original);
966
- assert.deepEqual(readFileSync(join(historical, 'failed-diagnostic.json')), original);
967
- }
968
- finally {
969
- rmSync(root, { force: true, recursive: true });
970
- }
971
- });
972
- test('preservation rejects drift without replacing an already preserved original', () => {
973
- const root = repository();
974
- try {
975
- const historical = join(root, '.issue-cli', 'issues', '17');
976
- mkdirSync(historical, { recursive: true });
977
- const source = join(historical, 'receipt.json');
978
- writeFileSync(source, 'original historical bytes');
979
- const inventory = inventoryTransitionEvidence(root, entry(root));
980
- const output = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', 'preserved');
981
- preserveTransitionEvidence(output, inventory);
982
- writeFileSync(source, 'changed historical bytes');
983
- assert.throws(() => preserveTransitionEvidence(output, inventory), /historical evidence.*drift/iu);
984
- assert.deepEqual(readFileSync(join(output, `${inventory[0].digest.slice(7)}.bin`)), Buffer.from('original historical bytes'));
985
- }
986
- finally {
987
- rmSync(root, { force: true, recursive: true });
988
- }
989
- });
990
- test('inventory preserves worktree-local original receipts and accounting before terminal removal', () => {
991
- const root = repository();
992
- try {
993
- const local = join(entry(root).path, '.issue-cli', 'receipts', 'verification');
994
- mkdirSync(local, { recursive: true });
995
- const path = join(local, 'historical.json');
996
- const bytes = Buffer.from('{"schemaVersion":"legacy.receipt@2","failedDiagnostic":true,"accounting":{"runtimeMs":771}}\n');
997
- writeFileSync(path, bytes);
998
- const inventory = inventoryTransitionEvidence(root, entry(root));
999
- const selected = inventory.find((file) => file.source === path);
1000
- assert.ok(selected, 'worktree-local original receipt was omitted');
1001
- const output = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', 'preserved');
1002
- preserveTransitionEvidence(output, inventory);
1003
- assert.deepEqual(readFileSync(join(output, `${selected.digest.slice(7)}.bin`)), bytes);
1004
- }
1005
- finally {
1006
- rmSync(root, { force: true, recursive: true });
1007
- }
1008
- });
1009
- function previousWriter(root, phase = 'idle') {
1010
- const worktree = join(root, '.worktrees', 'issue-17');
1011
- const worktreeDigest = digestValue(realpathSync(worktree));
1012
- const content = {
1013
- schemaVersion: 'ai-delivery.verification-writer@1',
1014
- writerId: 'c9d58755-17b2-4fc9-9218-90f92c7642e1',
1015
- worktreeDigest,
1016
- owner: { pid: 2_000_000_000, identity: 'synthetic deceased process' },
1017
- command: { phase },
1018
- };
1019
- const path = join(gitCommonDir(root), 'ai-delivery', 'writers@1', `${worktreeDigest.slice(7)}.json`);
1020
- mkdirSync(join(gitCommonDir(root), 'ai-delivery', 'writers@1'), { mode: 0o700, recursive: true });
1021
- const bytes = Buffer.from(`${JSON.stringify({ ...content, stateId: digestValue(content) }, null, 2)}\n`);
1022
- writeFileSync(path, bytes, { mode: 0o600 });
1023
- return { path, bytes };
1024
- }
1025
- test('transition lease preserves original bytes before claim and records release before deletion', async () => {
1026
- const root = repository();
1027
- try {
1028
- const original = previousWriter(root);
1029
- const events = [];
1030
- const writerId = '1b75f48b-0746-43a5-bd6d-9ddc17848c9a';
1031
- await withWorktreeTransitionWriterLease({
1032
- repoRoot: entry(root).path,
1033
- writerId,
1034
- beforeClaim: ({ previousBytes }) => {
1035
- assert.deepEqual(previousBytes, original.bytes);
1036
- assert.deepEqual(readFileSync(original.path), original.bytes);
1037
- events.push('preserved');
1038
- },
1039
- recordClaim: (bytes) => {
1040
- assert.deepEqual(events, ['preserved']);
1041
- assert.deepEqual(readFileSync(original.path), original.bytes);
1042
- assert.equal(JSON.parse(bytes.toString()).writerId, writerId);
1043
- events.push('claimed');
1044
- },
1045
- recordRelease: (bytes) => {
1046
- assert.deepEqual(events, ['preserved', 'claimed', 'operation']);
1047
- assert.deepEqual(readFileSync(original.path), bytes);
1048
- events.push('released');
1049
- },
1050
- }, async () => {
1051
- assert.equal(JSON.parse(readFileSync(original.path, 'utf8')).writerId, writerId);
1052
- events.push('operation');
1053
- });
1054
- assert.deepEqual(events, ['preserved', 'claimed', 'operation', 'released']);
1055
- assert.throws(() => readFileSync(original.path), { code: 'ENOENT' });
1056
- }
1057
- finally {
1058
- rmSync(root, { force: true, recursive: true });
1059
- }
1060
- });
1061
- test('failed intent preservation cannot overwrite the original writer', async () => {
1062
- const root = repository();
1063
- try {
1064
- const original = previousWriter(root);
1065
- await assert.rejects(withWorktreeTransitionWriterLease({
1066
- repoRoot: entry(root).path,
1067
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1068
- beforeClaim: () => {
1069
- throw new Error('synthetic intent failure');
1070
- },
1071
- recordClaim: () => assert.fail('claim must not be reached'),
1072
- recordRelease: () => assert.fail('release must not be reached'),
1073
- }, async () => assert.fail('operation must not be reached')), /synthetic intent failure/u);
1074
- assert.deepEqual(readFileSync(original.path), original.bytes);
1075
- }
1076
- finally {
1077
- rmSync(root, { force: true, recursive: true });
1078
- }
1079
- });
1080
- test('failed claim evidence cannot replace the preserved writer', async () => {
1081
- const root = repository();
1082
- try {
1083
- const original = previousWriter(root);
1084
- await assert.rejects(withWorktreeTransitionWriterLease({
1085
- repoRoot: entry(root).path,
1086
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1087
- beforeClaim: () => undefined,
1088
- recordClaim: () => {
1089
- throw new Error('synthetic claim failure');
1090
- },
1091
- recordRelease: () => assert.fail('release must not be reached'),
1092
- }, async () => assert.fail('operation must not be reached')), /synthetic claim failure/u);
1093
- assert.deepEqual(readFileSync(original.path), original.bytes);
1094
- }
1095
- finally {
1096
- rmSync(root, { force: true, recursive: true });
1097
- }
1098
- });
1099
- test('transition refuses an interrupted unknown launch without changing its state', async () => {
1100
- const root = repository();
1101
- try {
1102
- const original = previousWriter(root, 'starting');
1103
- await assert.rejects(withWorktreeTransitionWriterLease({
1104
- repoRoot: entry(root).path,
1105
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1106
- beforeClaim: () => assert.fail('unknown ownership must refuse before preservation'),
1107
- recordClaim: () => assert.fail('unknown ownership must refuse before claim'),
1108
- recordRelease: () => assert.fail('unknown ownership must refuse before release'),
1109
- }, async () => assert.fail('operation must not be reached')), /unknown command ownership/u);
1110
- assert.deepEqual(readFileSync(original.path), original.bytes);
1111
- }
1112
- finally {
1113
- rmSync(root, { force: true, recursive: true });
1114
- }
1115
- });
1116
- test('transition cannot delete its writer when durable release evidence fails', async () => {
1117
- const root = repository();
1118
- try {
1119
- const original = previousWriter(root);
1120
- let claim;
1121
- await assert.rejects(withWorktreeTransitionWriterLease({
1122
- repoRoot: entry(root).path,
1123
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1124
- beforeClaim: () => undefined,
1125
- recordClaim: (bytes) => {
1126
- claim = Buffer.from(bytes);
1127
- },
1128
- recordRelease: () => {
1129
- throw new Error('synthetic release evidence failure');
1130
- },
1131
- }, async () => undefined), /synthetic release evidence failure/u);
1132
- assert.deepEqual(readFileSync(original.path), claim);
1133
- }
1134
- finally {
1135
- rmSync(root, { force: true, recursive: true });
1136
- }
1137
- });
1138
- test('transition seals completion only after recorded writer deletion while the lease remains held', async () => {
1139
- const root = repository();
1140
- try {
1141
- const original = previousWriter(root);
1142
- let releaseRecorded = false;
1143
- let sealed = false;
1144
- await withWorktreeTransitionWriterLease({
1145
- repoRoot: entry(root).path,
1146
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1147
- beforeClaim: () => undefined,
1148
- recordClaim: () => undefined,
1149
- recordRelease: () => {
1150
- releaseRecorded = true;
1151
- },
1152
- afterRelease: () => {
1153
- assert.equal(releaseRecorded, true);
1154
- assert.throws(() => readFileSync(original.path), { code: 'ENOENT' });
1155
- assert.equal(realpathSync(`${original.path}.lock`), `${original.path}.lock`);
1156
- sealed = true;
1157
- },
1158
- }, async () => undefined);
1159
- assert.equal(sealed, true);
1160
- assert.throws(() => realpathSync(`${original.path}.lock`), { code: 'ENOENT' });
1161
- }
1162
- finally {
1163
- rmSync(root, { force: true, recursive: true });
1164
- }
1165
- });
1166
- test('removed-worktree replay uses the original subject writer slot without recreating source', async () => {
1167
- const root = repository();
1168
- try {
1169
- const row = entry(root);
1170
- const original = previousWriter(root);
1171
- execFileSync('git', ['worktree', 'remove', row.path], { cwd: root, stdio: 'pipe' });
1172
- let captured = false;
1173
- await withWorktreeTransitionWriterLease({
1174
- repoRoot: root,
1175
- worktreePath: row.path,
1176
- writerId: '1b75f48b-0746-43a5-bd6d-9ddc17848c9a',
1177
- beforeClaim: ({ previousBytes }) => {
1178
- assert.deepEqual(previousBytes, original.bytes);
1179
- captured = true;
1180
- },
1181
- recordClaim: () => undefined,
1182
- recordRelease: () => undefined,
1183
- }, async () => assert.throws(() => realpathSync(row.path), { code: 'ENOENT' }));
1184
- assert.equal(captured, true);
1185
- assert.throws(() => realpathSync(row.path), { code: 'ENOENT' });
1186
- }
1187
- finally {
1188
- rmSync(root, { force: true, recursive: true });
1189
- }
1190
- });
1191
- //# sourceMappingURL=worktreeTransition.test.js.map