@aviaratech/ai-delivery 0.3.35 → 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 (297) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +57 -554
  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 +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  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 +402 -515
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  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 -479
  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.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +329 -353
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +59 -19
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.js +73 -67
  95. package/dist/git.js.map +7 -1
  96. package/dist/gitProcess.d.ts +1 -1
  97. package/dist/gitProcess.js +58 -53
  98. package/dist/gitProcess.js.map +7 -1
  99. package/dist/github/client.d.ts +2 -2
  100. package/dist/github/client.js +484 -379
  101. package/dist/github/client.js.map +7 -1
  102. package/dist/github/commandIdentityPolicy.js +44 -52
  103. package/dist/github/commandIdentityPolicy.js.map +7 -1
  104. package/dist/github/discovery.d.ts +1 -0
  105. package/dist/github/discovery.js +197 -215
  106. package/dist/github/discovery.js.map +7 -1
  107. package/dist/github/discovery.test.js +223 -177
  108. package/dist/github/discovery.test.js.map +7 -1
  109. package/dist/github/issueHistory.d.ts +2 -2
  110. package/dist/github/issueHistory.js +117 -125
  111. package/dist/github/issueHistory.js.map +7 -1
  112. package/dist/github/machineAuth.d.ts +1 -1
  113. package/dist/github/machineAuth.js +126 -117
  114. package/dist/github/machineAuth.js.map +7 -1
  115. package/dist/github/machineAuth.test.js +755 -639
  116. package/dist/github/machineAuth.test.js.map +7 -1
  117. package/dist/github/nativeIssueMetadata.js +286 -273
  118. package/dist/github/nativeIssueMetadata.js.map +7 -1
  119. package/dist/github/projectDelivery.d.ts +18 -2
  120. package/dist/github/projectDelivery.js +615 -557
  121. package/dist/github/projectDelivery.js.map +7 -1
  122. package/dist/github/relationships.js +433 -389
  123. package/dist/github/relationships.js.map +7 -1
  124. package/dist/github/repo.d.ts +1 -0
  125. package/dist/github/repo.js +123 -96
  126. package/dist/github/repo.js.map +7 -1
  127. package/dist/index.js +3 -3
  128. package/dist/index.js.map +7 -1
  129. package/dist/issue.d.ts +40 -9
  130. package/dist/issue.js +2102 -1742
  131. package/dist/issue.js.map +7 -1
  132. package/dist/issue63History.test.js +40 -42
  133. package/dist/issue63History.test.js.map +7 -1
  134. package/dist/issue63Routes.test.js +154 -143
  135. package/dist/issue63Routes.test.js.map +7 -1
  136. package/dist/issueBatchUpdate.test.js +989 -885
  137. package/dist/issueBatchUpdate.test.js.map +7 -1
  138. package/dist/issueBlockerGuard.test.js +262 -226
  139. package/dist/issueBlockerGuard.test.js.map +7 -1
  140. package/dist/issueContract.d.ts +23 -4
  141. package/dist/issueContract.js +416 -395
  142. package/dist/issueContract.js.map +7 -1
  143. package/dist/issueContract.test.d.ts +4 -3
  144. package/dist/issueContract.test.js +358 -321
  145. package/dist/issueContract.test.js.map +7 -1
  146. package/dist/issueDates.test.js +235 -233
  147. package/dist/issueDates.test.js.map +7 -1
  148. package/dist/issueInfoReadback.test.js +304 -190
  149. package/dist/issueInfoReadback.test.js.map +7 -1
  150. package/dist/issueIntake.test.js +1945 -1732
  151. package/dist/issueIntake.test.js.map +7 -1
  152. package/dist/issueJournal.d.ts +40 -19
  153. package/dist/issueJournal.js +229 -138
  154. package/dist/issueJournal.js.map +7 -1
  155. package/dist/issueJournal.test.js +605 -422
  156. package/dist/issueJournal.test.js.map +7 -1
  157. package/dist/issueRollup.test.d.ts +1 -0
  158. package/dist/issueRollup.test.js +476 -0
  159. package/dist/issueRollup.test.js.map +7 -0
  160. package/dist/issueTracking.test.js +1059 -989
  161. package/dist/issueTracking.test.js.map +7 -1
  162. package/dist/issueWriteRecovery.test.d.ts +1 -0
  163. package/dist/issueWriteRecovery.test.js +260 -0
  164. package/dist/issueWriteRecovery.test.js.map +7 -0
  165. package/dist/lifecycle.test.js +112 -441
  166. package/dist/lifecycle.test.js.map +7 -1
  167. package/dist/logger.js +80 -74
  168. package/dist/logger.js.map +7 -1
  169. package/dist/mcp/index.js +116 -94
  170. package/dist/mcp/index.js.map +7 -1
  171. package/dist/mcp/tools.d.ts +264 -286
  172. package/dist/mcp/tools.js +267 -340
  173. package/dist/mcp/tools.js.map +7 -1
  174. package/dist/pluginAuthProbe.js +63 -52
  175. package/dist/pluginAuthProbe.js.map +7 -1
  176. package/dist/pluginAuthProbe.test.js +85 -62
  177. package/dist/pluginAuthProbe.test.js.map +7 -1
  178. package/dist/pluginCredentials.test.js +282 -259
  179. package/dist/pluginCredentials.test.js.map +7 -1
  180. package/dist/pluginDoctor.test.js +653 -588
  181. package/dist/pluginDoctor.test.js.map +7 -1
  182. package/dist/pluginInstaller.d.ts +7 -5
  183. package/dist/pluginInstaller.js +1173 -1229
  184. package/dist/pluginInstaller.js.map +7 -1
  185. package/dist/pluginInstaller.test.js +1842 -1423
  186. package/dist/pluginInstaller.test.js.map +7 -1
  187. package/dist/pluginPackaging.test.js +460 -409
  188. package/dist/pluginPackaging.test.js.map +7 -1
  189. package/dist/pr.d.ts +132 -94
  190. package/dist/pr.js +1521 -1323
  191. package/dist/pr.js.map +7 -1
  192. package/dist/pr.test.js +1678 -632
  193. package/dist/pr.test.js.map +7 -1
  194. package/dist/prAssociation.test.js +2419 -1788
  195. package/dist/prAssociation.test.js.map +7 -1
  196. package/dist/prDispatch.test.js +150 -89
  197. package/dist/prDispatch.test.js.map +7 -1
  198. package/dist/readView.d.ts +183 -0
  199. package/dist/readView.js +217 -0
  200. package/dist/readView.js.map +7 -0
  201. package/dist/readView.test.d.ts +1 -0
  202. package/dist/readView.test.js +119 -0
  203. package/dist/readView.test.js.map +7 -0
  204. package/dist/releaseReconciliation.test.js +267 -288
  205. package/dist/releaseReconciliation.test.js.map +7 -1
  206. package/dist/releaseWorkflow.test.js +2493 -422
  207. package/dist/releaseWorkflow.test.js.map +7 -1
  208. package/dist/review.d.ts +738 -2
  209. package/dist/review.js +601 -348
  210. package/dist/review.js.map +7 -1
  211. package/dist/review.test.js +1218 -812
  212. package/dist/review.test.js.map +7 -1
  213. package/dist/reviewSubmit.test.d.ts +1 -0
  214. package/dist/reviewSubmit.test.js +747 -0
  215. package/dist/reviewSubmit.test.js.map +7 -0
  216. package/dist/services/agentReadinessService.js +42 -37
  217. package/dist/services/agentReadinessService.js.map +7 -1
  218. package/dist/services/blockerGuardService.js +188 -188
  219. package/dist/services/blockerGuardService.js.map +7 -1
  220. package/dist/services/boardReconcileService.d.ts +125 -125
  221. package/dist/services/boardReconcileService.js +1295 -1421
  222. package/dist/services/boardReconcileService.js.map +7 -1
  223. package/dist/services/deliveryAdmission.js +131 -154
  224. package/dist/services/deliveryAdmission.js.map +7 -1
  225. package/dist/services/deliveryHealthService.js +197 -199
  226. package/dist/services/deliveryHealthService.js.map +7 -1
  227. package/dist/services/legacyIssueMigration.js +263 -277
  228. package/dist/services/legacyIssueMigration.js.map +7 -1
  229. package/dist/services/worktreeRegistry.d.ts +27 -119
  230. package/dist/services/worktreeRegistry.js +765 -1182
  231. package/dist/services/worktreeRegistry.js.map +7 -1
  232. package/dist/stagedChecks.test.js +396 -194
  233. package/dist/stagedChecks.test.js.map +7 -1
  234. package/dist/start.test.js +99 -95
  235. package/dist/start.test.js.map +7 -1
  236. package/dist/stdoutRegression.test.js +353 -352
  237. package/dist/stdoutRegression.test.js.map +7 -1
  238. package/dist/targetPolicyDiscovery.test.js +141 -143
  239. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  240. package/dist/targetPolicyEntrypoints.test.js +308 -269
  241. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  242. package/dist/targetPolicyLocal.test.js +580 -1051
  243. package/dist/targetPolicyLocal.test.js.map +7 -1
  244. package/dist/targetPolicyRoutes.test.js +305 -281
  245. package/dist/targetPolicyRoutes.test.js.map +7 -1
  246. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  247. package/dist/targetRepositoryExecution.test.js +463 -0
  248. package/dist/targetRepositoryExecution.test.js.map +7 -0
  249. package/dist/terminalMessages.js +41 -35
  250. package/dist/terminalMessages.js.map +7 -1
  251. package/dist/toolOutput.d.ts +2 -0
  252. package/dist/toolOutput.js +36 -0
  253. package/dist/toolOutput.js.map +7 -0
  254. package/dist/toolOutput.test.d.ts +1 -0
  255. package/dist/toolOutput.test.js +240 -0
  256. package/dist/toolOutput.test.js.map +7 -0
  257. package/dist/utils/atomicJson.js +84 -76
  258. package/dist/utils/atomicJson.js.map +7 -1
  259. package/dist/utils/filesystem.js +15 -18
  260. package/dist/utils/filesystem.js.map +7 -1
  261. package/dist/utils/lockfile.js +68 -71
  262. package/dist/utils/lockfile.js.map +7 -1
  263. package/dist/verification.d.ts +1 -19
  264. package/dist/verification.js +1020 -1939
  265. package/dist/verification.js.map +7 -1
  266. package/dist/verificationGate.test.js +127 -117
  267. package/dist/verificationGate.test.js.map +7 -1
  268. package/dist/version.js +23 -24
  269. package/dist/version.js.map +7 -1
  270. package/dist/worktree.d.ts +3 -15
  271. package/dist/worktree.js +97 -177
  272. package/dist/worktree.js.map +7 -1
  273. package/package.json +9 -8
  274. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  275. package/plugins/ai-delivery/README.md +47 -156
  276. package/plugins/ai-delivery/plugin.json +1 -1
  277. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  278. package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
  279. package/plugins/ai-delivery/runtime/package.json +1 -1
  280. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  281. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  282. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  283. package/dist/investigationCompletion.test.js +0 -728
  284. package/dist/investigationCompletion.test.js.map +0 -1
  285. package/dist/setup.d.ts +0 -60
  286. package/dist/setup.js +0 -585
  287. package/dist/setup.js.map +0 -1
  288. package/dist/setup.test.js +0 -3329
  289. package/dist/setup.test.js.map +0 -1
  290. package/dist/worktreeTransition.d.ts +0 -211
  291. package/dist/worktreeTransition.js +0 -1037
  292. package/dist/worktreeTransition.js.map +0 -1
  293. package/dist/worktreeTransition.test.js +0 -1191
  294. package/dist/worktreeTransition.test.js.map +0 -1
  295. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  296. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  297. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,1248 +1,831 @@
1
- import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readFileSync, readdirSync } from 'node:fs';
2
- import { dirname, join, resolve } from 'node:path';
3
- import { z } from 'zod';
4
- import { assertPrivateFile, CoordinateSchema, DigestSchema, RepositorySchema, digestBytes, stableJson, writeCreateOnly, } from '../delivery/common.js';
5
- import { digestValue } from '../delivery/index.js';
6
- import { gitCommonDir } from '../git.js';
7
- import { RuntimeAdmissionSchema } from './deliveryAdmission.js';
8
- import { logInfo, logWarn } from '../logger.js';
9
- import { ensureDataDirectory, ISSUE_CLI_DATA_DIR } from '../utils/filesystem.js';
10
- import { ensurePrivateDirectoryDurably, writeJsonFileAtomically, writePrivateJsonFileAtomically, } from '../utils/atomicJson.js';
11
- import { withLock } from '../utils/lockfile.js';
1
+ import { closeSync, existsSync, fsyncSync, lstatSync, openSync, readFileSync, readdirSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { z } from "zod";
4
+ import {
5
+ assertPrivateFile,
6
+ CoordinateSchema,
7
+ DigestSchema,
8
+ digestBytes,
9
+ stableJson,
10
+ writeCreateOnly
11
+ } from "../delivery/common.js";
12
+ import { digestValue } from "../delivery/index.js";
13
+ import { gitCommonDir } from "../git.js";
14
+ import { RuntimeAdmissionSchema } from "./deliveryAdmission.js";
15
+ import { logInfo, logWarn } from "../logger.js";
16
+ import { ensureDataDirectory, ISSUE_CLI_DATA_DIR } from "../utils/filesystem.js";
17
+ import {
18
+ ensurePrivateDirectoryDurably,
19
+ writeJsonFileAtomically,
20
+ writePrivateJsonFileAtomically
21
+ } from "../utils/atomicJson.js";
22
+ import { withLock } from "../utils/lockfile.js";
12
23
  const REGISTRY_PATH = `${ISSUE_CLI_DATA_DIR}/worktrees.json`;
13
- const LOCK_RETRY_MESSAGE = 'Worktree registry locked by another process. Retrying...';
14
- const ContinuationRowSchema = z
15
- .strictObject({
16
- branch: z.string().min(1),
17
- createdAt: z.string().min(1),
18
- identity: z.string().min(1),
19
- issueNumber: z.number().int().positive(),
20
- path: z.string().min(1),
21
- prNumber: z.number().int().positive().optional(),
22
- status: z.enum(['active', 'error', 'merged', 'pr-published', 'stale']),
23
- type: z.literal('issue'),
24
- updatedAt: z.string().min(1),
25
- })
26
- .transform(({ prNumber, ...row }) => ({ ...row, ...(prNumber === undefined ? {} : { prNumber }) }));
27
- /** @internal Private exact-plan checkpoint; it is not a public transition purpose. */
28
- export const CommittedContinuationPlanSchema = z
29
- .strictObject({
30
- schemaVersion: z.literal('ai-delivery.committed-continuation-plan@1'),
31
- planId: DigestSchema,
32
- repository: z.string().min(1),
33
- repoRoot: z.string().min(1),
34
- configDigest: DigestSchema,
35
- currentRuntime: RuntimeAdmissionSchema,
36
- row: ContinuationRowSchema,
37
- replacement: ContinuationRowSchema,
38
- head: CoordinateSchema,
39
- terminalHead: CoordinateSchema,
40
- terminalMergeId: DigestSchema,
41
- operator: z.strictObject({
42
- actorLogin: z.string().min(1),
43
- credentialIdentity: z.string().regex(/^user:[1-9]\d*$/u),
44
- }),
45
- reviewerActor: z.string().min(1),
46
- preserved: z.array(z.strictObject({ path: z.string().min(1), digest: DigestSchema })).min(1),
47
- })
48
- .superRefine((plan, ctx) => {
49
- const { planId, ...content } = plan;
50
- const { prNumber: _pr, identity: _identity, status: _status, updatedAt: _updated, ...original } = plan.row;
51
- const { identity: _newIdentity, status: _newStatus, updatedAt: _newUpdated, ...replacement } = plan.replacement;
52
- if (planId !== digestValue(content) ||
53
- plan.row.status !== 'merged' ||
54
- !plan.row.prNumber ||
55
- plan.replacement.status !== 'active' ||
56
- plan.replacement.prNumber !== undefined ||
57
- stableJson(original) !== stableJson(replacement) ||
58
- plan.head.sha === plan.terminalHead.sha ||
59
- new Set(plan.preserved.map((file) => file.path)).size !== plan.preserved.length)
60
- ctx.addIssue({ code: 'custom', message: 'Committed continuation plan identity or disposition is invalid.' });
24
+ const LOCK_RETRY_MESSAGE = "Worktree registry locked by another process. Retrying...";
25
+ const ContinuationRowSchema = z.strictObject({
26
+ branch: z.string().min(1),
27
+ createdAt: z.string().min(1),
28
+ identity: z.string().min(1),
29
+ issueNumber: z.number().int().positive(),
30
+ path: z.string().min(1),
31
+ prNumber: z.number().int().positive().optional(),
32
+ status: z.enum(["active", "error", "merged", "pr-published", "stale"]),
33
+ type: z.literal("issue"),
34
+ updatedAt: z.string().min(1)
35
+ }).transform(({ prNumber, ...row }) => ({ ...row, ...prNumber === void 0 ? {} : { prNumber } }));
36
+ const CommittedContinuationPlanSchema = z.strictObject({
37
+ schemaVersion: z.literal("ai-delivery.committed-continuation-plan@1"),
38
+ planId: DigestSchema,
39
+ repository: z.string().min(1),
40
+ repoRoot: z.string().min(1),
41
+ configDigest: DigestSchema,
42
+ currentRuntime: RuntimeAdmissionSchema,
43
+ row: ContinuationRowSchema,
44
+ replacement: ContinuationRowSchema,
45
+ head: CoordinateSchema,
46
+ terminalHead: CoordinateSchema,
47
+ terminalMergeId: DigestSchema,
48
+ operator: z.strictObject({
49
+ actorLogin: z.string().min(1),
50
+ credentialIdentity: z.string().regex(/^user:[1-9]\d*$/u)
51
+ }),
52
+ reviewerActor: z.string().min(1),
53
+ preserved: z.array(z.strictObject({ path: z.string().min(1), digest: DigestSchema })).min(1)
54
+ }).superRefine((plan, ctx) => {
55
+ const { planId, ...content } = plan;
56
+ const { prNumber: _pr, identity: _identity, status: _status, updatedAt: _updated, ...original } = plan.row;
57
+ const { identity: _newIdentity, status: _newStatus, updatedAt: _newUpdated, ...replacement } = plan.replacement;
58
+ if (planId !== digestValue(content) || plan.row.status !== "merged" || !plan.row.prNumber || plan.replacement.status !== "active" || plan.replacement.prNumber !== void 0 || stableJson(original) !== stableJson(replacement) || plan.head.sha === plan.terminalHead.sha || new Set(plan.preserved.map((file) => file.path)).size !== plan.preserved.length)
59
+ ctx.addIssue({ code: "custom", message: "Committed continuation plan identity or disposition is invalid." });
61
60
  });
62
- const ContinuationIntentSchema = z
63
- .strictObject({
64
- schemaVersion: z.literal('ai-delivery.committed-continuation-intent@1'),
65
- intentId: DigestSchema,
66
- plan: CommittedContinuationPlanSchema,
67
- authorityCommentId: z.number().int().positive(),
68
- acceptanceCommentId: z.number().int().positive(),
69
- })
70
- .superRefine(({ intentId, ...content }, ctx) => {
71
- if (intentId !== digestValue(content))
72
- ctx.addIssue({ code: 'custom', message: 'Continuation intent identity is invalid.' });
61
+ const ContinuationIntentSchema = z.strictObject({
62
+ schemaVersion: z.literal("ai-delivery.committed-continuation-intent@1"),
63
+ intentId: DigestSchema,
64
+ plan: CommittedContinuationPlanSchema,
65
+ authorityCommentId: z.number().int().positive(),
66
+ acceptanceCommentId: z.number().int().positive()
67
+ }).superRefine(({ intentId, ...content }, ctx) => {
68
+ if (intentId !== digestValue(content))
69
+ ctx.addIssue({ code: "custom", message: "Continuation intent identity is invalid." });
73
70
  });
74
- const ContinuationCompletionSchema = z
75
- .strictObject({
76
- schemaVersion: z.literal('ai-delivery.committed-continuation-completion@1'),
77
- completionId: DigestSchema,
78
- intentId: DigestSchema,
79
- planId: DigestSchema,
80
- row: ContinuationRowSchema,
81
- head: CoordinateSchema,
82
- completed: z.literal(true),
83
- })
84
- .superRefine(({ completionId, ...content }, ctx) => {
85
- if (completionId !== digestValue(content))
86
- ctx.addIssue({ code: 'custom', message: 'Continuation completion identity is invalid.' });
71
+ const ContinuationCompletionSchema = z.strictObject({
72
+ schemaVersion: z.literal("ai-delivery.committed-continuation-completion@1"),
73
+ completionId: DigestSchema,
74
+ intentId: DigestSchema,
75
+ planId: DigestSchema,
76
+ row: ContinuationRowSchema,
77
+ head: CoordinateSchema,
78
+ completed: z.literal(true)
79
+ }).superRefine(({ completionId, ...content }, ctx) => {
80
+ if (completionId !== digestValue(content))
81
+ ctx.addIssue({ code: "custom", message: "Continuation completion identity is invalid." });
87
82
  });
88
- export function committedContinuationPlanPath(root, issueNumber, head) {
89
- return join(gitCommonDir(root), 'ai-delivery', 'continuations', String(issueNumber), `${head}.plan.json`);
83
+ function committedContinuationPlanPath(root, issueNumber, head) {
84
+ return join(gitCommonDir(root), "ai-delivery", "continuations", String(issueNumber), `${head}.plan.json`);
90
85
  }
91
86
  function continuationIntentPath(plan) {
92
- return committedContinuationPlanPath(plan.repoRoot, plan.row.issueNumber, plan.head.sha).replace(/\.plan\.json$/u, '.intent.json');
87
+ return committedContinuationPlanPath(plan.repoRoot, plan.row.issueNumber, plan.head.sha).replace(
88
+ /\.plan\.json$/u,
89
+ ".intent.json"
90
+ );
93
91
  }
94
92
  function continuationCompletionPath(plan) {
95
- return continuationIntentPath(plan).replace(/\.intent\.json$/u, '.completion.json');
93
+ return continuationIntentPath(plan).replace(/\.intent\.json$/u, ".completion.json");
96
94
  }
97
95
  function continuationBeforeimagePath(plan, digest) {
98
- return join(gitCommonDir(plan.repoRoot), 'ai-delivery', 'continuations', 'evidence', `${digest.slice(7)}.bin`);
96
+ return join(gitCommonDir(plan.repoRoot), "ai-delivery", "continuations", "evidence", `${digest.slice(7)}.bin`);
99
97
  }
100
98
  function assertContinuationPreserved(plan, beforeimages = false) {
101
- for (const file of plan.preserved) {
102
- if (digestBytes(assertPrivateFile(file.path)) !== file.digest ||
103
- (beforeimages && digestBytes(assertPrivateFile(continuationBeforeimagePath(plan, file.digest))) !== file.digest))
104
- throw new Error('Committed continuation original evidence changed.');
105
- }
106
- if (beforeimages) {
107
- const bytes = Buffer.from(stableJson(plan.row));
108
- if (!assertPrivateFile(continuationBeforeimagePath(plan, digestBytes(bytes))).equals(bytes))
109
- throw new Error('Committed continuation original row beforeimage changed.');
110
- }
111
- }
112
- /** @internal Pending intents are recoverable only by the same supported develop boundary. */
113
- export function pendingCommittedContinuation(issueNumber, root) {
114
- const directory = join(gitCommonDir(root), 'ai-delivery', 'continuations', String(issueNumber));
115
- if (!existsSync(directory))
116
- return undefined;
117
- let pending;
118
- for (const name of readdirSync(directory)
119
- .filter((name) => name.endsWith('.intent.json'))
120
- .sort()) {
121
- const intent = ContinuationIntentSchema.parse(JSON.parse(assertPrivateFile(join(directory, name)).toString('utf8')));
122
- const plan = intent.plan;
123
- if (plan.repoRoot !== resolve(root) ||
124
- plan.row.issueNumber !== issueNumber ||
125
- join(directory, name) !== continuationIntentPath(plan))
126
- throw new Error('Committed continuation checkpoint identity disagrees.');
127
- assertContinuationPreserved(plan, true);
128
- const completionPath = continuationCompletionPath(plan);
129
- if (existsSync(completionPath)) {
130
- const completion = ContinuationCompletionSchema.parse(JSON.parse(assertPrivateFile(completionPath).toString('utf8')));
131
- if (completion.intentId !== intent.intentId ||
132
- completion.planId !== plan.planId ||
133
- stableJson(completion.row) !== stableJson(plan.replacement) ||
134
- stableJson(completion.head) !== stableJson(plan.head))
135
- throw new Error('Committed continuation completion disagrees with its intent.');
136
- assertOwnerWitness(plan.replacement, root);
137
- // Terminal recovery validates existing ancestors and repairs their directory durability.
138
- prepareCommittedContinuationDirectory(root, directory, false);
139
- prepareCommittedContinuationDirectory(root, dirname(continuationBeforeimagePath(plan, plan.preserved[0].digest)), false);
140
- syncCommittedContinuationDirectory(completionPath);
141
- }
142
- else {
143
- if (pending)
144
- throw new Error('Issue has multiple incomplete committed continuations.');
145
- pending = intent;
146
- }
147
- }
148
- return pending;
99
+ for (const file of plan.preserved) {
100
+ if (digestBytes(assertPrivateFile(file.path)) !== file.digest || beforeimages && digestBytes(assertPrivateFile(continuationBeforeimagePath(plan, file.digest))) !== file.digest)
101
+ throw new Error("Committed continuation original evidence changed.");
102
+ }
103
+ if (beforeimages) {
104
+ const bytes = Buffer.from(stableJson(plan.row));
105
+ if (!assertPrivateFile(continuationBeforeimagePath(plan, digestBytes(bytes))).equals(bytes))
106
+ throw new Error("Committed continuation original row beforeimage changed.");
107
+ }
108
+ }
109
+ function pendingCommittedContinuation(issueNumber, root) {
110
+ const directory = join(gitCommonDir(root), "ai-delivery", "continuations", String(issueNumber));
111
+ if (!existsSync(directory)) return void 0;
112
+ let pending;
113
+ for (const name of readdirSync(directory).filter((name2) => name2.endsWith(".intent.json")).sort()) {
114
+ const intent = ContinuationIntentSchema.parse(
115
+ JSON.parse(assertPrivateFile(join(directory, name)).toString("utf8"))
116
+ );
117
+ const plan = intent.plan;
118
+ if (plan.repoRoot !== resolve(root) || plan.row.issueNumber !== issueNumber || join(directory, name) !== continuationIntentPath(plan))
119
+ throw new Error("Committed continuation checkpoint identity disagrees.");
120
+ assertContinuationPreserved(plan, true);
121
+ const completionPath = continuationCompletionPath(plan);
122
+ if (existsSync(completionPath)) {
123
+ const completion = ContinuationCompletionSchema.parse(
124
+ JSON.parse(assertPrivateFile(completionPath).toString("utf8"))
125
+ );
126
+ if (completion.intentId !== intent.intentId || completion.planId !== plan.planId || stableJson(completion.row) !== stableJson(plan.replacement) || stableJson(completion.head) !== stableJson(plan.head))
127
+ throw new Error("Committed continuation completion disagrees with its intent.");
128
+ assertOwnerWitness(plan.replacement, root);
129
+ prepareCommittedContinuationDirectory(root, directory, false);
130
+ prepareCommittedContinuationDirectory(
131
+ root,
132
+ dirname(continuationBeforeimagePath(plan, plan.preserved[0].digest)),
133
+ false
134
+ );
135
+ syncCommittedContinuationDirectory(completionPath);
136
+ } else {
137
+ if (pending) throw new Error("Issue has multiple incomplete committed continuations.");
138
+ pending = intent;
139
+ }
140
+ }
141
+ return pending;
149
142
  }
150
143
  function ownerContent(entry) {
151
- if (!entry.identity)
152
- throw new Error('ai-delivery worktree ownership requires the preparing identity.');
153
- return {
154
- branch: entry.branch,
155
- identity: entry.identity,
156
- ...(entry.issueNumber === undefined ? {} : { issueNumber: entry.issueNumber }),
157
- path: entry.path,
158
- ...(entry.prNumber === undefined || entry.type === 'issue' ? {} : { prNumber: entry.prNumber }),
159
- schemaVersion: 'ai-delivery.worktree-owner@1',
160
- type: entry.type,
161
- };
144
+ if (!entry.identity) throw new Error("ai-delivery worktree ownership requires the preparing identity.");
145
+ return {
146
+ branch: entry.branch,
147
+ identity: entry.identity,
148
+ ...entry.issueNumber === void 0 ? {} : { issueNumber: entry.issueNumber },
149
+ path: entry.path,
150
+ ...entry.prNumber === void 0 || entry.type === "issue" ? {} : { prNumber: entry.prNumber },
151
+ schemaVersion: "ai-delivery.worktree-owner@1",
152
+ type: entry.type
153
+ };
162
154
  }
163
155
  function ownerPath(root, entry) {
164
- const id = digestValue(ownerContent(entry)).slice('sha256:'.length);
165
- return join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', `${id}.json`);
156
+ const id = digestValue(ownerContent(entry)).slice("sha256:".length);
157
+ return join(gitCommonDir(root), "ai-delivery", "worktree-owners", `${id}.json`);
166
158
  }
167
- function assertNoIncompleteWorktreeTransition(entry, root) {
168
- if (entry.type !== 'issue' || entry.issueNumber === undefined)
169
- return;
170
- const path = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', `issue-${String(entry.issueNumber)}.transition.json`);
171
- try {
172
- lstatSync(path);
173
- }
174
- catch (error) {
175
- if (error.code === 'ENOENT')
176
- return;
177
- throw new Error('Worktree transition is incomplete or unreadable.');
178
- }
179
- try {
180
- const intent = JSON.parse(assertPrivateFile(path).toString('utf8'));
181
- const { intentId, ...content } = intent;
182
- const { planId, ...planContent } = intent.plan;
183
- if (intent.schemaVersion !== 'ai-delivery.worktree-transition-intent@1' ||
184
- intentId !== digestValue(content) ||
185
- planId !== digestValue(planContent) ||
186
- intent.plan.repoRoot !== resolve(root) ||
187
- intent.plan.row.issueNumber !== entry.issueNumber)
188
- throw new Error('Invalid transition intent.');
189
- if (intent.plan.purpose === 'merged-cleanup')
190
- throw new Error('Worktree transition is terminal and cannot authorize ordinary source operations.');
191
- const completionPath = join(`${path}.evidence`, 'completion.json');
192
- const completion = JSON.parse(assertPrivateFile(completionPath).toString('utf8'));
193
- const { completionId, ...completionContent } = completion;
194
- if (completion.schemaVersion !== 'ai-delivery.worktree-transition-completion@1' ||
195
- completion.planId !== planId ||
196
- completion.intentId !== intentId ||
197
- completion.completed !== true ||
198
- completionId !== digestValue(completionContent) ||
199
- JSON.stringify(ownerContent(entry)) !== JSON.stringify(ownerContent(intent.plan.row)))
200
- throw new Error('Invalid transition completion.');
201
- return;
202
- }
203
- catch (error) {
204
- if (error instanceof Error && error.message.includes('transition is terminal'))
205
- throw error;
206
- throw new Error('Worktree transition is incomplete or unreadable; resume its exact approved plan.');
207
- }
208
- }
209
- /** An immutable witness separates new rows from legacy rows in the same canonical registry. */
210
- export function assertAiDeliveryWorktreeOwner(entry, root) {
211
- if (entry.issueNumber !== undefined)
212
- assertNoInvestigationCompletion(entry.issueNumber, root);
213
- assertNoIncompleteWorktreeTransition(entry, root);
214
- if (entry.issueNumber !== undefined && pendingCommittedContinuation(entry.issueNumber, root))
215
- throw new Error('Committed continuation is pending or incomplete; resume supported develop.');
216
- assertOwnerWitness(entry, root);
159
+ function assertAiDeliveryWorktreeOwner(entry, root) {
160
+ if (entry.issueNumber !== void 0 && pendingCommittedContinuation(entry.issueNumber, root))
161
+ throw new Error("Committed continuation is pending or incomplete; resume supported develop.");
162
+ assertOwnerWitness(entry, root);
217
163
  }
218
164
  function assertOwnerWitness(entry, root) {
219
- const content = ownerContent(entry);
220
- const path = ownerPath(root, entry);
221
- let stored;
222
- try {
223
- stored = JSON.parse(assertPrivateFile(path).toString('utf8'));
224
- }
225
- catch {
226
- throw new Error('Worktree lacks its exact ai-delivery ownership witness.');
227
- }
228
- if (JSON.stringify(stored) !== JSON.stringify({ ...content, ownerId: digestValue(content) })) {
229
- throw new Error('Worktree ownership witness disagrees with the canonical registry identity.');
230
- }
231
- }
232
- /** Ordinary source mutations also refuse terminal/pending issue intent after the row was removed. */
233
- export function assertIssueWorktreeTransitionAdmission(issueNumber, root, committedRecovery = false) {
234
- assertNoInvestigationCompletion(issueNumber, root);
235
- if (pendingCommittedContinuation(issueNumber, root) && !committedRecovery)
236
- throw new Error('Committed continuation is pending or incomplete; resume supported develop.');
237
- const path = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', `issue-${String(issueNumber)}.transition.json`);
238
- try {
239
- lstatSync(path);
240
- }
241
- catch (error) {
242
- if (error.code === 'ENOENT')
243
- return;
244
- throw new Error('Worktree transition is incomplete or unreadable.');
245
- }
246
- let row;
247
- try {
248
- row = JSON.parse(assertPrivateFile(path).toString('utf8')).plan.row;
249
- if (row.type !== 'issue' || row.issueNumber !== issueNumber)
250
- throw new Error('Transition embedded issue identity disagrees.');
251
- }
252
- catch {
253
- throw new Error('Worktree transition is incomplete or unreadable.');
254
- }
255
- assertNoIncompleteWorktreeTransition(row, root);
165
+ const content = ownerContent(entry);
166
+ const path = ownerPath(root, entry);
167
+ let stored;
168
+ try {
169
+ stored = JSON.parse(assertPrivateFile(path).toString("utf8"));
170
+ } catch {
171
+ throw new Error("Worktree lacks its exact ai-delivery ownership witness.");
172
+ }
173
+ if (JSON.stringify(stored) !== JSON.stringify({ ...content, ownerId: digestValue(content) })) {
174
+ throw new Error("Worktree ownership witness disagrees with the canonical registry identity.");
175
+ }
176
+ }
177
+ function assertIssueWorktreeTransitionAdmission(issueNumber, root, committedRecovery = false) {
178
+ if (pendingCommittedContinuation(issueNumber, root) && !committedRecovery)
179
+ throw new Error("Committed continuation is pending or incomplete; resume supported develop.");
256
180
  }
257
181
  function writeWorktreeOwner(entry, root, transition = false) {
258
- const content = ownerContent(entry);
259
- writeCreateOnly(ownerPath(root, entry), Buffer.from(JSON.stringify({ ...content, ownerId: digestValue(content) })));
260
- if (!transition)
261
- assertAiDeliveryWorktreeOwner(entry, root);
262
- }
263
- /** @internal New continuation checkpoints are published only while both owning locks are held. */
264
- export function writeCommittedContinuationCheckpoint(path, value) {
265
- const assertEqual = () => {
266
- const stored = JSON.parse(assertPrivateFile(path).toString('utf8'));
267
- if (stableJson(stored) !== stableJson(value))
268
- throw new Error('Committed continuation checkpoint changed.');
269
- };
270
- try {
271
- assertEqual();
272
- }
273
- catch (error) {
274
- if (error.code !== 'ENOENT')
275
- throw error;
276
- writePrivateJsonFileAtomically(path, value);
277
- assertEqual();
278
- }
279
- // Retry completes durability if the prior publisher died after rename but before directory sync.
280
- syncCommittedContinuationDirectory(path);
182
+ const content = ownerContent(entry);
183
+ writeCreateOnly(ownerPath(root, entry), Buffer.from(JSON.stringify({ ...content, ownerId: digestValue(content) })));
184
+ if (!transition) assertAiDeliveryWorktreeOwner(entry, root);
185
+ }
186
+ function writeCommittedContinuationCheckpoint(path, value) {
187
+ const assertEqual = () => {
188
+ const stored = JSON.parse(assertPrivateFile(path).toString("utf8"));
189
+ if (stableJson(stored) !== stableJson(value)) throw new Error("Committed continuation checkpoint changed.");
190
+ };
191
+ try {
192
+ assertEqual();
193
+ } catch (error) {
194
+ if (error.code !== "ENOENT") throw error;
195
+ writePrivateJsonFileAtomically(path, value);
196
+ assertEqual();
197
+ }
198
+ syncCommittedContinuationDirectory(path);
281
199
  }
282
200
  function syncCommittedContinuationDirectory(path) {
283
- const directory = openSync(dirname(path), 'r');
284
- try {
285
- fsyncSync(directory);
286
- }
287
- finally {
288
- closeSync(directory);
289
- }
201
+ const directory = openSync(dirname(path), "r");
202
+ try {
203
+ fsyncSync(directory);
204
+ } finally {
205
+ closeSync(directory);
206
+ }
290
207
  }
291
- /** Repair only this new namespace, anchored at the existing Git common directory. */
292
208
  function prepareCommittedContinuationDirectory(root, directory, create = true) {
293
- const deliveryDirectory = join(gitCommonDir(root), 'ai-delivery');
294
- const continuationRoot = join(deliveryDirectory, 'continuations');
295
- const paths = [deliveryDirectory, continuationRoot, directory];
296
- const validate = (path, missing) => {
297
- let metadata;
298
- try {
299
- metadata = lstatSync(path);
300
- }
301
- catch (error) {
302
- if (missing && error.code === 'ENOENT')
303
- return;
304
- throw error;
305
- }
306
- if (!metadata.isDirectory() ||
307
- metadata.isSymbolicLink() ||
308
- (path !== deliveryDirectory && (metadata.mode & 0o077) !== 0))
309
- throw new Error('Committed continuation evidence requires a private directory.');
310
- };
311
- for (const path of paths)
312
- validate(path, create && path !== deliveryDirectory);
313
- if (create)
314
- ensurePrivateDirectoryDurably(directory);
315
- for (const path of paths) {
316
- validate(path, false);
317
- // Existing mkdir state can be recovery from death before its parent was synced.
318
- syncCommittedContinuationDirectory(path);
319
- }
320
- }
321
- /** @internal One canonical row, its immutable witnesses, and the existing registry lock own this recovery. */
322
- export async function withCommittedContinuationRegistry(root, issueNumber, operation) {
323
- ensureRegistryDirectory(root);
324
- return withLock(REGISTRY_PATH, {
325
- projectRoot: root,
326
- timeout: 5000,
327
- operation: async () => {
328
- const pending = pendingCommittedContinuation(issueNumber, root);
329
- let intent = pending;
330
- let current;
331
- const readCurrent = () => {
332
- const registry = loadRegistryStrict(root);
333
- const matches = registry.worktrees.filter((row) => row.type === 'issue' && row.issueNumber === issueNumber);
334
- const row = matches[0];
335
- if (matches.length !== 1 || !row)
336
- throw new Error('Committed continuation requires one exact canonical issue row.');
337
- if (registry.worktrees.some((other) => other !== row && registryIdentitiesOverlap(other, row)))
338
- throw new Error('Committed continuation overlaps another canonical owner.');
339
- assertNoIncompleteWorktreeTransition(row, root);
340
- assertOwnerWitness(row, root);
341
- return { registry, row };
342
- };
343
- current = readCurrent().row;
344
- if (pending &&
345
- ![pending.plan.row, pending.plan.replacement].some((row) => stableJson(row) === stableJson(current)))
346
- throw new Error('Committed continuation canonical row drifted.');
347
- const original = pending?.plan.row ?? current;
348
- assertOwnerWitness(original, root);
349
- const witnessPath = ownerPath(root, original);
350
- const ownerWitness = { path: witnessPath, digest: digestBytes(assertPrivateFile(witnessPath)) };
351
- return operation({
352
- current,
353
- pending,
354
- ownerWitness,
355
- prepare: () => prepareCommittedContinuationDirectory(root, join(gitCommonDir(root), 'ai-delivery', 'continuations', String(issueNumber))),
356
- begin: (raw, ids) => {
357
- const plan = CommittedContinuationPlanSchema.parse(raw);
358
- if (plan.repoRoot !== resolve(root) ||
359
- plan.row.issueNumber !== issueNumber ||
360
- stableJson(plan.row) !== stableJson(original) ||
361
- !plan.preserved.some((file) => stableJson(file) === stableJson(ownerWitness)))
362
- throw new Error('Committed continuation lacks exact original custody.');
363
- const content = { schemaVersion: 'ai-delivery.committed-continuation-intent@1', plan, ...ids };
364
- const next = ContinuationIntentSchema.parse({ ...content, intentId: digestValue(content) });
365
- if (intent && stableJson(next) !== stableJson(intent))
366
- throw new Error('Committed continuation intent drifted.');
367
- assertContinuationPreserved(plan);
368
- const evidenceDirectory = dirname(continuationBeforeimagePath(plan, plan.preserved[0].digest));
369
- prepareCommittedContinuationDirectory(root, evidenceDirectory);
370
- for (const file of plan.preserved)
371
- writeCreateOnly(continuationBeforeimagePath(plan, file.digest), assertPrivateFile(file.path), file.digest);
372
- const rowBytes = Buffer.from(stableJson(plan.row));
373
- writeCreateOnly(continuationBeforeimagePath(plan, digestBytes(rowBytes)), rowBytes, digestBytes(rowBytes));
374
- writeCommittedContinuationCheckpoint(continuationIntentPath(plan), next);
375
- intent = next;
376
- },
377
- commit: () => {
378
- if (!intent)
379
- throw new Error('Committed continuation lacks its durable intent.');
380
- const { registry, row } = readCurrent();
381
- if (stableJson(row) !== stableJson(current))
382
- throw new Error('Committed continuation canonical row changed before commit.');
383
- assertContinuationPreserved(intent.plan, true);
384
- const replacementOwner = ownerContent(intent.plan.replacement);
385
- writeCommittedContinuationCheckpoint(ownerPath(root, intent.plan.replacement), {
386
- ...replacementOwner,
387
- ownerId: digestValue(replacementOwner),
388
- });
389
- registry.worktrees.splice(registry.worktrees.indexOf(row), 1, intent.plan.replacement);
390
- saveRegistryStrict(root, registry);
391
- current = intent.plan.replacement;
392
- },
393
- complete: () => {
394
- if (!intent || stableJson(readCurrent().row) !== stableJson(intent.plan.replacement))
395
- throw new Error('Committed continuation replacement row is incomplete.');
396
- assertContinuationPreserved(intent.plan, true);
397
- assertOwnerWitness(intent.plan.replacement, root);
398
- const content = {
399
- schemaVersion: 'ai-delivery.committed-continuation-completion@1',
400
- intentId: intent.intentId,
401
- planId: intent.plan.planId,
402
- row: intent.plan.replacement,
403
- head: intent.plan.head,
404
- completed: true,
405
- };
406
- writeCommittedContinuationCheckpoint(continuationCompletionPath(intent.plan), {
407
- ...content,
408
- completionId: digestValue(content),
409
- });
410
- },
411
- });
412
- },
413
- });
414
- }
415
- /** @internal The explicit transition owner holds the existing registry lock through its exact planned mutation. */
416
- export async function withWorktreeTransitionRegistry(plan, operation) {
417
- const root = plan.repoRoot;
418
- if (pendingCommittedContinuation(plan.row.issueNumber, root))
419
- throw new Error('Committed continuation is pending or incomplete; resume supported develop.');
420
- ensureRegistryDirectory(root);
421
- return withLock(REGISTRY_PATH, {
422
- projectRoot: root,
423
- timeout: 5000,
424
- operation: async () => {
425
- const registry = loadRegistryStrict(root);
426
- const matches = registry.worktrees.filter((entry) => entry.type === 'issue' && entry.issueNumber === plan.row.issueNumber);
427
- if (matches.length > 1)
428
- throw new Error('Transition has duplicate canonical issue rows.');
429
- if (registry.worktrees.some((entry) => !matches.includes(entry) && registryIdentitiesOverlap(entry, plan.row)))
430
- throw new Error('Transition conflicts with another canonical registry path, branch or PR identity.');
431
- let current = matches[0];
432
- const original = {
433
- ...plan.row,
434
- ...(plan.row.prNumber === undefined ? {} : { prNumber: plan.row.prNumber }),
435
- };
436
- const replacement = plan.purpose === 'active-resume'
437
- ? original
438
- : {
439
- ...original,
440
- prNumber: plan.terminalPrNumber,
441
- status: 'merged',
442
- };
443
- if (current !== undefined &&
444
- ![original, replacement].some((allowed) => stableJson(current) === stableJson(allowed)))
445
- throw new Error('Transition canonical row drifted.');
446
- const intentPath = join(gitCommonDir(root), 'ai-delivery', 'worktree-owners', `issue-${String(plan.row.issueNumber)}.transition.json`);
447
- const requireIntent = () => {
448
- const intent = JSON.parse(assertPrivateFile(intentPath).toString('utf8'));
449
- if (intent.plan?.planId !== plan.planId)
450
- throw new Error('Transition lacks its exact durable intent.');
451
- };
452
- return operation({
453
- current,
454
- writeOwner: () => {
455
- requireIntent();
456
- writeWorktreeOwner(replacement, root, true);
457
- },
458
- commitRow: () => {
459
- requireIntent();
460
- if (current === undefined)
461
- throw new Error('Transition cannot recreate a removed canonical row.');
462
- registry.worktrees.splice(registry.worktrees.indexOf(current), 1, replacement);
463
- current = replacement;
464
- saveRegistryStrict(root, registry);
465
- return replacement;
466
- },
467
- removeRow: () => {
468
- requireIntent();
469
- if (plan.purpose !== 'merged-cleanup' ||
470
- plan.disposition !== 'remove' ||
471
- plan.retainedHoldCommentIds.length !== 0)
472
- throw new Error('Transition lacks explicit unheld terminal source disposition.');
473
- if (current !== undefined) {
474
- registry.worktrees.splice(registry.worktrees.indexOf(current), 1);
475
- saveRegistryStrict(root, registry);
476
- current = undefined;
477
- }
478
- },
479
- });
480
- },
481
- });
482
- }
483
- /** @internal Validate the existing immutable witness without granting ordinary terminal admission. */
484
- export function assertTransitionOwnerWitness(plan) {
485
- const row = plan.row;
486
- const content = ownerContent(row);
487
- const stored = JSON.parse(assertPrivateFile(ownerPath(plan.repoRoot, row)).toString('utf8'));
488
- if (stableJson(stored) !== stableJson({ ...content, ownerId: digestValue(content) }))
489
- throw new Error('Sealed transition owner witness drifted.');
490
- }
491
- export async function addWorktreeEntry(entry, projectRoot) {
492
- const root = projectRoot ?? process.cwd();
493
- const normalizedEntry = {
494
- ...entry,
495
- status: entry.status,
496
- updatedAt: entry.updatedAt,
497
- };
498
- ensureRegistryDirectory(root);
499
- await withLock(REGISTRY_PATH, {
500
- onTimeout: () => {
501
- logWarn(LOCK_RETRY_MESSAGE);
502
- },
503
- operation: () => {
504
- assertNoIncompleteWorktreeTransition(normalizedEntry, root);
505
- const registry = loadRegistryStrict(root);
506
- const collisions = registry.worktrees.filter((existing) => registryIdentitiesOverlap(existing, normalizedEntry));
507
- const [existing] = collisions;
508
- if (collisions.length > 0) {
509
- if (collisions.length === 1 && existing !== undefined && isIdempotentRegistration(existing, normalizedEntry)) {
510
- assertAiDeliveryWorktreeOwner(existing, root);
511
- logInfo(`Worktree already registered: ${normalizedEntry.path}`);
512
- return;
513
- }
514
- if (collisions.length === 1 && existing !== undefined && isMergedIssueReactivation(existing, normalizedEntry)) {
515
- assertAiDeliveryWorktreeOwner(existing, root);
516
- const existingIndex = registry.worktrees.indexOf(existing);
517
- registry.worktrees.splice(existingIndex, 1, {
518
- ...normalizedEntry,
519
- createdAt: existing.createdAt,
520
- });
521
- saveRegistryStrict(root, registry);
522
- logInfo(`Reactivated merged issue worktree: ${normalizedEntry.path}`);
523
- return;
524
- }
525
- throw new Error(`New worktree entry conflicts with existing canonical registry identity: ${normalizedEntry.path}.`);
526
- }
527
- writeWorktreeOwner(normalizedEntry, root);
528
- registry.worktrees.push(normalizedEntry);
529
- logInfo(`Added to worktree registry: ${normalizedEntry.path}`);
530
- saveRegistryStrict(root, registry);
531
- },
532
- projectRoot: root,
533
- timeout: 5000,
534
- });
535
- }
536
- /** Resolve the sole canonical issue row for a provider-mutating lifecycle transition. */
537
- export function getIssueWorktreeStrict(issueNumber, projectRoot) {
538
- const root = projectRoot ?? process.cwd();
539
- const registry = loadRegistryStrict(root);
540
- const matching = registry.worktrees.filter((entry) => entry.type === 'issue' && entry.issueNumber === issueNumber);
541
- const entry = matching[0];
542
- if (matching.length !== 1 || entry === undefined) {
543
- throw new Error(`Expected exactly one canonical registry row for issue #${String(issueNumber)}; found ${String(matching.length)}.`);
544
- }
545
- assertAiDeliveryWorktreeOwner(entry, root);
546
- return entry;
547
- }
548
- /** Native metadata never adopts source; retain every transition and canonical registry fence. */
549
- export function assertNativeIssueTrackingAdmission(issueNumber, root) {
550
- assertIssueWorktreeTransitionAdmission(issueNumber, root);
551
- const matches = listWorktreesStrict(root).filter((entry) => entry.type === 'issue' && entry.issueNumber === issueNumber);
552
- if (matches.length > 1)
553
- throw new Error(`Issue #${String(issueNumber)} has duplicate worktree owners.`);
554
- }
555
- export function getStaleWorktrees(daysOld, projectRoot) {
556
- const root = projectRoot ?? process.cwd();
557
- const registry = loadRegistry(root);
558
- const cutoffDate = new Date();
559
- cutoffDate.setDate(cutoffDate.getDate() - daysOld);
560
- return registry.worktrees.filter((entry) => {
561
- const updatedAt = new Date(entry.updatedAt);
562
- return updatedAt < cutoffDate || entry.status === 'stale' || entry.status === 'merged';
563
- });
564
- }
565
- export function getWorktreeByIssue(issueNumber, projectRoot) {
566
- const root = projectRoot ?? process.cwd();
567
- const registry = loadRegistry(root);
568
- return registry.worktrees.find((w) => w.type === 'issue' && w.issueNumber === issueNumber) ?? null;
569
- }
570
- export function getWorktreeByPR(prNumber, projectRoot) {
571
- const root = projectRoot ?? process.cwd();
572
- const registry = loadRegistry(root);
573
- return registry.worktrees.find((w) => w.type === 'pr' && w.prNumber === prNumber) ?? null;
574
- }
575
- export function listWorktrees(projectRoot) {
576
- const root = projectRoot ?? process.cwd();
577
- const registry = loadRegistry(root);
578
- return registry.worktrees;
579
- }
580
- /**
581
- * Reads the registry for a terminal safety decision. Unlike the operational
582
- * listing helper, this fails closed if an existing registry cannot be read.
583
- */
584
- export function listWorktreesStrict(projectRoot) {
585
- const root = projectRoot ?? process.cwd();
586
- const registry = loadRegistryStrict(root);
587
- return registry.worktrees;
588
- }
589
- export async function markStaleEntries(thresholdMs, projectRoot) {
590
- const root = projectRoot ?? process.cwd();
591
- let updated = 0;
592
- ensureRegistryDirectory(root);
593
- await withLock(REGISTRY_PATH, {
594
- onTimeout: () => {
595
- logWarn(LOCK_RETRY_MESSAGE);
596
- },
597
- operation: () => {
598
- const registry = loadRegistryStrict(root);
599
- const now = Date.now();
600
- const newWorktrees = registry.worktrees.map((entry) => {
601
- const age = now - new Date(entry.updatedAt).getTime();
602
- if (age >= thresholdMs &&
603
- entry.type !== 'standalone' &&
604
- entry.status !== 'stale' &&
605
- entry.status !== 'merged') {
606
- assertAiDeliveryWorktreeOwner(entry, root);
607
- updated += 1;
608
- return {
609
- ...entry,
610
- status: 'stale',
611
- updatedAt: new Date().toISOString(),
612
- };
613
- }
614
- return entry;
615
- });
616
- if (updated > 0) {
617
- registry.worktrees = newWorktrees;
618
- saveRegistryStrict(root, registry);
619
- }
620
- },
621
- projectRoot: root,
622
- timeout: 5000,
623
- });
624
- return updated;
625
- }
626
- /** Atomically reconcile one verified terminal PR without changing its original producer identity. */
627
- export async function reconcileCompletedIssueWorktreeDelivery(options) {
628
- if (!Number.isSafeInteger(options.prNumber) || options.prNumber <= 0) {
629
- throw new Error(`Canonical PR number must be a positive integer for issue #${String(options.issueNumber)}.`);
630
- }
631
- const root = options.projectRoot ?? process.cwd();
632
- ensureRegistryDirectory(root);
633
- return await withLock(REGISTRY_PATH, {
634
- onTimeout: () => {
635
- logWarn(LOCK_RETRY_MESSAGE);
636
- },
637
- operation: () => {
638
- const registry = loadRegistryStrict(root);
639
- const matchingIndex = requireCanonicalIssueIndex({ ...options, registry });
640
- const entry = registry.worktrees[matchingIndex];
641
- if (entry === undefined) {
642
- throw new Error(`Canonical registry row for issue #${String(options.issueNumber)} disappeared during reconciliation.`);
643
- }
644
- assertAiDeliveryWorktreeOwner(entry, root);
645
- if (entry.status === 'merged' && entry.prNumber === options.prNumber) {
646
- return 'already-reconciled';
647
- }
648
- if (!(entry.status === 'active' && entry.prNumber === undefined) &&
649
- !(entry.status === 'pr-published' && entry.prNumber === options.prNumber)) {
650
- throw new Error(`Invalid completed-delivery reconciliation for #${String(options.issueNumber)}: ${entry.status}.`);
651
- }
652
- registry.worktrees.splice(matchingIndex, 1, {
653
- ...entry,
654
- prNumber: options.prNumber,
655
- status: 'merged',
656
- updatedAt: new Date().toISOString(),
657
- });
658
- saveRegistryStrict(root, registry);
659
- assertIssueDeliveryReadback({
660
- options: { ...options, status: 'merged' },
661
- registry: loadRegistryStrict(root),
662
- });
663
- return 'reconciled';
664
- },
665
- projectRoot: root,
666
- timeout: 5000,
667
- });
668
- }
669
- /** Remove one exact active standalone row without weakening registry parsing or identity checks. */
670
- export async function removeActiveStandaloneWorktreeEntry(input) {
671
- const root = input.projectRoot;
672
- ensureRegistryDirectory(root);
673
- await withLock(REGISTRY_PATH, {
674
- onTimeout: () => {
675
- logWarn(LOCK_RETRY_MESSAGE);
676
- },
677
- operation: () => {
678
- const registry = loadRegistryStrict(root);
679
- const matchingIndexes = registry.worktrees.flatMap((entry, index) => entry.path === input.path || entry.branch === input.branch ? [index] : []);
680
- const [matchingIndex] = matchingIndexes;
681
- const entry = matchingIndex === undefined ? undefined : registry.worktrees[matchingIndex];
682
- if (matchingIndexes.length !== 1 ||
683
- entry === undefined ||
684
- entry.path !== input.path ||
685
- entry.branch !== input.branch ||
686
- entry.type !== 'standalone' ||
687
- entry.status !== 'active' ||
688
- entry.issueNumber !== undefined ||
689
- entry.prNumber !== undefined) {
690
- throw new Error('Expected one exact active standalone registry row for qualification cleanup.');
691
- }
692
- if (matchingIndex === undefined) {
693
- throw new Error('Qualification cleanup registry identity disappeared before removal.');
694
- }
695
- assertAiDeliveryWorktreeOwner(entry, root);
696
- registry.worktrees.splice(matchingIndex, 1);
697
- saveRegistryStrict(root, registry);
698
- const readback = loadRegistryStrict(root).worktrees;
699
- if (readback.some((candidate) => candidate.path === input.path || candidate.branch === input.branch)) {
700
- throw new Error('Qualification cleanup registry readback retained the standalone identity.');
701
- }
702
- },
703
- projectRoot: root,
704
- timeout: 5000,
705
- });
706
- }
707
- export async function removeWorktreeEntry(path, projectRoot) {
708
- const root = projectRoot ?? process.cwd();
709
- ensureRegistryDirectory(root);
710
- return await withLock(REGISTRY_PATH, {
711
- onTimeout: () => {
712
- logWarn(LOCK_RETRY_MESSAGE);
713
- },
714
- operation: () => {
715
- const registry = loadRegistryStrict(root);
716
- const matching = registry.worktrees.filter((row) => row.path === path);
717
- if (matching.length > 1)
718
- throw new Error('Worktree registry contains duplicate paths.');
719
- if (matching[0] !== undefined) {
720
- assertAiDeliveryWorktreeOwner(matching[0], root);
721
- registry.worktrees = registry.worktrees.filter((row) => row.path !== path);
722
- saveRegistryStrict(root, registry);
723
- logInfo(`Removed from worktree registry: ${path}`);
724
- return true;
725
- }
726
- return false;
727
- },
728
- projectRoot: root,
729
- timeout: 5000,
730
- });
731
- }
732
- export async function updateIssueWorktreeDelivery(options) {
733
- const { branch, issueNumber, path, status } = options;
734
- const root = options.projectRoot ?? process.cwd();
735
- ensureRegistryDirectory(root);
736
- await withLock(REGISTRY_PATH, {
737
- onTimeout: () => {
738
- logWarn(LOCK_RETRY_MESSAGE);
209
+ const deliveryDirectory = join(gitCommonDir(root), "ai-delivery");
210
+ const continuationRoot = join(deliveryDirectory, "continuations");
211
+ const paths = [deliveryDirectory, continuationRoot, directory];
212
+ const validate = (path, missing) => {
213
+ let metadata;
214
+ try {
215
+ metadata = lstatSync(path);
216
+ } catch (error) {
217
+ if (missing && error.code === "ENOENT") return;
218
+ throw error;
219
+ }
220
+ if (!metadata.isDirectory() || metadata.isSymbolicLink() || path !== deliveryDirectory && (metadata.mode & 63) !== 0)
221
+ throw new Error("Committed continuation evidence requires a private directory.");
222
+ };
223
+ for (const path of paths) validate(path, create && path !== deliveryDirectory);
224
+ if (create) ensurePrivateDirectoryDurably(directory);
225
+ for (const path of paths) {
226
+ validate(path, false);
227
+ syncCommittedContinuationDirectory(path);
228
+ }
229
+ }
230
+ async function withCommittedContinuationRegistry(root, issueNumber, operation) {
231
+ ensureRegistryDirectory(root);
232
+ return withLock(REGISTRY_PATH, {
233
+ projectRoot: root,
234
+ timeout: 5e3,
235
+ operation: async () => {
236
+ const pending = pendingCommittedContinuation(issueNumber, root);
237
+ let intent = pending;
238
+ let current;
239
+ const readCurrent = () => {
240
+ const registry = loadRegistryStrict(root);
241
+ const matches = registry.worktrees.filter((row2) => row2.type === "issue" && row2.issueNumber === issueNumber);
242
+ const row = matches[0];
243
+ if (matches.length !== 1 || !row)
244
+ throw new Error("Committed continuation requires one exact canonical issue row.");
245
+ if (registry.worktrees.some((other) => other !== row && registryIdentitiesOverlap(other, row)))
246
+ throw new Error("Committed continuation overlaps another canonical owner.");
247
+ assertOwnerWitness(row, root);
248
+ return { registry, row };
249
+ };
250
+ current = readCurrent().row;
251
+ if (pending && ![pending.plan.row, pending.plan.replacement].some((row) => stableJson(row) === stableJson(current)))
252
+ throw new Error("Committed continuation canonical row drifted.");
253
+ const original = pending?.plan.row ?? current;
254
+ assertOwnerWitness(original, root);
255
+ const witnessPath = ownerPath(root, original);
256
+ const ownerWitness = { path: witnessPath, digest: digestBytes(assertPrivateFile(witnessPath)) };
257
+ return operation({
258
+ current,
259
+ pending,
260
+ ownerWitness,
261
+ prepare: () => prepareCommittedContinuationDirectory(
262
+ root,
263
+ join(gitCommonDir(root), "ai-delivery", "continuations", String(issueNumber))
264
+ ),
265
+ begin: (raw, ids) => {
266
+ const plan = CommittedContinuationPlanSchema.parse(raw);
267
+ if (plan.repoRoot !== resolve(root) || plan.row.issueNumber !== issueNumber || stableJson(plan.row) !== stableJson(original) || !plan.preserved.some((file) => stableJson(file) === stableJson(ownerWitness)))
268
+ throw new Error("Committed continuation lacks exact original custody.");
269
+ const content = { schemaVersion: "ai-delivery.committed-continuation-intent@1", plan, ...ids };
270
+ const next = ContinuationIntentSchema.parse({ ...content, intentId: digestValue(content) });
271
+ if (intent && stableJson(next) !== stableJson(intent))
272
+ throw new Error("Committed continuation intent drifted.");
273
+ assertContinuationPreserved(plan);
274
+ const evidenceDirectory = dirname(continuationBeforeimagePath(plan, plan.preserved[0].digest));
275
+ prepareCommittedContinuationDirectory(root, evidenceDirectory);
276
+ for (const file of plan.preserved)
277
+ writeCreateOnly(continuationBeforeimagePath(plan, file.digest), assertPrivateFile(file.path), file.digest);
278
+ const rowBytes = Buffer.from(stableJson(plan.row));
279
+ writeCreateOnly(continuationBeforeimagePath(plan, digestBytes(rowBytes)), rowBytes, digestBytes(rowBytes));
280
+ writeCommittedContinuationCheckpoint(continuationIntentPath(plan), next);
281
+ intent = next;
739
282
  },
740
- operation: () => {
741
- const registry = loadRegistryStrict(root);
742
- const matchingIndex = requireCanonicalIssueIndex({ branch, issueNumber, path, registry });
743
- const entry = registry.worktrees[matchingIndex];
744
- if (entry === undefined) {
745
- throw new Error(`Canonical registry row for issue #${String(issueNumber)} disappeared during transition.`);
746
- }
747
- assertAiDeliveryWorktreeOwner(entry, root);
748
- assertIssueDeliveryTransition({ entry, options });
749
- registry.worktrees.splice(matchingIndex, 1, {
750
- ...entry,
751
- ...(options.status === 'pr-published' ? { prNumber: options.prNumber } : {}),
752
- status,
753
- updatedAt: new Date().toISOString(),
754
- });
755
- saveRegistryStrict(root, registry);
756
- assertIssueDeliveryReadback({ options, registry: loadRegistryStrict(root) });
283
+ commit: () => {
284
+ if (!intent) throw new Error("Committed continuation lacks its durable intent.");
285
+ const { registry, row } = readCurrent();
286
+ if (stableJson(row) !== stableJson(current))
287
+ throw new Error("Committed continuation canonical row changed before commit.");
288
+ assertContinuationPreserved(intent.plan, true);
289
+ const replacementOwner = ownerContent(intent.plan.replacement);
290
+ writeCommittedContinuationCheckpoint(ownerPath(root, intent.plan.replacement), {
291
+ ...replacementOwner,
292
+ ownerId: digestValue(replacementOwner)
293
+ });
294
+ registry.worktrees.splice(registry.worktrees.indexOf(row), 1, intent.plan.replacement);
295
+ saveRegistryStrict(root, registry);
296
+ current = intent.plan.replacement;
757
297
  },
758
- projectRoot: root,
759
- timeout: 5000,
760
- });
761
- }
762
- function assertIssueDeliveryReadback({ options, registry, }) {
763
- const rows = registry.worktrees.filter((candidate) => candidate.type === 'issue' && candidate.issueNumber === options.issueNumber);
764
- const entry = rows[0];
765
- if (rows.length !== 1 ||
766
- entry === undefined ||
767
- entry.branch !== options.branch ||
768
- entry.path !== options.path ||
769
- entry.status !== options.status ||
770
- (options.status === 'pr-published' && entry.prNumber !== options.prNumber)) {
771
- throw new Error(`Canonical registry transition readback failed for issue #${String(options.issueNumber)}.`);
772
- }
773
- }
774
- function assertIssueDeliveryTransition({ entry, options, }) {
775
- if (options.status === 'pr-published') {
776
- if (!Number.isSafeInteger(options.prNumber) || options.prNumber <= 0) {
777
- throw new Error(`Canonical PR number must be a positive integer for issue #${String(options.issueNumber)}.`);
298
+ complete: () => {
299
+ if (!intent || stableJson(readCurrent().row) !== stableJson(intent.plan.replacement))
300
+ throw new Error("Committed continuation replacement row is incomplete.");
301
+ assertContinuationPreserved(intent.plan, true);
302
+ assertOwnerWitness(intent.plan.replacement, root);
303
+ const content = {
304
+ schemaVersion: "ai-delivery.committed-continuation-completion@1",
305
+ intentId: intent.intentId,
306
+ planId: intent.plan.planId,
307
+ row: intent.plan.replacement,
308
+ head: intent.plan.head,
309
+ completed: true
310
+ };
311
+ writeCommittedContinuationCheckpoint(continuationCompletionPath(intent.plan), {
312
+ ...content,
313
+ completionId: digestValue(content)
314
+ });
778
315
  }
779
- if (entry.status === 'active' && entry.prNumber === undefined) {
780
- return;
316
+ });
317
+ }
318
+ });
319
+ }
320
+ async function addWorktreeEntry(entry, projectRoot) {
321
+ const root = projectRoot ?? process.cwd();
322
+ const normalizedEntry = {
323
+ ...entry,
324
+ status: entry.status,
325
+ updatedAt: entry.updatedAt
326
+ };
327
+ ensureRegistryDirectory(root);
328
+ await withLock(REGISTRY_PATH, {
329
+ onTimeout: () => {
330
+ logWarn(LOCK_RETRY_MESSAGE);
331
+ },
332
+ operation: () => {
333
+ const registry = loadRegistryStrict(root);
334
+ const collisions = registry.worktrees.filter((existing2) => registryIdentitiesOverlap(existing2, normalizedEntry));
335
+ const [existing] = collisions;
336
+ if (collisions.length > 0) {
337
+ if (collisions.length === 1 && existing !== void 0 && isIdempotentRegistration(existing, normalizedEntry)) {
338
+ assertAiDeliveryWorktreeOwner(existing, root);
339
+ logInfo(`Worktree already registered: ${normalizedEntry.path}`);
340
+ return;
781
341
  }
782
- if (entry.status === 'pr-published' && entry.prNumber === options.prNumber) {
783
- return;
342
+ if (collisions.length === 1 && existing !== void 0 && isMergedIssueReactivation(existing, normalizedEntry)) {
343
+ assertAiDeliveryWorktreeOwner(existing, root);
344
+ const existingIndex = registry.worktrees.indexOf(existing);
345
+ registry.worktrees.splice(existingIndex, 1, {
346
+ ...normalizedEntry,
347
+ createdAt: existing.createdAt
348
+ });
349
+ saveRegistryStrict(root, registry);
350
+ logInfo(`Reactivated merged issue worktree: ${normalizedEntry.path}`);
351
+ return;
784
352
  }
785
- if (entry.status === 'pr-published' && entry.prNumber !== undefined) {
786
- throw new Error(`Issue #${String(options.issueNumber)} cannot replace canonical PR #${String(entry.prNumber)} with #${String(options.prNumber)}.`);
353
+ throw new Error(
354
+ `New worktree entry conflicts with existing canonical registry identity: ${normalizedEntry.path}.`
355
+ );
356
+ }
357
+ writeWorktreeOwner(normalizedEntry, root);
358
+ registry.worktrees.push(normalizedEntry);
359
+ logInfo(`Added to worktree registry: ${normalizedEntry.path}`);
360
+ saveRegistryStrict(root, registry);
361
+ },
362
+ projectRoot: root,
363
+ timeout: 5e3
364
+ });
365
+ }
366
+ function getIssueWorktreeStrict(issueNumber, projectRoot) {
367
+ const root = projectRoot ?? process.cwd();
368
+ const registry = loadRegistryStrict(root);
369
+ const matching = registry.worktrees.filter((entry2) => entry2.type === "issue" && entry2.issueNumber === issueNumber);
370
+ const entry = matching[0];
371
+ if (matching.length !== 1 || entry === void 0) {
372
+ throw new Error(
373
+ `Expected exactly one canonical registry row for issue #${String(issueNumber)}; found ${String(matching.length)}.`
374
+ );
375
+ }
376
+ assertAiDeliveryWorktreeOwner(entry, root);
377
+ return entry;
378
+ }
379
+ function assertNativeIssueTrackingAdmission(issueNumber, root) {
380
+ assertIssueWorktreeTransitionAdmission(issueNumber, root);
381
+ const matches = listWorktreesStrict(root).filter(
382
+ (entry) => entry.type === "issue" && entry.issueNumber === issueNumber
383
+ );
384
+ if (matches.length > 1) throw new Error(`Issue #${String(issueNumber)} has duplicate worktree owners.`);
385
+ }
386
+ function getStaleWorktrees(daysOld, projectRoot) {
387
+ const root = projectRoot ?? process.cwd();
388
+ const registry = loadRegistry(root);
389
+ const cutoffDate = /* @__PURE__ */ new Date();
390
+ cutoffDate.setDate(cutoffDate.getDate() - daysOld);
391
+ return registry.worktrees.filter((entry) => {
392
+ const updatedAt = new Date(entry.updatedAt);
393
+ return updatedAt < cutoffDate || entry.status === "stale" || entry.status === "merged";
394
+ });
395
+ }
396
+ function getWorktreeByIssue(issueNumber, projectRoot) {
397
+ const root = projectRoot ?? process.cwd();
398
+ const registry = loadRegistry(root);
399
+ return registry.worktrees.find((w) => w.type === "issue" && w.issueNumber === issueNumber) ?? null;
400
+ }
401
+ function getWorktreeByPR(prNumber, projectRoot) {
402
+ const root = projectRoot ?? process.cwd();
403
+ const registry = loadRegistry(root);
404
+ return registry.worktrees.find((w) => w.type === "pr" && w.prNumber === prNumber) ?? null;
405
+ }
406
+ function listWorktrees(projectRoot) {
407
+ const root = projectRoot ?? process.cwd();
408
+ const registry = loadRegistry(root);
409
+ return registry.worktrees;
410
+ }
411
+ function listWorktreesStrict(projectRoot) {
412
+ const root = projectRoot ?? process.cwd();
413
+ const registry = loadRegistryStrict(root);
414
+ return registry.worktrees;
415
+ }
416
+ async function markStaleEntries(thresholdMs, projectRoot) {
417
+ const root = projectRoot ?? process.cwd();
418
+ let updated = 0;
419
+ ensureRegistryDirectory(root);
420
+ await withLock(REGISTRY_PATH, {
421
+ onTimeout: () => {
422
+ logWarn(LOCK_RETRY_MESSAGE);
423
+ },
424
+ operation: () => {
425
+ const registry = loadRegistryStrict(root);
426
+ const now = Date.now();
427
+ const newWorktrees = registry.worktrees.map((entry) => {
428
+ const age = now - new Date(entry.updatedAt).getTime();
429
+ if (age >= thresholdMs && entry.type !== "standalone" && entry.status !== "stale" && entry.status !== "merged") {
430
+ assertAiDeliveryWorktreeOwner(entry, root);
431
+ updated += 1;
432
+ return {
433
+ ...entry,
434
+ status: "stale",
435
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
436
+ };
787
437
  }
788
- throw new Error(`Invalid issue delivery transition for #${String(options.issueNumber)}: ${entry.status} -> pr-published.`);
438
+ return entry;
439
+ });
440
+ if (updated > 0) {
441
+ registry.worktrees = newWorktrees;
442
+ saveRegistryStrict(root, registry);
443
+ }
444
+ },
445
+ projectRoot: root,
446
+ timeout: 5e3
447
+ });
448
+ return updated;
449
+ }
450
+ async function reconcileCompletedIssueWorktreeDelivery(options) {
451
+ if (!Number.isSafeInteger(options.prNumber) || options.prNumber <= 0) {
452
+ throw new Error(`Canonical PR number must be a positive integer for issue #${String(options.issueNumber)}.`);
453
+ }
454
+ const root = options.projectRoot ?? process.cwd();
455
+ ensureRegistryDirectory(root);
456
+ return await withLock(REGISTRY_PATH, {
457
+ onTimeout: () => {
458
+ logWarn(LOCK_RETRY_MESSAGE);
459
+ },
460
+ operation: () => {
461
+ const registry = loadRegistryStrict(root);
462
+ const matchingIndex = requireCanonicalIssueIndex({ ...options, registry });
463
+ const entry = registry.worktrees[matchingIndex];
464
+ if (entry === void 0) {
465
+ throw new Error(
466
+ `Canonical registry row for issue #${String(options.issueNumber)} disappeared during reconciliation.`
467
+ );
468
+ }
469
+ assertAiDeliveryWorktreeOwner(entry, root);
470
+ if (options.removeSource !== void 0 && registry.worktrees.some(
471
+ (other, index) => index !== matchingIndex && registryIdentitiesOverlap(other, { ...entry, prNumber: options.prNumber })
472
+ ))
473
+ throw new Error("Another registry owner claims this source; preserve both registrations before cleanup.");
474
+ if (entry.status === "merged" && entry.prNumber === options.prNumber && options.removeSource === void 0) {
475
+ return "already-reconciled";
476
+ }
477
+ if (!(entry.status === "active" && entry.prNumber === void 0) && !(entry.status === "pr-published" && entry.prNumber === options.prNumber) && !(entry.status === "merged" && entry.prNumber === options.prNumber)) {
478
+ throw new Error(
479
+ `Invalid completed-delivery reconciliation for #${String(options.issueNumber)}: ${entry.status}.`
480
+ );
481
+ }
482
+ registry.worktrees.splice(matchingIndex, 1, {
483
+ ...entry,
484
+ prNumber: options.prNumber,
485
+ status: "merged",
486
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
487
+ });
488
+ if (options.removeSource !== void 0) {
489
+ options.removeSource(registry.worktrees[matchingIndex]);
490
+ registry.worktrees.splice(matchingIndex, 1);
491
+ }
492
+ saveRegistryStrict(root, registry);
493
+ if (options.removeSource === void 0)
494
+ assertIssueDeliveryReadback({
495
+ options: { ...options, status: "merged" },
496
+ registry: loadRegistryStrict(root)
497
+ });
498
+ return "reconciled";
499
+ },
500
+ projectRoot: root,
501
+ timeout: 5e3
502
+ });
503
+ }
504
+ async function removeActiveStandaloneWorktreeEntry(input) {
505
+ const root = input.projectRoot;
506
+ ensureRegistryDirectory(root);
507
+ await withLock(REGISTRY_PATH, {
508
+ onTimeout: () => {
509
+ logWarn(LOCK_RETRY_MESSAGE);
510
+ },
511
+ operation: () => {
512
+ const registry = loadRegistryStrict(root);
513
+ const matchingIndexes = registry.worktrees.flatMap(
514
+ (entry2, index) => entry2.path === input.path || entry2.branch === input.branch ? [index] : []
515
+ );
516
+ const [matchingIndex] = matchingIndexes;
517
+ const entry = matchingIndex === void 0 ? void 0 : registry.worktrees[matchingIndex];
518
+ if (matchingIndexes.length !== 1 || entry === void 0 || entry.path !== input.path || entry.branch !== input.branch || entry.type !== "standalone" || entry.status !== "active" || entry.issueNumber !== void 0 || entry.prNumber !== void 0) {
519
+ throw new Error("Expected one exact active standalone registry row for qualification cleanup.");
520
+ }
521
+ if (matchingIndex === void 0) {
522
+ throw new Error("Qualification cleanup registry identity disappeared before removal.");
523
+ }
524
+ assertAiDeliveryWorktreeOwner(entry, root);
525
+ registry.worktrees.splice(matchingIndex, 1);
526
+ saveRegistryStrict(root, registry);
527
+ const readback = loadRegistryStrict(root).worktrees;
528
+ if (readback.some((candidate) => candidate.path === input.path || candidate.branch === input.branch)) {
529
+ throw new Error("Qualification cleanup registry readback retained the standalone identity.");
530
+ }
531
+ },
532
+ projectRoot: root,
533
+ timeout: 5e3
534
+ });
535
+ }
536
+ async function removeWorktreeEntry(path, projectRoot) {
537
+ const root = projectRoot ?? process.cwd();
538
+ ensureRegistryDirectory(root);
539
+ return await withLock(REGISTRY_PATH, {
540
+ onTimeout: () => {
541
+ logWarn(LOCK_RETRY_MESSAGE);
542
+ },
543
+ operation: () => {
544
+ const registry = loadRegistryStrict(root);
545
+ const matching = registry.worktrees.filter((row) => row.path === path);
546
+ if (matching.length > 1) throw new Error("Worktree registry contains duplicate paths.");
547
+ if (matching[0] !== void 0) {
548
+ assertAiDeliveryWorktreeOwner(matching[0], root);
549
+ registry.worktrees = registry.worktrees.filter((row) => row.path !== path);
550
+ saveRegistryStrict(root, registry);
551
+ logInfo(`Removed from worktree registry: ${path}`);
552
+ return true;
553
+ }
554
+ return false;
555
+ },
556
+ projectRoot: root,
557
+ timeout: 5e3
558
+ });
559
+ }
560
+ async function updateIssueWorktreeDelivery(options) {
561
+ const { branch, issueNumber, path, status } = options;
562
+ const root = options.projectRoot ?? process.cwd();
563
+ ensureRegistryDirectory(root);
564
+ await withLock(REGISTRY_PATH, {
565
+ onTimeout: () => {
566
+ logWarn(LOCK_RETRY_MESSAGE);
567
+ },
568
+ operation: () => {
569
+ const registry = loadRegistryStrict(root);
570
+ const matchingIndex = requireCanonicalIssueIndex({ branch, issueNumber, path, registry });
571
+ const entry = registry.worktrees[matchingIndex];
572
+ if (entry === void 0) {
573
+ throw new Error(`Canonical registry row for issue #${String(issueNumber)} disappeared during transition.`);
574
+ }
575
+ assertAiDeliveryWorktreeOwner(entry, root);
576
+ assertIssueDeliveryTransition({ entry, options });
577
+ registry.worktrees.splice(matchingIndex, 1, {
578
+ ...entry,
579
+ ...options.status === "pr-published" ? { prNumber: options.prNumber } : {},
580
+ status,
581
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
582
+ });
583
+ saveRegistryStrict(root, registry);
584
+ assertIssueDeliveryReadback({ options, registry: loadRegistryStrict(root) });
585
+ },
586
+ projectRoot: root,
587
+ timeout: 5e3
588
+ });
589
+ }
590
+ function assertIssueDeliveryReadback({
591
+ options,
592
+ registry
593
+ }) {
594
+ const rows = registry.worktrees.filter(
595
+ (candidate) => candidate.type === "issue" && candidate.issueNumber === options.issueNumber
596
+ );
597
+ const entry = rows[0];
598
+ if (rows.length !== 1 || entry === void 0 || entry.branch !== options.branch || entry.path !== options.path || entry.status !== options.status || options.status === "pr-published" && entry.prNumber !== options.prNumber) {
599
+ throw new Error(`Canonical registry transition readback failed for issue #${String(options.issueNumber)}.`);
600
+ }
601
+ }
602
+ function assertIssueDeliveryTransition({
603
+ entry,
604
+ options
605
+ }) {
606
+ if (options.status === "pr-published") {
607
+ if (!Number.isSafeInteger(options.prNumber) || options.prNumber <= 0) {
608
+ throw new Error(`Canonical PR number must be a positive integer for issue #${String(options.issueNumber)}.`);
609
+ }
610
+ if (entry.status === "active" && entry.prNumber === void 0) {
611
+ return;
789
612
  }
790
- if ((entry.status === 'pr-published' || entry.status === 'merged') &&
791
- entry.prNumber !== undefined &&
792
- Number.isSafeInteger(entry.prNumber) &&
793
- entry.prNumber > 0) {
794
- return;
613
+ if (entry.status === "pr-published" && entry.prNumber === options.prNumber) {
614
+ return;
795
615
  }
796
- throw new Error(`Invalid issue delivery transition for #${String(options.issueNumber)}: ${entry.status} -> merged.`);
616
+ if (entry.status === "pr-published" && entry.prNumber !== void 0) {
617
+ throw new Error(
618
+ `Issue #${String(options.issueNumber)} cannot replace canonical PR #${String(entry.prNumber)} with #${String(options.prNumber)}.`
619
+ );
620
+ }
621
+ throw new Error(
622
+ `Invalid issue delivery transition for #${String(options.issueNumber)}: ${entry.status} -> pr-published.`
623
+ );
624
+ }
625
+ if ((entry.status === "pr-published" || entry.status === "merged") && entry.prNumber !== void 0 && Number.isSafeInteger(entry.prNumber) && entry.prNumber > 0) {
626
+ return;
627
+ }
628
+ throw new Error(`Invalid issue delivery transition for #${String(options.issueNumber)}: ${entry.status} -> merged.`);
797
629
  }
798
630
  function ensureRegistryDirectory(root) {
799
- ensureDataDirectory(root);
631
+ ensureDataDirectory(root);
800
632
  }
801
633
  function isIdempotentRegistration(existing, incoming) {
802
- return (existing.branch === incoming.branch &&
803
- existing.identity === incoming.identity &&
804
- existing.issueNumber === incoming.issueNumber &&
805
- existing.path === incoming.path &&
806
- existing.prNumber === incoming.prNumber &&
807
- existing.status === incoming.status &&
808
- existing.type === incoming.type);
634
+ return existing.branch === incoming.branch && existing.identity === incoming.identity && existing.issueNumber === incoming.issueNumber && existing.path === incoming.path && existing.prNumber === incoming.prNumber && existing.status === incoming.status && existing.type === incoming.type;
809
635
  }
810
636
  function isMergedIssueReactivation(existing, incoming) {
811
- return (existing.branch === incoming.branch &&
812
- existing.identity === incoming.identity &&
813
- existing.issueNumber === incoming.issueNumber &&
814
- existing.path === incoming.path &&
815
- existing.prNumber !== undefined &&
816
- existing.status === 'merged' &&
817
- existing.type === 'issue' &&
818
- incoming.prNumber === undefined &&
819
- incoming.status === 'active' &&
820
- incoming.type === 'issue');
637
+ return existing.branch === incoming.branch && existing.identity === incoming.identity && existing.issueNumber === incoming.issueNumber && existing.path === incoming.path && existing.prNumber !== void 0 && existing.status === "merged" && existing.type === "issue" && incoming.prNumber === void 0 && incoming.status === "active" && incoming.type === "issue";
821
638
  }
822
639
  function isRecord(value) {
823
- return typeof value === 'object' && value !== null && !Array.isArray(value);
640
+ return typeof value === "object" && value !== null && !Array.isArray(value);
824
641
  }
825
642
  function loadRegistry(root) {
826
- const registryPath = resolve(root, REGISTRY_PATH);
827
- if (!existsSync(registryPath)) {
828
- return { worktrees: [] };
829
- }
830
- try {
831
- const raw = readFileSync(registryPath, 'utf8');
832
- const parsed = JSON.parse(raw);
643
+ const registryPath = resolve(root, REGISTRY_PATH);
644
+ if (!existsSync(registryPath)) {
645
+ return { worktrees: [] };
646
+ }
647
+ try {
648
+ const raw = readFileSync(registryPath, "utf8");
649
+ const parsed = JSON.parse(raw);
650
+ return {
651
+ worktrees: parsed.worktrees.map((entry) => {
652
+ const status = normalizeStatus(entry.status);
833
653
  return {
834
- worktrees: parsed.worktrees.map((entry) => {
835
- const status = normalizeStatus(entry.status);
836
- return {
837
- branch: entry.branch,
838
- createdAt: entry.createdAt,
839
- ...(entry.identity !== undefined ? { identity: entry.identity } : {}),
840
- ...(entry.issueNumber !== undefined ? { issueNumber: entry.issueNumber } : {}),
841
- path: entry.path,
842
- ...(entry.prNumber !== undefined ? { prNumber: entry.prNumber } : {}),
843
- status,
844
- type: entry.type,
845
- updatedAt: entry.updatedAt ?? entry.createdAt,
846
- };
847
- }),
654
+ branch: entry.branch,
655
+ createdAt: entry.createdAt,
656
+ ...entry.identity !== void 0 ? { identity: entry.identity } : {},
657
+ ...entry.issueNumber !== void 0 ? { issueNumber: entry.issueNumber } : {},
658
+ path: entry.path,
659
+ ...entry.prNumber !== void 0 ? { prNumber: entry.prNumber } : {},
660
+ status,
661
+ type: entry.type,
662
+ updatedAt: entry.updatedAt ?? entry.createdAt
848
663
  };
849
- }
850
- catch (error) {
851
- logWarn(`Failed to load worktree registry: ${error instanceof Error ? error.message : String(error)}`);
852
- return { worktrees: [] };
853
- }
664
+ })
665
+ };
666
+ } catch (error) {
667
+ logWarn(`Failed to load worktree registry: ${error instanceof Error ? error.message : String(error)}`);
668
+ return { worktrees: [] };
669
+ }
854
670
  }
855
671
  function loadRegistryStrict(root) {
856
- const registryPath = resolve(root, REGISTRY_PATH);
857
- if (!existsSync(registryPath)) {
858
- return { worktrees: [] };
859
- }
860
- try {
861
- const raw = readFileSync(registryPath, 'utf8');
862
- const parsed = JSON.parse(raw);
863
- if (!isRecord(parsed) || Object.keys(parsed).length !== 1 || !Array.isArray(parsed.worktrees)) {
864
- throw new Error('Registry must be an object with a worktrees array.');
865
- }
866
- return {
867
- worktrees: parsed.worktrees.map((entry, index) => normalizeStrictWorktreeEntry(entry, index)),
868
- };
869
- }
870
- catch (error) {
871
- throw new Error(`Unable to read worktree registry: ${error instanceof Error ? error.message : String(error)}`);
672
+ const registryPath = resolve(root, REGISTRY_PATH);
673
+ if (!existsSync(registryPath)) {
674
+ return { worktrees: [] };
675
+ }
676
+ try {
677
+ const raw = readFileSync(registryPath, "utf8");
678
+ const parsed = JSON.parse(raw);
679
+ if (!isRecord(parsed) || Object.keys(parsed).length !== 1 || !Array.isArray(parsed.worktrees)) {
680
+ throw new Error("Registry must be an object with a worktrees array.");
872
681
  }
682
+ return {
683
+ worktrees: parsed.worktrees.map((entry, index) => normalizeStrictWorktreeEntry(entry, index))
684
+ };
685
+ } catch (error) {
686
+ throw new Error(`Unable to read worktree registry: ${error instanceof Error ? error.message : String(error)}`);
687
+ }
873
688
  }
874
689
  function normalizeStatus(raw) {
875
- if (raw === 'merged' || raw === 'pr-published' || raw === 'active' || raw === 'error' || raw === 'stale') {
876
- return raw;
877
- }
878
- throw new Error('Worktree registry status is invalid.');
690
+ if (raw === "merged" || raw === "pr-published" || raw === "active" || raw === "error" || raw === "stale") {
691
+ return raw;
692
+ }
693
+ throw new Error("Worktree registry status is invalid.");
879
694
  }
880
695
  function normalizeStrictWorktreeEntry(entry, index) {
881
- if (!isRecord(entry)) {
882
- throw new Error(`worktrees[${String(index)}] must be an object.`);
883
- }
884
- const allowed = new Set([
885
- 'branch',
886
- 'createdAt',
887
- 'identity',
888
- 'issueNumber',
889
- 'path',
890
- 'prNumber',
891
- 'status',
892
- 'type',
893
- 'updatedAt',
894
- ]);
895
- const unknown = Object.keys(entry).filter((key) => !allowed.has(key));
896
- if (unknown.length > 0) {
897
- throw new Error(`worktrees[${String(index)}] has unsupported fields: ${unknown.join(', ')}.`);
898
- }
899
- const branch = requiredString(entry.branch, `worktrees[${String(index)}].branch`);
900
- const createdAt = requiredString(entry.createdAt, `worktrees[${String(index)}].createdAt`);
901
- const path = requiredString(entry.path, `worktrees[${String(index)}].path`);
902
- const type = requiredWorktreeType(entry.type, `worktrees[${String(index)}].type`);
903
- const status = requiredWorktreeStatus(entry.status, `worktrees[${String(index)}].status`);
904
- const identity = optionalString(entry.identity, `worktrees[${String(index)}].identity`);
905
- const issueNumber = optionalPositiveInteger(entry.issueNumber, `worktrees[${String(index)}].issueNumber`);
906
- const prNumber = optionalPositiveInteger(entry.prNumber, `worktrees[${String(index)}].prNumber`);
907
- const updatedAt = requiredString(entry.updatedAt, `worktrees[${String(index)}].updatedAt`);
908
- if (type === 'issue' && issueNumber === undefined) {
909
- throw new Error(`worktrees[${String(index)}].issueNumber is required for issue worktrees.`);
910
- }
911
- return {
912
- branch,
913
- createdAt,
914
- ...(identity === undefined ? {} : { identity }),
915
- ...(issueNumber === undefined ? {} : { issueNumber }),
916
- path,
917
- ...(prNumber === undefined ? {} : { prNumber }),
918
- status,
919
- type,
920
- updatedAt,
921
- };
696
+ if (!isRecord(entry)) {
697
+ throw new Error(`worktrees[${String(index)}] must be an object.`);
698
+ }
699
+ const allowed = /* @__PURE__ */ new Set([
700
+ "branch",
701
+ "createdAt",
702
+ "identity",
703
+ "issueNumber",
704
+ "path",
705
+ "prNumber",
706
+ "status",
707
+ "type",
708
+ "updatedAt"
709
+ ]);
710
+ const unknown = Object.keys(entry).filter((key) => !allowed.has(key));
711
+ if (unknown.length > 0) {
712
+ throw new Error(`worktrees[${String(index)}] has unsupported fields: ${unknown.join(", ")}.`);
713
+ }
714
+ const branch = requiredString(entry.branch, `worktrees[${String(index)}].branch`);
715
+ const createdAt = requiredString(entry.createdAt, `worktrees[${String(index)}].createdAt`);
716
+ const path = requiredString(entry.path, `worktrees[${String(index)}].path`);
717
+ const type = requiredWorktreeType(entry.type, `worktrees[${String(index)}].type`);
718
+ const status = requiredWorktreeStatus(entry.status, `worktrees[${String(index)}].status`);
719
+ const identity = optionalString(entry.identity, `worktrees[${String(index)}].identity`);
720
+ const issueNumber = optionalPositiveInteger(entry.issueNumber, `worktrees[${String(index)}].issueNumber`);
721
+ const prNumber = optionalPositiveInteger(entry.prNumber, `worktrees[${String(index)}].prNumber`);
722
+ const updatedAt = requiredString(entry.updatedAt, `worktrees[${String(index)}].updatedAt`);
723
+ if (type === "issue" && issueNumber === void 0) {
724
+ throw new Error(`worktrees[${String(index)}].issueNumber is required for issue worktrees.`);
725
+ }
726
+ return {
727
+ branch,
728
+ createdAt,
729
+ ...identity === void 0 ? {} : { identity },
730
+ ...issueNumber === void 0 ? {} : { issueNumber },
731
+ path,
732
+ ...prNumber === void 0 ? {} : { prNumber },
733
+ status,
734
+ type,
735
+ updatedAt
736
+ };
922
737
  }
923
738
  function optionalPositiveInteger(value, label) {
924
- if (value === undefined) {
925
- return undefined;
926
- }
927
- if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
928
- throw new Error(`${label} must be a positive integer.`);
929
- }
930
- return value;
739
+ if (value === void 0) {
740
+ return void 0;
741
+ }
742
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
743
+ throw new Error(`${label} must be a positive integer.`);
744
+ }
745
+ return value;
931
746
  }
932
747
  function optionalString(value, label) {
933
- if (value === undefined) {
934
- return undefined;
935
- }
936
- return requiredString(value, label);
748
+ if (value === void 0) {
749
+ return void 0;
750
+ }
751
+ return requiredString(value, label);
937
752
  }
938
753
  function registryIdentitiesOverlap(left, right) {
939
- return (left.path === right.path ||
940
- left.branch === right.branch ||
941
- (left.issueNumber !== undefined && right.issueNumber !== undefined && left.issueNumber === right.issueNumber) ||
942
- (left.prNumber !== undefined && right.prNumber !== undefined && left.prNumber === right.prNumber));
943
- }
944
- function requireCanonicalIssueIndex({ branch, issueNumber, path, registry, }) {
945
- const issueIndexes = registry.worktrees.flatMap((entry, index) => entry.type === 'issue' && entry.issueNumber === issueNumber ? [index] : []);
946
- if (issueIndexes.length !== 1) {
947
- throw new Error(`Expected exactly one canonical registry row for issue #${String(issueNumber)}; found ${String(issueIndexes.length)}.`);
948
- }
949
- const matchingIndex = issueIndexes[0];
950
- const entry = matchingIndex === undefined ? undefined : registry.worktrees[matchingIndex];
951
- if (matchingIndex === undefined || entry === undefined) {
952
- throw new Error(`Canonical registry row for issue #${String(issueNumber)} disappeared during transition.`);
953
- }
954
- if (entry.branch !== branch || entry.path !== path) {
955
- throw new Error(`Canonical registry row for issue #${String(issueNumber)} does not match branch ${branch} and path ${path}.`);
956
- }
957
- return matchingIndex;
754
+ return left.path === right.path || left.branch === right.branch || left.issueNumber !== void 0 && right.issueNumber !== void 0 && left.issueNumber === right.issueNumber || left.prNumber !== void 0 && right.prNumber !== void 0 && left.prNumber === right.prNumber;
755
+ }
756
+ function requireCanonicalIssueIndex({
757
+ branch,
758
+ issueNumber,
759
+ path,
760
+ registry
761
+ }) {
762
+ const issueIndexes = registry.worktrees.flatMap(
763
+ (entry2, index) => entry2.type === "issue" && entry2.issueNumber === issueNumber ? [index] : []
764
+ );
765
+ if (issueIndexes.length !== 1) {
766
+ throw new Error(
767
+ `Expected exactly one canonical registry row for issue #${String(issueNumber)}; found ${String(issueIndexes.length)}.`
768
+ );
769
+ }
770
+ const matchingIndex = issueIndexes[0];
771
+ const entry = matchingIndex === void 0 ? void 0 : registry.worktrees[matchingIndex];
772
+ if (matchingIndex === void 0 || entry === void 0) {
773
+ throw new Error(`Canonical registry row for issue #${String(issueNumber)} disappeared during transition.`);
774
+ }
775
+ if (entry.branch !== branch || entry.path !== path) {
776
+ throw new Error(
777
+ `Canonical registry row for issue #${String(issueNumber)} does not match branch ${branch} and path ${path}.`
778
+ );
779
+ }
780
+ return matchingIndex;
958
781
  }
959
782
  function requiredString(value, label) {
960
- if (typeof value !== 'string' || value.trim().length === 0) {
961
- throw new Error(`${label} must be a non-empty string.`);
962
- }
963
- return value;
783
+ if (typeof value !== "string" || value.trim().length === 0) {
784
+ throw new Error(`${label} must be a non-empty string.`);
785
+ }
786
+ return value;
964
787
  }
965
788
  function requiredWorktreeStatus(value, label) {
966
- if (value === 'merged' || value === 'pr-published' || value === 'active' || value === 'error' || value === 'stale') {
967
- return value;
968
- }
969
- throw new Error(`${label} is invalid.`);
789
+ if (value === "merged" || value === "pr-published" || value === "active" || value === "error" || value === "stale") {
790
+ return value;
791
+ }
792
+ throw new Error(`${label} is invalid.`);
970
793
  }
971
794
  function requiredWorktreeType(value, label) {
972
- if (value === 'issue' || value === 'pr' || value === 'standalone') {
973
- return value;
974
- }
975
- throw new Error(`${label} is invalid.`);
795
+ if (value === "issue" || value === "pr" || value === "standalone") {
796
+ return value;
797
+ }
798
+ throw new Error(`${label} is invalid.`);
976
799
  }
977
800
  function saveRegistryStrict(root, registry) {
978
- ensureRegistryDirectory(root);
979
- const registryPath = resolve(root, REGISTRY_PATH);
980
- try {
981
- writeJsonFileAtomically(registryPath, registry);
982
- }
983
- catch (error) {
984
- throw new Error(`Unable to save worktree registry: ${error instanceof Error ? error.message : String(error)}`);
985
- }
986
- }
987
- /** Current, prospective custody is separate from legacy producer/policy transitions. */
988
- export const InvestigationPreparationSchema = z
989
- .strictObject({
990
- schemaVersion: z.literal('ai-delivery.investigation-preparation@1'),
991
- preparationId: DigestSchema,
992
- repository: RepositorySchema,
993
- repoRoot: z.string().min(1),
994
- row: ContinuationRowSchema,
995
- head: CoordinateSchema,
996
- physical: z.strictObject({
997
- device: z.number().int().nonnegative().safe(),
998
- inode: z.number().int().nonnegative().safe(),
999
- gitDirectory: z.string().min(1),
1000
- gitDevice: z.number().int().nonnegative().safe(),
1001
- gitInode: z.number().int().nonnegative().safe(),
1002
- }),
1003
- operator: z.strictObject({
1004
- actorLogin: z.string().min(1),
1005
- credentialIdentity: z.string().regex(/^user:[1-9]\d*$/u),
1006
- }),
1007
- reviewerActor: z.string().min(1),
1008
- })
1009
- .superRefine(({ preparationId, ...content }, ctx) => {
1010
- if (preparationId !== digestValue(content) ||
1011
- content.row.status !== 'active' ||
1012
- content.row.prNumber !== undefined ||
1013
- content.row.branch !== `issue/${String(content.row.issueNumber)}` ||
1014
- content.row.path !== join(content.repoRoot, '.worktrees', `issue-${String(content.row.issueNumber)}`) ||
1015
- content.operator.actorLogin.toLowerCase() === content.reviewerActor.toLowerCase())
1016
- ctx.addIssue({ code: 'custom', message: 'Investigation preparation identity is invalid.' });
1017
- });
1018
- const InvestigationIntentSchema = z
1019
- .strictObject({
1020
- schemaVersion: z.literal('ai-delivery.investigation-completion-intent@1'),
1021
- intentId: DigestSchema,
1022
- preparationId: DigestSchema,
1023
- resultDigest: DigestSchema,
1024
- authorityCommentId: z.number().int().positive().safe(),
1025
- acceptanceCommentId: z.number().int().positive().safe(),
1026
- registryBeforeimage: DigestSchema,
1027
- authorityDigest: DigestSchema,
1028
- })
1029
- .superRefine(({ intentId, ...content }, ctx) => {
1030
- if (intentId !== digestValue(content))
1031
- ctx.addIssue({ code: 'custom', message: 'Investigation intent is corrupt.' });
1032
- });
1033
- const InvestigationCompletionSchema = z
1034
- .strictObject({
1035
- schemaVersion: z.literal('ai-delivery.investigation-completion@1'),
1036
- completionId: DigestSchema,
1037
- intentId: DigestSchema,
1038
- preparationId: DigestSchema,
1039
- completed: z.literal(true),
1040
- })
1041
- .superRefine(({ completionId, ...content }, ctx) => {
1042
- if (completionId !== digestValue(content))
1043
- ctx.addIssue({ code: 'custom', message: 'Investigation completion is corrupt.' });
1044
- });
1045
- function investigationDirectory(root, issueNumber) {
1046
- return join(gitCommonDir(root), 'ai-delivery', 'investigations', String(issueNumber));
1047
- }
1048
- function assertNoInvestigationCompletion(issueNumber, root) {
1049
- const path = join(investigationDirectory(root, issueNumber), 'intent.json');
1050
- try {
1051
- lstatSync(path);
1052
- }
1053
- catch (error) {
1054
- if (error.code === 'ENOENT')
1055
- return;
1056
- throw error;
1057
- }
1058
- throw new Error('Investigation completion is pending or terminal; resume only its exact completion.');
1059
- }
1060
- function readInvestigationJson(path) {
1061
- return JSON.parse(assertPrivateFile(path, { maxBytes: 1024 * 1024 }).toString('utf8'));
1062
- }
1063
- export function readInvestigationPreparation(root, issueNumber) {
1064
- const path = join(investigationDirectory(root, issueNumber), 'preparation.json');
1065
- try {
1066
- lstatSync(path);
1067
- }
1068
- catch (error) {
1069
- if (error.code === 'ENOENT')
1070
- return undefined;
1071
- throw error;
1072
- }
1073
- const preparation = InvestigationPreparationSchema.parse(readInvestigationJson(path));
1074
- if (preparation.repoRoot !== root || preparation.row.issueNumber !== issueNumber)
1075
- throw new Error('Investigation preparation belongs to another repository or issue.');
1076
- return preparation;
1077
- }
1078
- export function readInvestigationAcknowledgement(root, issueNumber) {
1079
- return z
1080
- .strictObject({ commentId: z.number().int().positive().safe(), url: z.url(), body: z.string().min(1) })
1081
- .parse(readInvestigationJson(join(investigationDirectory(root, issueNumber), 'acknowledgement.json')));
1082
- }
1083
- function prepareInvestigationDirectory(root, issueNumber) {
1084
- const directory = investigationDirectory(root, issueNumber);
1085
- const common = gitCommonDir(root);
1086
- for (const path of [join(common, 'ai-delivery'), join(common, 'ai-delivery', 'investigations'), directory]) {
1087
- try {
1088
- const metadata = lstatSync(path);
1089
- if (!metadata.isDirectory() || metadata.isSymbolicLink())
1090
- throw new Error('Investigation custody directory is unsafe.');
1091
- }
1092
- catch (error) {
1093
- if (error.code !== 'ENOENT')
1094
- throw error;
1095
- }
1096
- }
1097
- ensurePrivateDirectoryDurably(directory);
1098
- return directory;
1099
- }
1100
- function assertInvestigationRegistry(root) {
1101
- const directory = join(root, ISSUE_CLI_DATA_DIR);
1102
- const metadata = lstatSync(directory);
1103
- if (!metadata.isDirectory() || metadata.isSymbolicLink())
1104
- throw new Error('Canonical registry directory is unsafe.');
1105
- const path = join(root, REGISTRY_PATH);
1106
- if (existsSync(path)) {
1107
- const file = lstatSync(path);
1108
- if (!file.isFile() || file.isSymbolicLink() || file.nlink !== 1)
1109
- throw new Error('Canonical registry file is unsafe.');
1110
- }
1111
- }
1112
- function investigationRow(registry, preparation) {
1113
- const matches = registry.worktrees.filter((entry) => registryIdentitiesOverlap(entry, preparation.row));
1114
- if (matches.length > 1 || (matches[0] !== undefined && stableJson(matches[0]) !== stableJson(preparation.row)))
1115
- throw new Error('Investigation conflicts with canonical registry custody.');
1116
- return matches[0];
1117
- }
1118
- /** Explicit prospective registration; never adopts a legacy row or replaces its baseline. */
1119
- export async function registerInvestigationCustody(raw, acknowledge) {
1120
- const preparation = InvestigationPreparationSchema.parse(raw);
1121
- const root = preparation.repoRoot;
1122
- const issueNumber = preparation.row.issueNumber;
1123
- assertIssueWorktreeTransitionAdmission(issueNumber, root);
1124
- ensureRegistryDirectory(root);
1125
- assertInvestigationRegistry(root);
1126
- await withLock(REGISTRY_PATH, {
1127
- projectRoot: root,
1128
- timeout: 5000,
1129
- operation: async () => {
1130
- assertIssueWorktreeTransitionAdmission(issueNumber, root);
1131
- const registry = loadRegistryStrict(root);
1132
- const prior = readInvestigationPreparation(root, issueNumber);
1133
- if (prior === undefined && registry.worktrees.some((entry) => registryIdentitiesOverlap(entry, preparation.row)))
1134
- throw new Error('Legacy custody cannot be adopted as a current investigation.');
1135
- const row = investigationRow(registry, preparation);
1136
- if (prior !== undefined && stableJson(prior) !== stableJson(preparation))
1137
- throw new Error('Investigation baseline cannot be replaced.');
1138
- const directory = prepareInvestigationDirectory(root, issueNumber);
1139
- writeCreateOnly(join(directory, 'preparation.json'), Buffer.from(stableJson(preparation)));
1140
- const acknowledgement = await acknowledge();
1141
- writeCreateOnly(join(directory, 'acknowledgement.json'), Buffer.from(stableJson(acknowledgement)));
1142
- writeWorktreeOwner(preparation.row, root);
1143
- if (row === undefined) {
1144
- registry.worktrees.push(preparation.row);
1145
- saveRegistryStrict(root, registry);
1146
- }
1147
- if (investigationRow(loadRegistryStrict(root), preparation) === undefined)
1148
- throw new Error('Investigation registration readback is missing.');
1149
- },
1150
- });
1151
- }
1152
- /** The same canonical lock owns evidence preservation, non-force removal, and row commit. */
1153
- export async function completeInvestigationCustody(input) {
1154
- const preparation = InvestigationPreparationSchema.parse(input.preparation);
1155
- const root = preparation.repoRoot;
1156
- const issueNumber = preparation.row.issueNumber;
1157
- ensureRegistryDirectory(root);
1158
- assertInvestigationRegistry(root);
1159
- return withLock(REGISTRY_PATH, {
1160
- projectRoot: root,
1161
- timeout: 5000,
1162
- operation: async () => {
1163
- if (stableJson(readInvestigationPreparation(root, issueNumber)) !== stableJson(preparation))
1164
- throw new Error('Investigation preparation drifted.');
1165
- // Legacy transition/continuation custody remains a separate mandatory fence.
1166
- assertNoIncompleteWorktreeTransition(preparation.row, root);
1167
- if (pendingCommittedContinuation(issueNumber, root))
1168
- throw new Error('Committed continuation is incomplete.');
1169
- assertOwnerWitness(preparation.row, root);
1170
- const directory = investigationDirectory(root, issueNumber);
1171
- const intentPath = join(directory, 'intent.json');
1172
- const completionPath = join(directory, 'completion.json');
1173
- const intent = existsSync(intentPath)
1174
- ? InvestigationIntentSchema.parse(readInvestigationJson(intentPath))
1175
- : undefined;
1176
- const completion = existsSync(completionPath)
1177
- ? InvestigationCompletionSchema.parse(readInvestigationJson(completionPath))
1178
- : undefined;
1179
- const registry = loadRegistryStrict(root);
1180
- const row = investigationRow(registry, preparation);
1181
- if (row === undefined && intent === undefined)
1182
- throw new Error('Investigation row disappeared without a removal intent.');
1183
- if (completion !== undefined &&
1184
- (intent === undefined ||
1185
- row !== undefined ||
1186
- completion.intentId !== intent.intentId ||
1187
- completion.preparationId !== preparation.preparationId))
1188
- throw new Error('Investigation completion custody is inconsistent.');
1189
- const resultDigest = digestBytes(input.result);
1190
- if (intent !== undefined &&
1191
- (intent.preparationId !== preparation.preparationId ||
1192
- intent.resultDigest !== resultDigest ||
1193
- intent.authorityCommentId !== input.authorityCommentId ||
1194
- intent.acceptanceCommentId !== input.acceptanceCommentId))
1195
- throw new Error('Resume requires the same exact investigation intent and evidence.');
1196
- if (intent !== undefined)
1197
- for (const digest of [intent.resultDigest, intent.registryBeforeimage, intent.authorityDigest])
1198
- if (digestBytes(assertPrivateFile(join(directory, `${digest.slice(7)}.bin`))) !== digest)
1199
- throw new Error('Preserved investigation evidence changed.');
1200
- input.assertSource(intent !== undefined);
1201
- const authority = await input.authorize();
1202
- input.assertSource(intent !== undefined);
1203
- if (input.dryRun)
1204
- return { completed: false, replayed: intent !== undefined };
1205
- if (completion !== undefined)
1206
- return { completed: true, replayed: true, receiptPath: completionPath };
1207
- let accepted = intent;
1208
- if (accepted === undefined) {
1209
- const registryBytes = readFileSync(join(root, REGISTRY_PATH));
1210
- const authorityBytes = Buffer.from(stableJson(authority));
1211
- for (const bytes of [input.result, registryBytes, authorityBytes]) {
1212
- const digest = digestBytes(bytes);
1213
- writeCreateOnly(join(directory, `${digest.slice(7)}.bin`), bytes, digest);
1214
- }
1215
- const content = {
1216
- schemaVersion: 'ai-delivery.investigation-completion-intent@1',
1217
- preparationId: preparation.preparationId,
1218
- resultDigest,
1219
- authorityCommentId: input.authorityCommentId,
1220
- acceptanceCommentId: input.acceptanceCommentId,
1221
- registryBeforeimage: digestBytes(registryBytes),
1222
- authorityDigest: digestBytes(authorityBytes),
1223
- };
1224
- accepted = InvestigationIntentSchema.parse({ ...content, intentId: digestValue(content) });
1225
- writeCreateOnly(intentPath, Buffer.from(stableJson(accepted)));
1226
- }
1227
- // A fresh intent never turns unexplained absence into authorized recovery.
1228
- input.assertSource(intent !== undefined);
1229
- input.removeSource();
1230
- input.assertSource(true);
1231
- if (row !== undefined) {
1232
- registry.worktrees.splice(registry.worktrees.indexOf(row), 1);
1233
- saveRegistryStrict(root, registry);
1234
- }
1235
- if (investigationRow(loadRegistryStrict(root), preparation) !== undefined)
1236
- throw new Error('Investigation registry removal readback failed.');
1237
- const content = {
1238
- schemaVersion: 'ai-delivery.investigation-completion@1',
1239
- intentId: accepted.intentId,
1240
- preparationId: preparation.preparationId,
1241
- completed: true,
1242
- };
1243
- writeCreateOnly(completionPath, Buffer.from(stableJson({ ...content, completionId: digestValue(content) })));
1244
- return { completed: true, replayed: intent !== undefined, receiptPath: completionPath };
1245
- },
1246
- });
1247
- }
1248
- //# sourceMappingURL=worktreeRegistry.js.map
801
+ ensureRegistryDirectory(root);
802
+ const registryPath = resolve(root, REGISTRY_PATH);
803
+ try {
804
+ writeJsonFileAtomically(registryPath, registry);
805
+ } catch (error) {
806
+ throw new Error(`Unable to save worktree registry: ${error instanceof Error ? error.message : String(error)}`);
807
+ }
808
+ }
809
+ export {
810
+ CommittedContinuationPlanSchema,
811
+ addWorktreeEntry,
812
+ assertAiDeliveryWorktreeOwner,
813
+ assertIssueWorktreeTransitionAdmission,
814
+ assertNativeIssueTrackingAdmission,
815
+ committedContinuationPlanPath,
816
+ getIssueWorktreeStrict,
817
+ getStaleWorktrees,
818
+ getWorktreeByIssue,
819
+ getWorktreeByPR,
820
+ listWorktrees,
821
+ listWorktreesStrict,
822
+ markStaleEntries,
823
+ pendingCommittedContinuation,
824
+ reconcileCompletedIssueWorktreeDelivery,
825
+ removeActiveStandaloneWorktreeEntry,
826
+ removeWorktreeEntry,
827
+ updateIssueWorktreeDelivery,
828
+ withCommittedContinuationRegistry,
829
+ writeCommittedContinuationCheckpoint
830
+ };
831
+ //# sourceMappingURL=worktreeRegistry.js.map