@ornexus/neocortex 4.61.5 → 4.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +1 -1
  5. package/package.json +5 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -220
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.d.ts +8 -1
  20. package/packages/client/dist/agent/update-description.js +2 -260
  21. package/packages/client/dist/cache/crypto-utils.js +1 -78
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -364
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +17 -0
  39. package/packages/client/dist/commands/invoke.js +148 -7822
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -174
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  77. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  78. package/packages/client/dist/commands/story-worktree.js +5 -258
  79. package/packages/client/dist/config/host-auth-broker.js +1 -60
  80. package/packages/client/dist/config/host-auth-reference.js +1 -93
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -224
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  99. package/packages/client/dist/continuity/outbox.js +1 -117
  100. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  101. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  102. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  103. package/packages/client/dist/errors/error-messages.js +2 -258
  104. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  105. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  106. package/packages/client/dist/evidence/collector.js +1 -347
  107. package/packages/client/dist/evidence/index.js +1 -1
  108. package/packages/client/dist/evidence/types.js +0 -2
  109. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  110. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  111. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  112. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  113. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +94 -9
  114. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -1592
  115. package/packages/client/dist/git/epic-operational-state.js +2 -672
  116. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  117. package/packages/client/dist/git/git-lifecycle-store.d.ts +88 -0
  118. package/packages/client/dist/git/git-lifecycle-store.js +9 -2529
  119. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  120. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  121. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  122. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  123. package/packages/client/dist/git/release-gate-env.d.ts +62 -0
  124. package/packages/client/dist/git/release-gate-env.js +1 -0
  125. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  126. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -186
  127. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  128. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  129. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  130. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  131. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  132. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  133. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  134. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  135. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  136. package/packages/client/dist/i18n/first-run.js +2 -60
  137. package/packages/client/dist/index.js +1 -50
  138. package/packages/client/dist/invocation/invoke-input.js +1 -24
  139. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  140. package/packages/client/dist/license/index.js +1 -5
  141. package/packages/client/dist/license/license-client.js +1 -337
  142. package/packages/client/dist/machine/fingerprint.js +2 -163
  143. package/packages/client/dist/machine/index.js +1 -5
  144. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  145. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  146. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  147. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  148. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  149. package/packages/client/dist/migrations/project-identity.js +7 -493
  150. package/packages/client/dist/migrations/state-json.js +4 -393
  151. package/packages/client/dist/policy/architecture-policy.js +2 -184
  152. package/packages/client/dist/policy/index.js +1 -7
  153. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  154. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  155. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  156. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  157. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  158. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  159. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  160. package/packages/client/dist/private-execution/delivery.js +13 -410
  161. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  162. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  163. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  164. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  165. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  166. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  167. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  168. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  169. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  170. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  171. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  172. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  173. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  174. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  175. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  176. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  177. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  178. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  179. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  180. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  181. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  182. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  183. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  184. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  185. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  186. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  187. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  188. package/packages/client/dist/private-execution/session-lease.js +1 -63
  189. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  190. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  191. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  192. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  193. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  194. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  195. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  196. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  197. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  198. package/packages/client/dist/resilience/index.js +1 -8
  199. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  200. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  201. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  202. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  203. package/packages/client/dist/runner/binary.js +1 -404
  204. package/packages/client/dist/runner/cli.js +17 -1571
  205. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  206. package/packages/client/dist/runner/headless/adapters.js +1 -49
  207. package/packages/client/dist/runner/headless/background-root.js +1 -85
  208. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  209. package/packages/client/dist/runner/headless/child-env.js +1 -0
  210. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  211. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  212. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  213. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  214. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -0
  215. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  216. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  217. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  218. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  219. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  220. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  221. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  222. package/packages/client/dist/runner/headless/resolver.js +1 -231
  223. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  224. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  225. package/packages/client/dist/runner/headless/types.js +2 -575
  226. package/packages/client/dist/runner/host-capacity.js +1 -59
  227. package/packages/client/dist/runner/local-console.js +13 -396
  228. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  229. package/packages/client/dist/runner/project-identity.js +1 -106
  230. package/packages/client/dist/runner/scheduler.js +7 -995
  231. package/packages/client/dist/runner-cli.js +2 -18
  232. package/packages/client/dist/state/invocation-shape.js +1 -13
  233. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  234. package/packages/client/dist/state/state-json-repair.js +3 -785
  235. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  236. package/packages/client/dist/telemetry/index.js +1 -5
  237. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  238. package/packages/client/dist/tier/index.js +1 -5
  239. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  240. package/packages/client/dist/types/index.js +1 -38
  241. package/packages/client/dist/version.js +1 -27
  242. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  243. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  244. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  245. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  246. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  247. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  248. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  249. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  250. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  251. package/packages/client/dist/yoloop/index.js +1 -8
  252. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  253. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +16 -0
  254. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  255. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  256. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  257. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  258. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  259. package/packages/shared/dist/project-manifest-projection.js +199 -0
  260. package/packages/shared/dist/project-validation-commands.js +14 -6
  261. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  262. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  263. package/packages/shared/dist/yoloop/epic-terminal-git.js +94 -6
  264. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  265. package/targets-stubs/antigravity/gemini.md +1 -1
  266. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  267. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  268. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  269. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  270. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  271. package/targets-stubs/claude-code/neocortex.md +5 -5
  272. package/targets-stubs/codex/AGENTS.md +1 -1
  273. package/targets-stubs/cursor/agent.md +2 -2
  274. package/targets-stubs/gemini-cli/agent.md +2 -2
  275. package/targets-stubs/lib/managed-config-merge.js +77 -1
  276. package/targets-stubs/lib/managed-profile.sh +7 -0
  277. package/targets-stubs/opencode/neocortex-root.md +1 -1
  278. package/targets-stubs/vscode/install-vscode.sh +21 -0
  279. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,843 +1,3 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * P225.05 -- client-managed story worktree lifecycle (P225-CON-WORKTREE).
15
- *
16
- * create | adopt | sync | status | release for one story's temporary worktree.
17
- * Ownership is proven by two independent facts before any effect: a journal
18
- * entry in the private Git lifecycle runtime (lock + revision CAS) and a nonce
19
- * marker inside the worktree's private Git directory. Anything else is manual
20
- * and is never touched. No command uses `--force`, resolves conflicts, writes
21
- * tracked state or takes the P207 writer lease of the root checkout.
22
- *
23
- * Public values carry opaque IDs, SHAs, repository-relative paths and reason
24
- * codes only. The private absolute path is returned separately (`privatePath`)
25
- * for the local caller and is never part of `value`.
26
- */
27
- import { execFile } from 'node:child_process';
28
- import { createHash, randomBytes } from 'node:crypto';
29
- import { chmod, lstat, readFile, realpath, unlink, writeFile } from 'node:fs/promises';
30
- import { homedir as osHomedir } from 'node:os';
31
- import { isAbsolute, join, resolve } from 'node:path';
32
- import { yoloopDomainHash } from '../../../shared/dist/yoloop/canonical.js';
33
- import { STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS, compactStoryWorktreeJournal, ensureStoryWorktreeJournal, isStoryWorktreeCleanupReceiptRecord, mutateGitLifecycleRuntime, readGitLifecycleRuntime, } from './git-lifecycle-store.js';
34
- import { STORY_WORKTREE_ID_ENV, ensurePrivateStoryWorktreeRoot, resolveStoryWorktreePath, resolveStoryWorktreeRoot, storyWorktreeIdentity, } from './story-worktree-paths.js';
35
- export const STORY_WORKTREE_MARKER_FILE = 'nx-owner';
36
- /** Same domain as shared `digestStoryWorktreeReceipt` (P225-CON-RECEIPTS). */
37
- export const STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN = 'neocortex.p225.story-worktree-receipt.v1';
38
- /** Receipt digest computed with the packaged canonical hash (parity-tested). */
39
- export function digestStoryWorktreeReceiptLocal(receipt) {
40
- return yoloopDomainHash(STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN, receipt);
41
- }
42
- const DIRECTIVE_KEYS = Object.freeze([
43
- 'schemaVersion', 'kind', 'directiveId', 'epicId', 'storyId', 'releasedStepId',
44
- 'dependsOn', 'integratedEpicHeadSha', 'graphRevision', 'issuedAt',
45
- ]);
46
- const DIRECTIVE_STEP = /^step-c-[0-9]+-[a-z0-9-]{1,60}$/;
47
- const STORY_REF = /^P[1-9][0-9]*(?:\.[0-9]+)+$/;
48
- const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;
49
- /** Closed `dependency-release-directive` shape (parity-tested with the shared validator). */
50
- function isDependencyReleaseDirective(value) {
51
- if (value === null || typeof value !== 'object' || Array.isArray(value))
52
- return false;
53
- const directive = value;
54
- const keys = Object.keys(directive);
55
- if (keys.length !== DIRECTIVE_KEYS.length || !keys.every((key) => DIRECTIVE_KEYS.includes(key)))
56
- return false;
57
- const dependsOn = directive.dependsOn;
58
- return directive.schemaVersion === 1 && directive.kind === 'dependency-release-directive'
59
- && typeof directive.directiveId === 'string' && OPAQUE_ID.test(directive.directiveId)
60
- && typeof directive.epicId === 'string' && EPIC_ID.test(directive.epicId)
61
- && typeof directive.storyId === 'string' && STORY_REF.test(directive.storyId)
62
- && typeof directive.releasedStepId === 'string' && DIRECTIVE_STEP.test(directive.releasedStepId)
63
- && Array.isArray(dependsOn) && dependsOn.length > 0 && new Set(dependsOn).size === dependsOn.length
64
- && dependsOn.every((item) => typeof item === 'string' && STORY_REF.test(item))
65
- && typeof directive.integratedEpicHeadSha === 'string' && FULL_SHA.test(directive.integratedEpicHeadSha)
66
- && typeof directive.graphRevision === 'string' && SHA256.test(directive.graphRevision)
67
- && typeof directive.issuedAt === 'string' && ISO_UTC.test(directive.issuedAt) && Number.isFinite(Date.parse(directive.issuedAt));
68
- }
69
- const DEFAULT_TTL_MS = 24 * 60 * 60 * 1000;
70
- const GIT_TIMEOUT_MS = 30_000;
71
- const MAX_CONFLICT_PATHS = 200;
72
- const FULL_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
73
- const SHA256 = /^[a-f0-9]{64}$/;
74
- const LEASE_ID = /^swt-[a-f0-9]{24}$/;
75
- const OPAQUE_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;
76
- const EPIC_ID = /^P[1-9][0-9]*$/;
77
- /** Branches that adopt never registers: release could otherwise delete them. */
78
- const PROTECTED_BRANCH = /^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/;
79
- class StoryWorktreeRefusal extends Error {
80
- reasonCode;
81
- constructor(reasonCode) {
82
- super(reasonCode);
83
- this.reasonCode = reasonCode;
84
- }
85
- }
86
- function refuse(reasonCode) {
87
- throw new StoryWorktreeRefusal(reasonCode);
88
- }
89
- function sanitizedGitEnv() {
90
- const env = { ...process.env };
91
- for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY'])
92
- delete env[key];
93
- env.GIT_TERMINAL_PROMPT = '0';
94
- return env;
95
- }
96
- /** Bounded Git execution shared with the P225.06 cleanup module (exit code + stdout only). */
97
- export function runStoryWorktreeGit(cwd, args) {
98
- return git(cwd, args);
99
- }
100
- function git(cwd, args) {
101
- return new Promise((resolvePromise) => {
102
- execFile('git', [...args], {
103
- cwd,
104
- encoding: 'utf8',
105
- env: sanitizedGitEnv(),
106
- maxBuffer: 8 * 1024 * 1024,
107
- timeout: GIT_TIMEOUT_MS,
108
- windowsHide: true,
109
- }, (error, stdout) => resolvePromise({ ok: !error, stdout: String(stdout ?? '') }));
110
- });
111
- }
112
- async function gitOk(cwd, args) {
113
- return (await git(cwd, args)).ok;
114
- }
115
- async function gitValue(cwd, args, reasonCode) {
116
- const outcome = await git(cwd, args);
117
- if (!outcome.ok)
118
- refuse(reasonCode);
119
- return outcome.stdout.trim();
120
- }
121
- function sha256(value) {
122
- return createHash('sha256').update(value).digest('hex');
123
- }
124
- async function pathExists(path) {
125
- try {
126
- await lstat(path);
127
- return true;
128
- }
129
- catch {
130
- return false;
131
- }
132
- }
133
- function sleep(ms) {
134
- return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
135
- }
136
- export function parseWorktreeList(output) {
137
- const result = [];
138
- for (const block of output.split('\0\0')) {
139
- const fields = block.split('\0').filter(Boolean);
140
- const path = fields.find((field) => field.startsWith('worktree '))?.slice('worktree '.length);
141
- if (!path)
142
- continue;
143
- const head = fields.find((field) => field.startsWith('HEAD '))?.slice('HEAD '.length);
144
- const branchRef = fields.find((field) => field.startsWith('branch '))?.slice('branch '.length);
145
- result.push({
146
- path,
147
- ...(head ? { head } : {}),
148
- ...(branchRef?.startsWith('refs/heads/') ? { branch: branchRef.slice('refs/heads/'.length) } : {}),
149
- });
150
- }
151
- return result;
152
- }
153
- function safeConflictPath(value) {
154
- return value.length > 0 && value.length <= 512 && !isAbsolute(value) && !/^[A-Za-z]:/.test(value)
155
- && !value.includes('\\') && !value.split('/').some((segment) => segment === '..' || segment === '');
156
- }
157
- export class StoryWorktreeManager {
158
- options;
159
- projectRoot;
160
- now;
161
- randomNonce;
162
- platform;
163
- constructor(options) {
164
- this.options = options;
165
- this.projectRoot = resolve(options.projectRoot);
166
- this.now = options.now ?? (() => new Date());
167
- this.randomNonce = options.randomNonce ?? (() => randomBytes(32).toString('hex'));
168
- this.platform = options.platform ?? process.platform;
169
- }
170
- async create(input) {
171
- return this.guard(async () => {
172
- const identity = this.identity(input);
173
- const facts = await this.repository();
174
- await this.assertAuthorizedBase(facts, identity.executionBranch, input.baseSha, input.graphRevision);
175
- const rootResult = resolveStoryWorktreeRoot({
176
- platform: this.platform,
177
- env: this.options.env ?? process.env,
178
- homedir: this.options.homedir ?? osHomedir(),
179
- ...(this.options.worktreeRoot ? { override: this.options.worktreeRoot } : {}),
180
- });
181
- if (!rootResult.ok)
182
- refuse(rootResult.reasonCode);
183
- const pathResult = resolveStoryWorktreePath({
184
- root: rootResult.value, hash8: identity.hash8, repositoryRoot: facts.mainRoot, platform: this.platform,
185
- });
186
- if (!pathResult.ok)
187
- refuse(pathResult.reasonCode);
188
- const ensured = await ensurePrivateStoryWorktreeRoot(rootResult.value, this.platform);
189
- if (!ensured.ok)
190
- refuse(ensured.reasonCode);
191
- // Re-check length and repository containment on the canonical root: a
192
- // symlinked ancestor (or a win32 short-name expansion) must not move the
193
- // worktree inside the repository or past the length limit.
194
- const canonicalPath = resolveStoryWorktreePath({
195
- root: await realpath(rootResult.value), hash8: identity.hash8, repositoryRoot: facts.mainRoot, platform: this.platform,
196
- });
197
- if (!canonicalPath.ok)
198
- refuse(canonicalPath.reasonCode);
199
- const worktreePath = canonicalPath.value;
200
- const existing = (await this.readDocument()).storyWorktrees?.entries[identity.leaseId];
201
- if (existing) {
202
- if (existing.state === 'active' && existing.baseSha === input.baseSha
203
- && existing.graphRevision === input.graphRevision && await this.ownershipProven(existing, facts)) {
204
- await this.assertNoCleanupInProgress(facts, existing.leaseId);
205
- return { ok: true, value: this.leaseValue(existing, true), privatePath: existing.worktreePath };
206
- }
207
- if (!await this.reclaimStaleReservation(existing, facts))
208
- refuse('story-worktree-entry-conflict');
209
- }
210
- if (await pathExists(worktreePath))
211
- refuse('story-worktree-path-occupied');
212
- if (await gitOk(facts.mainRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${identity.temporaryBranch}`])) {
213
- refuse('story-worktree-branch-exists');
214
- }
215
- const nonce = this.randomNonce();
216
- const acquired = this.now();
217
- const entry = {
218
- schemaVersion: 1,
219
- leaseId: identity.leaseId,
220
- epicId: identity.epicId,
221
- storyId: identity.storyId,
222
- dispatchDigest: sha256(identity.dispatchId),
223
- hash8: identity.hash8,
224
- executionBranch: identity.executionBranch,
225
- temporaryBranch: identity.temporaryBranch,
226
- worktreeRef: identity.worktreeRef,
227
- worktreePath,
228
- workspaceMechanism: 'client_managed_worktree',
229
- ownerId: this.ownerId(input.ownerId, nonce),
230
- nonceDigest: sha256(nonce),
231
- baseSha: input.baseSha,
232
- graphRevision: input.graphRevision,
233
- state: 'creating',
234
- acquiredAt: acquired.toISOString(),
235
- expiresAt: new Date(acquired.getTime() + (this.options.ttlMs ?? DEFAULT_TTL_MS)).toISOString(),
236
- };
237
- await this.mutate((document) => {
238
- const journal = ensureStoryWorktreeJournal(document);
239
- if (journal.entries[entry.leaseId]
240
- || Object.values(journal.entries).some((item) => item.worktreePath === worktreePath)) {
241
- refuse('story-worktree-entry-conflict');
242
- }
243
- journal.entries[entry.leaseId] = entry;
244
- });
245
- let added = false;
246
- try {
247
- if (!await gitOk(facts.mainRoot, ['worktree', 'add', '-b', identity.temporaryBranch, worktreePath, input.baseSha])) {
248
- refuse('story-worktree-add-failed');
249
- }
250
- added = true;
251
- if (this.platform !== 'win32')
252
- await chmod(worktreePath, 0o700);
253
- else
254
- await this.enableWindowsLongPaths(facts, worktreePath);
255
- const gitDir = await this.worktreeGitDir(worktreePath, facts);
256
- await writeFile(join(gitDir, STORY_WORKTREE_MARKER_FILE), `${JSON.stringify({ schemaVersion: 1, leaseId: entry.leaseId, nonce })}\n`, { flag: 'wx', mode: 0o600 });
257
- const active = { ...entry, state: 'active' };
258
- await this.mutate((document) => {
259
- const journal = ensureStoryWorktreeJournal(document);
260
- const current = journal.entries[entry.leaseId];
261
- if (!current || current.state !== 'creating' || current.nonceDigest !== entry.nonceDigest) {
262
- refuse('story-worktree-entry-conflict');
263
- }
264
- journal.entries[entry.leaseId] = active;
265
- });
266
- return { ok: true, value: this.leaseValue(active, false), privatePath: worktreePath };
267
- }
268
- catch (error) {
269
- await this.rollbackCreate(facts, entry, added);
270
- throw error;
271
- }
272
- });
273
- }
274
- async adopt(input) {
275
- return this.guard(async () => {
276
- const identity = this.identity(input);
277
- const facts = await this.repository();
278
- await this.assertAuthorizedBase(facts, identity.executionBranch, input.baseSha, input.graphRevision);
279
- if (typeof input.worktreePath !== 'string' || !isAbsolute(input.worktreePath))
280
- refuse('story-worktree-adopt-path-invalid');
281
- let canonical;
282
- try {
283
- canonical = await realpath(input.worktreePath);
284
- }
285
- catch {
286
- refuse('story-worktree-adopt-unregistered');
287
- }
288
- const list = await this.listWorktrees(facts);
289
- const index = list.findIndex((item) => this.samePath(item.path, canonical));
290
- if (index === 0)
291
- refuse('story-worktree-adopt-main-refused');
292
- if (index < 0)
293
- refuse('story-worktree-adopt-unregistered');
294
- const listed = list[index];
295
- if (!listed.branch)
296
- refuse('story-worktree-adopt-detached');
297
- if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(listed.branch) || listed.branch.includes('..')) {
298
- refuse('story-worktree-adopt-branch-invalid');
299
- }
300
- if (PROTECTED_BRANCH.test(listed.branch) || listed.branch === list[0]?.branch
301
- || await gitOk(facts.mainRoot, ['config', '--get', `branch.${listed.branch}.remote`])) {
302
- refuse('story-worktree-adopt-branch-protected');
303
- }
304
- const document = await this.readDocument();
305
- const entries = document.storyWorktrees?.entries ?? {};
306
- const existing = entries[identity.leaseId];
307
- if (existing) {
308
- // P225.08-ADR-3: re-adoption of the same identity/path keeps working
309
- // after the child committed, as long as HEAD still descends from base.
310
- if (this.samePath(existing.worktreePath, canonical) && existing.state === 'active' && await this.ownershipProven(existing, facts)) {
311
- if (!await gitOk(canonical, ['merge-base', '--is-ancestor', input.baseSha, 'HEAD']))
312
- refuse('story-worktree-base-divergent');
313
- await this.assertNoCleanupInProgress(facts, existing.leaseId);
314
- return { ok: true, value: this.leaseValue(existing, true), privatePath: existing.worktreePath };
315
- }
316
- refuse('story-worktree-entry-conflict');
317
- }
318
- if (Object.values(entries).some((item) => this.samePath(item.worktreePath, canonical)))
319
- refuse('story-worktree-entry-conflict');
320
- // P225.08-ADR-1/2: a new adoption needs the exact authorized base and a
321
- // clean checkout; both are verified before the marker or journal write.
322
- const head = await gitValue(canonical, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
323
- if (head !== input.baseSha)
324
- refuse('native-worktree-base-mismatch');
325
- const status = await git(canonical, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
326
- if (!status.ok)
327
- refuse('story-worktree-git-failed');
328
- if (!await this.clean(canonical))
329
- refuse('native-worktree-dirty');
330
- const gitDir = await this.worktreeGitDir(canonical, facts);
331
- const markerPath = join(gitDir, STORY_WORKTREE_MARKER_FILE);
332
- if (await pathExists(markerPath)) {
333
- // Only an orphan marker of this same identity (crash before the
334
- // journal write, no entry) may be replaced; anything else is foreign.
335
- if (await this.markerLeaseId(markerPath) !== identity.leaseId)
336
- refuse('story-worktree-marker-exists');
337
- await unlink(markerPath);
338
- }
339
- const nonce = this.randomNonce();
340
- const acquired = this.now();
341
- const entry = {
342
- schemaVersion: 1,
343
- leaseId: identity.leaseId,
344
- epicId: identity.epicId,
345
- storyId: identity.storyId,
346
- dispatchDigest: sha256(identity.dispatchId),
347
- hash8: identity.hash8,
348
- executionBranch: identity.executionBranch,
349
- temporaryBranch: listed.branch,
350
- worktreeRef: identity.worktreeRef,
351
- worktreePath: canonical,
352
- workspaceMechanism: 'native_subagent_worktree',
353
- ownerId: this.ownerId(input.ownerId, nonce),
354
- nonceDigest: sha256(nonce),
355
- baseSha: input.baseSha,
356
- graphRevision: input.graphRevision,
357
- state: 'active',
358
- acquiredAt: acquired.toISOString(),
359
- expiresAt: new Date(acquired.getTime() + (this.options.ttlMs ?? DEFAULT_TTL_MS)).toISOString(),
360
- };
361
- await writeFile(markerPath, `${JSON.stringify({ schemaVersion: 1, leaseId: entry.leaseId, nonce })}\n`, { flag: 'wx', mode: 0o600 });
362
- try {
363
- await this.mutate((doc) => {
364
- const journal = ensureStoryWorktreeJournal(doc);
365
- if (journal.entries[entry.leaseId]
366
- || Object.values(journal.entries).some((item) => this.samePath(item.worktreePath, canonical))) {
367
- refuse('story-worktree-entry-conflict');
368
- }
369
- journal.entries[entry.leaseId] = entry;
370
- });
371
- }
372
- catch (error) {
373
- await this.removeOwnMarker(markerPath, nonce);
374
- throw error;
375
- }
376
- return { ok: true, value: this.leaseValue(entry, false), privatePath: canonical };
377
- });
378
- }
379
- async sync(input) {
380
- return this.guard(async () => {
381
- const facts = await this.repository();
382
- const entry = await this.ownedEntry(input.leaseId, facts);
383
- let integratedSha = input.integratedSha;
384
- if (input.directive !== undefined) {
385
- const directive = input.directive;
386
- if (!isDependencyReleaseDirective(input.directive)
387
- || directive.epicId !== entry.epicId || directive.storyId !== entry.storyId
388
- || (integratedSha !== undefined && integratedSha !== directive.integratedEpicHeadSha)) {
389
- refuse('story-worktree-directive-invalid');
390
- }
391
- integratedSha = String(directive.integratedEpicHeadSha);
392
- }
393
- if (typeof integratedSha !== 'string' || !FULL_SHA.test(integratedSha))
394
- refuse('story-worktree-sync-sha-invalid');
395
- if (!await this.clean(entry.worktreePath))
396
- refuse('story-worktree-dirty');
397
- const epicHead = await this.epicHead(facts, entry.executionBranch);
398
- if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', integratedSha, epicHead])) {
399
- refuse('story-worktree-sync-sha-unintegrated');
400
- }
401
- let outcome = 'already-synced';
402
- if (!await gitOk(entry.worktreePath, ['merge-base', '--is-ancestor', integratedSha, 'HEAD'])) {
403
- const merged = await git(entry.worktreePath, ['merge', '--no-edit', integratedSha]);
404
- if (!merged.ok) {
405
- const unmerged = await git(entry.worktreePath, ['diff', '--name-only', '--diff-filter=U', '-z']);
406
- const conflictPaths = unmerged.stdout.split('\0').filter(safeConflictPath).sort().slice(0, MAX_CONFLICT_PATHS);
407
- if (conflictPaths.length === 0)
408
- refuse('story-worktree-sync-failed');
409
- return { ok: false, reasonCode: 'story-worktree-sync-conflict', conflictPaths };
410
- }
411
- outcome = 'synced';
412
- }
413
- const headSha = await gitValue(entry.worktreePath, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
414
- await this.mutate((document) => {
415
- const journal = ensureStoryWorktreeJournal(document);
416
- const current = journal.entries[entry.leaseId];
417
- if (!current || current.nonceDigest !== entry.nonceDigest)
418
- refuse('story-worktree-entry-conflict');
419
- journal.entries[entry.leaseId] = { ...current, syncedSha: integratedSha };
420
- });
421
- return { ok: true, value: { leaseId: entry.leaseId, outcome, integratedSha, headSha } };
422
- });
423
- }
424
- async status(input) {
425
- return this.guard(async () => {
426
- if ((input.leaseId === undefined) === (input.epicId === undefined))
427
- refuse('story-worktree-status-selector-invalid');
428
- if (input.leaseId !== undefined && !LEASE_ID.test(input.leaseId))
429
- refuse('story-worktree-lease-invalid');
430
- if (input.epicId !== undefined && !EPIC_ID.test(input.epicId))
431
- refuse('story-worktree-identity-invalid');
432
- const facts = await this.repository();
433
- const entries = Object.values((await this.readDocument()).storyWorktrees?.entries ?? {})
434
- .filter((entry) => (input.leaseId ? entry.leaseId === input.leaseId : entry.epicId === input.epicId))
435
- .sort((left, right) => left.leaseId.localeCompare(right.leaseId));
436
- if (input.leaseId && entries.length === 0)
437
- refuse('story-worktree-lease-unknown');
438
- const projected = [];
439
- for (const entry of entries)
440
- projected.push(await this.project(entry, facts));
441
- return { ok: true, value: { entries: projected } };
442
- });
443
- }
444
- async release(input) {
445
- return this.guard(async () => {
446
- const facts = await this.repository();
447
- const entry = await this.ownedEntry(input.leaseId, facts);
448
- if (!await this.clean(entry.worktreePath))
449
- refuse('story-worktree-dirty');
450
- const head = await gitValue(entry.worktreePath, ['rev-parse', 'HEAD'], 'story-worktree-git-failed');
451
- const epicHead = await this.epicHead(facts, entry.executionBranch);
452
- if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', head, epicHead]))
453
- refuse('story-worktree-not-integrated');
454
- // `git worktree remove` without --force refuses modified/untracked
455
- // trees; ignored files (build output, local env files) are disposable
456
- // by contract and are removed with the worktree (spec ADR-7).
457
- if (!await gitOk(facts.mainRoot, ['worktree', 'remove', entry.worktreePath]))
458
- refuse('story-worktree-remove-failed');
459
- await git(facts.mainRoot, ['worktree', 'prune']);
460
- let preservedReasonCode;
461
- if (entry.workspaceMechanism === 'native_subagent_worktree') {
462
- // The branch was created by the native harness, not by this tool.
463
- preservedReasonCode = 'story-worktree-adopted-branch-preserved';
464
- }
465
- else if (!await gitOk(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, head])) {
466
- // Compare-and-swap on the verified HEAD: a commit that landed after
467
- // the integration proof keeps the branch (and its reflog) intact.
468
- preservedReasonCode = 'story-worktree-branch-moved';
469
- }
470
- const localBranchRemoved = preservedReasonCode === undefined;
471
- const cleanedAt = this.now().toISOString();
472
- const receipt = {
473
- schemaVersion: 1,
474
- kind: 'cleanup-receipt',
475
- receiptId: `swc-${sha256(`${entry.leaseId}|${entry.nonceDigest}|${cleanedAt}`).slice(0, 24)}`,
476
- epicId: entry.epicId,
477
- storyId: entry.storyId,
478
- leaseId: entry.leaseId,
479
- trigger: 'success',
480
- worktreeRemoved: true,
481
- localBranchRemoved,
482
- remoteBranchRemoved: false,
483
- ...(preservedReasonCode ? { preservedReasonCode } : {}),
484
- cleanedAt,
485
- };
486
- if (!isStoryWorktreeCleanupReceiptRecord(receipt))
487
- refuse('story-worktree-receipt-invalid');
488
- await this.mutate((document) => {
489
- const journal = ensureStoryWorktreeJournal(document);
490
- const current = journal.entries[entry.leaseId];
491
- if (current && current.nonceDigest === entry.nonceDigest)
492
- delete journal.entries[entry.leaseId];
493
- journal.cleanupReceipts.push({ ...receipt });
494
- while (journal.cleanupReceipts.length > STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS)
495
- journal.cleanupReceipts.shift();
496
- });
497
- return { ok: true, value: { leaseId: entry.leaseId, receipt, receiptDigest: digestStoryWorktreeReceiptLocal(receipt) } };
498
- });
499
- }
500
- /** P225.06: private ownership/integration probe for the cleanup module. */
501
- async probe(leaseId) {
502
- return this.guard(async () => {
503
- if (typeof leaseId !== 'string' || !LEASE_ID.test(leaseId))
504
- refuse('story-worktree-lease-invalid');
505
- const facts = await this.repository();
506
- const entry = (await this.readDocument()).storyWorktrees?.entries[leaseId];
507
- if (!entry)
508
- refuse('story-worktree-lease-unknown');
509
- const list = await this.listWorktrees(facts);
510
- const registered = list.some((item, index) => index > 0 && this.samePath(item.path, entry.worktreePath));
511
- const branchCheckedOut = list.some((item) => item.branch === entry.temporaryBranch);
512
- const branch = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.temporaryBranch}^{commit}`]);
513
- const branchSha = branch.ok && FULL_SHA.test(branch.stdout.trim()) ? branch.stdout.trim() : undefined;
514
- const epic = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.executionBranch}^{commit}`]);
515
- const epicHead = epic.ok && FULL_SHA.test(epic.stdout.trim()) ? epic.stdout.trim() : undefined;
516
- const pathPresent = await pathExists(entry.worktreePath);
517
- const proven = entry.state === 'active' && pathPresent && await this.ownershipProven(entry, facts);
518
- let headSha;
519
- let clean;
520
- if (proven) {
521
- const head = await git(entry.worktreePath, ['rev-parse', 'HEAD']);
522
- if (head.ok && FULL_SHA.test(head.stdout.trim()))
523
- headSha = head.stdout.trim();
524
- clean = await this.clean(entry.worktreePath);
525
- }
526
- const tip = headSha ?? (pathPresent ? undefined : branchSha);
527
- const integrated = tip && epicHead ? await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', tip, epicHead]) : undefined;
528
- return {
529
- ok: true,
530
- value: {
531
- entry, facts, ownership: proven ? 'proven' : 'unproven', pathExists: pathPresent, registered,
532
- ...(branchSha ? { branchSha } : {}), branchCheckedOut,
533
- ...(headSha ? { headSha } : {}), ...(clean !== undefined ? { clean } : {}),
534
- ...(epicHead ? { epicHead } : {}), ...(integrated !== undefined ? { integrated } : {}),
535
- },
536
- };
537
- });
538
- }
539
- /** Registered secondary worktrees of this repository (canonical private paths). */
540
- async registeredWorktrees() {
541
- return this.guard(async () => {
542
- const facts = await this.repository();
543
- return { ok: true, value: { facts, worktrees: (await this.listWorktrees(facts)).slice(1) } };
544
- });
545
- }
546
- /** Canonical path comparison for the current platform. */
547
- sameWorktreePath(left, right) {
548
- return this.samePath(left, right);
549
- }
550
- /**
551
- * P225.06 failure/abandon hook: bundle unintegrated work, then remove the
552
- * worktree (or leave it `remove-pending`). Delegates to the cleanup module.
553
- */
554
- async fail(input) {
555
- const { StoryWorktreeCleanup } = await import('./story-worktree-cleanup.js');
556
- return new StoryWorktreeCleanup({ manager: this, projectRoot: this.projectRoot, now: this.now })
557
- .cleanup({ leaseId: input.leaseId, trigger: input.trigger ?? 'failure', ...(input.dryRun ? { dryRun: true } : {}) });
558
- }
559
- async abandon(input) {
560
- return this.fail({ ...input, trigger: 'abandon' });
561
- }
562
- // ---------------------------------------------------------------- helpers
563
- async guard(run) {
564
- try {
565
- return await run();
566
- }
567
- catch (error) {
568
- if (error instanceof StoryWorktreeRefusal)
569
- return { ok: false, reasonCode: error.reasonCode };
570
- const message = error instanceof Error ? error.message : '';
571
- // Lifecycle-store errors are already stable public reason codes.
572
- if (/^git-lifecycle-[a-z0-9-]{1,80}$/.test(message))
573
- return { ok: false, reasonCode: message };
574
- return { ok: false, reasonCode: 'story-worktree-internal-error' };
575
- }
576
- }
577
- identity(input) {
578
- const result = storyWorktreeIdentity(input);
579
- if (!result.ok)
580
- refuse(result.reasonCode);
581
- if (input.ownerId !== undefined && !OPAQUE_ID.test(input.ownerId))
582
- refuse('story-worktree-owner-invalid');
583
- return result.value;
584
- }
585
- /** P225.06: a worktree under cleanup (or with an untrusted sidecar) is never handed out again. */
586
- async assertNoCleanupInProgress(facts, leaseId) {
587
- const { storyWorktreeCleanupInProgress } = await import('./story-worktree-cleanup.js');
588
- if (await storyWorktreeCleanupInProgress(facts.commonDir, leaseId, this.now().getTime())) {
589
- refuse('story-worktree-cleanup-in-progress');
590
- }
591
- }
592
- ownerId(explicit, nonce) {
593
- return explicit ?? `owner-${sha256(`owner|${nonce}`).slice(0, 16)}`;
594
- }
595
- async repository() {
596
- let start;
597
- try {
598
- start = await realpath(this.projectRoot);
599
- }
600
- catch {
601
- refuse('story-worktree-project-root-invalid');
602
- }
603
- const commonRaw = await gitValue(start, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'story-worktree-project-root-invalid');
604
- const commonDir = await realpath(commonRaw);
605
- const list = parseWorktreeList(await gitValue(start, ['worktree', 'list', '--porcelain', '-z'], 'story-worktree-git-failed'));
606
- const main = list[0];
607
- if (!main)
608
- refuse('story-worktree-project-root-invalid');
609
- return { mainRoot: await realpath(main.path), commonDir };
610
- }
611
- async assertAuthorizedBase(facts, executionBranch, baseSha, graphRevision) {
612
- if (typeof graphRevision !== 'string' || !SHA256.test(graphRevision))
613
- refuse('story-worktree-graph-revision-invalid');
614
- if (typeof baseSha !== 'string' || !FULL_SHA.test(baseSha)
615
- || !await gitOk(facts.mainRoot, ['cat-file', '-e', `${baseSha}^{commit}`])) {
616
- refuse('story-worktree-base-invalid');
617
- }
618
- const epicHead = await this.epicHead(facts, executionBranch);
619
- if (!await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', baseSha, epicHead]))
620
- refuse('story-worktree-base-divergent');
621
- }
622
- async epicHead(facts, executionBranch) {
623
- return gitValue(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${executionBranch}^{commit}`], 'story-worktree-epic-branch-missing');
624
- }
625
- async worktreeGitDir(worktreePath, facts) {
626
- const gitDir = await realpath(await gitValue(worktreePath, ['rev-parse', '--absolute-git-dir'], 'story-worktree-git-failed'));
627
- const common = await realpath(await gitValue(worktreePath, ['rev-parse', '--path-format=absolute', '--git-common-dir'], 'story-worktree-git-failed'));
628
- const worktreesDir = join(facts.commonDir, 'worktrees');
629
- if (common !== facts.commonDir || (!gitDir.startsWith(`${worktreesDir}/`) && !gitDir.startsWith(`${worktreesDir}\\`))) {
630
- refuse('story-worktree-foreign-repository');
631
- }
632
- return gitDir;
633
- }
634
- async enableWindowsLongPaths(facts, worktreePath) {
635
- // Concurrent creations may contend on config.lock: retry, bounded.
636
- const configure = async (cwd, args) => {
637
- for (let attempt = 1; attempt <= 8; attempt++) {
638
- if (await gitOk(cwd, args))
639
- return;
640
- await sleep(25 * attempt);
641
- }
642
- refuse('story-worktree-config-failed');
643
- };
644
- const enabled = await git(facts.mainRoot, ['config', '--get', 'extensions.worktreeConfig']);
645
- if (!enabled.ok || enabled.stdout.trim() !== 'true')
646
- await configure(facts.mainRoot, ['config', 'extensions.worktreeConfig', 'true']);
647
- await configure(worktreePath, ['config', '--worktree', 'core.longPaths', 'true']);
648
- }
649
- async ownershipProven(entry, facts) {
650
- try {
651
- if (await realpath(entry.worktreePath) !== entry.worktreePath)
652
- return false;
653
- const gitDir = await this.worktreeGitDir(entry.worktreePath, facts);
654
- const marker = JSON.parse(await readFile(join(gitDir, STORY_WORKTREE_MARKER_FILE), 'utf8'));
655
- if (marker.schemaVersion !== 1 || marker.leaseId !== entry.leaseId || typeof marker.nonce !== 'string'
656
- || sha256(marker.nonce) !== entry.nonceDigest)
657
- return false;
658
- const list = await this.listWorktrees(facts);
659
- const index = list.findIndex((item) => this.samePath(item.path, entry.worktreePath));
660
- return index > 0 && list[index].branch === entry.temporaryBranch;
661
- }
662
- catch {
663
- return false;
664
- }
665
- }
666
- async ownedEntry(leaseId, facts) {
667
- if (typeof leaseId !== 'string' || !LEASE_ID.test(leaseId))
668
- refuse('story-worktree-lease-invalid');
669
- const entry = (await this.readDocument()).storyWorktrees?.entries[leaseId];
670
- if (!entry)
671
- refuse('story-worktree-lease-unknown');
672
- if (entry.state !== 'active' || !await this.ownershipProven(entry, facts))
673
- refuse('story-worktree-ownership-unproven');
674
- return entry;
675
- }
676
- async clean(worktreePath) {
677
- const status = await git(worktreePath, ['status', '--porcelain=v1', '--untracked-files=all', '-z']);
678
- if (!status.ok || status.stdout.length > 0)
679
- return false;
680
- const mergeHead = await git(worktreePath, ['rev-parse', '-q', '--verify', 'MERGE_HEAD']);
681
- return !mergeHead.ok;
682
- }
683
- async project(entry, facts) {
684
- const base = {
685
- leaseId: entry.leaseId,
686
- epicId: entry.epicId,
687
- storyId: entry.storyId,
688
- worktreeId: `nxwt-${entry.hash8}`,
689
- worktreeRef: entry.worktreeRef,
690
- temporaryBranch: entry.temporaryBranch,
691
- workspaceMechanism: entry.workspaceMechanism,
692
- state: entry.state,
693
- baseSha: entry.baseSha,
694
- ...(entry.syncedSha ? { syncedSha: entry.syncedSha } : {}),
695
- ownership: 'unproven',
696
- expiresAt: entry.expiresAt,
697
- };
698
- if (entry.state !== 'active' || !await this.ownershipProven(entry, facts))
699
- return base;
700
- const head = await git(entry.worktreePath, ['rev-parse', 'HEAD']);
701
- const headSha = head.stdout.trim();
702
- if (!head.ok || !FULL_SHA.test(headSha))
703
- return { ...base, ownership: 'proven' };
704
- const epicHead = await git(facts.mainRoot, ['rev-parse', '--verify', '--quiet', `refs/heads/${entry.executionBranch}^{commit}`]);
705
- const integrated = epicHead.ok
706
- && await gitOk(facts.mainRoot, ['merge-base', '--is-ancestor', headSha, epicHead.stdout.trim()]);
707
- return { ...base, ownership: 'proven', headSha, clean: await this.clean(entry.worktreePath), integrated };
708
- }
709
- leaseValue(entry, reused) {
710
- const lease = {
711
- schemaVersion: 1,
712
- kind: 'story-worktree-lease',
713
- leaseId: entry.leaseId,
714
- epicId: entry.epicId,
715
- storyId: entry.storyId,
716
- executionBranch: entry.executionBranch,
717
- temporaryBranch: entry.temporaryBranch,
718
- worktreeRef: entry.worktreeRef,
719
- workspaceMechanism: entry.workspaceMechanism,
720
- ownerId: entry.ownerId,
721
- baseSha: entry.baseSha,
722
- graphRevision: entry.graphRevision,
723
- acquiredAt: entry.acquiredAt,
724
- expiresAt: entry.expiresAt,
725
- };
726
- const worktreeId = `nxwt-${entry.hash8}`;
727
- return {
728
- lease,
729
- leaseDigest: digestStoryWorktreeReceiptLocal(lease),
730
- worktreeId,
731
- worktreeRef: entry.worktreeRef,
732
- temporaryBranch: entry.temporaryBranch,
733
- baseSha: entry.baseSha,
734
- reused,
735
- env: { [STORY_WORKTREE_ID_ENV]: worktreeId },
736
- };
737
- }
738
- async rollbackCreate(facts, entry, added) {
739
- if (added) {
740
- // The worktree was created by this call and holds no child work yet.
741
- await git(facts.mainRoot, ['worktree', 'remove', entry.worktreePath]);
742
- await git(facts.mainRoot, ['worktree', 'prune']);
743
- }
744
- // `worktree add -b` may leave the new branch behind on checkout failure.
745
- // Delete it only while it is unchecked-out and still at the base (CAS).
746
- const list = await this.listWorktrees(facts).catch(() => undefined);
747
- if (list && !list.some((item) => item.branch === entry.temporaryBranch)) {
748
- await git(facts.mainRoot, ['update-ref', '-d', `refs/heads/${entry.temporaryBranch}`, entry.baseSha]);
749
- }
750
- await this.mutate((document) => {
751
- const journal = ensureStoryWorktreeJournal(document);
752
- const current = journal.entries[entry.leaseId];
753
- if (current && current.nonceDigest === entry.nonceDigest)
754
- delete journal.entries[entry.leaseId];
755
- compactStoryWorktreeJournal(document);
756
- }).catch(() => undefined);
757
- }
758
- async removeOwnMarker(markerPath, nonce) {
759
- try {
760
- const marker = JSON.parse(await readFile(markerPath, 'utf8'));
761
- if (marker.nonce === nonce)
762
- await unlink(markerPath);
763
- }
764
- catch {
765
- // Best effort: an unowned or missing marker is left untouched.
766
- }
767
- }
768
- /** `git worktree list` with every path canonicalised for comparison. */
769
- async listWorktrees(facts) {
770
- const raw = parseWorktreeList(await gitValue(facts.mainRoot, ['worktree', 'list', '--porcelain', '-z'], 'story-worktree-git-failed'));
771
- return Promise.all(raw.map(async (item) => {
772
- const native = this.platform === 'win32' ? item.path.replace(/\//g, '\\') : item.path;
773
- try {
774
- return { ...item, path: await realpath(native) };
775
- }
776
- catch {
777
- return { ...item, path: native };
778
- }
779
- }));
780
- }
781
- samePath(left, right) {
782
- if (this.platform === 'win32') {
783
- const fold = (value) => value.replace(/\//g, '\\').toLowerCase();
784
- return fold(left) === fold(right);
785
- }
786
- return this.platform === 'darwin' ? left.toLowerCase() === right.toLowerCase() : left === right;
787
- }
788
- async markerLeaseId(markerPath) {
789
- try {
790
- const marker = JSON.parse(await readFile(markerPath, 'utf8'));
791
- return typeof marker.leaseId === 'string' ? marker.leaseId : undefined;
792
- }
793
- catch {
794
- return undefined;
795
- }
796
- }
797
- /**
798
- * A `creating` reservation left by a crashed or lock-starved call is
799
- * reclaimed only when it is provably empty (no path, no branch).
800
- */
801
- async reclaimStaleReservation(entry, facts) {
802
- if (entry.state !== 'creating')
803
- return false;
804
- // Resources left behind (path or branch) belong to P225.06 recovery.
805
- const empty = !await pathExists(entry.worktreePath)
806
- && !await gitOk(facts.mainRoot, ['show-ref', '--verify', '--quiet', `refs/heads/${entry.temporaryBranch}`]);
807
- if (!empty)
808
- return false;
809
- let reclaimed = false;
810
- await this.mutate((document) => {
811
- const journal = ensureStoryWorktreeJournal(document);
812
- const current = journal.entries[entry.leaseId];
813
- if (current && current.state === 'creating' && current.nonceDigest === entry.nonceDigest) {
814
- delete journal.entries[entry.leaseId];
815
- reclaimed = true;
816
- }
817
- });
818
- return reclaimed;
819
- }
820
- async readDocument() {
821
- return readGitLifecycleRuntime(this.projectRoot);
822
- }
823
- /** Journal write under the lifecycle lock, retrying bounded lock contention. */
824
- async mutate(apply) {
825
- const attempts = this.options.lockRetry?.attempts ?? 40;
826
- const delayMs = this.options.lockRetry?.delayMs ?? 25;
827
- for (let attempt = 1;; attempt++) {
828
- try {
829
- await mutateGitLifecycleRuntime(this.projectRoot, apply);
830
- return;
831
- }
832
- catch (error) {
833
- // A holder may release between our EEXIST and the ownership probe
834
- // (ENOENT on the lock directory): that transient is contention too.
835
- const busy = error instanceof Error && (error.message === 'git-lifecycle-runtime-lock-active'
836
- || (error.code === 'ENOENT' && error.message.includes('runtime.lock')));
837
- if (!busy || attempt >= attempts)
838
- throw error;
839
- await sleep(delayMs * Math.min(attempt, 8) + Math.floor(Math.random() * delayMs));
840
- }
841
- }
842
- }
843
- }
1
+ import{execFile as U}from"node:child_process";import{createHash as K,randomBytes as Y}from"node:crypto";import{chmod as Z,lstat as X,readFile as x,realpath as R,unlink as C,writeFile as B}from"node:fs/promises";import{homedir as Q}from"node:os";import{isAbsolute as W,join as E,resolve as ee}from"node:path";import{yoloopDomainHash as te}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,compactStoryWorktreeJournal as ae,ensureStoryWorktreeJournal as b,isStoryWorktreeCleanupReceiptRecord as oe,mutateGitLifecycleRuntime as se,readGitLifecycleRuntime as ie}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as ne,ensurePrivateStoryWorktreeRoot as ce,resolveStoryWorktreePath as H,resolveStoryWorktreeRoot as de,storyWorktreeIdentity as he}from"./story-worktree-paths.js";const O="nx-owner",le="neocortex.p225.story-worktree-receipt.v1";function $(n){return te(le,n)}const j=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),we=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,M=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,fe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function ue(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==j.length||!r.every(a=>j.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&z.test(e.directiveId)&&typeof e.epicId=="string"&&V.test(e.epicId)&&typeof e.storyId=="string"&&M.test(e.storyId)&&typeof e.releasedStepId=="string"&&we.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&M.test(a))&&typeof e.integratedEpicHeadSha=="string"&&P.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&L.test(e.graphRevision)&&typeof e.issuedAt=="string"&&fe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const N=1440*60*1e3,pe=3e4,me=200,P=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,L=/^[a-f0-9]{64}$/,T=/^swt-[a-f0-9]{24}$/,z=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,V=/^P[1-9][0-9]*$/,ke=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/;class G extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new G(n)}function ye(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Ae(n,e){return w(n,e)}function w(n,e){return new Promise(r=>{U("git",[...e],{cwd:n,encoding:"utf8",env:ye(),maxBuffer:8*1024*1024,timeout:pe,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??"")}))})}async function m(n,e){return(await w(n,e)).ok}async function S(n,e,r){const t=await w(n,e);return t.ok||o(r),t.stdout.trim()}function D(n){return K("sha256").update(n).digest("hex")}async function A(n){try{return await X(n),!0}catch{return!1}}function q(n){return new Promise(e=>setTimeout(e,n))}function F(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function ge(n){return n.length>0&&n.length<=512&&!W(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class _e{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ee(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>Y(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision);const a=de({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??Q(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=H({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await ce(a.value,this.platform);c.ok||o(c.reasonCode);const i=H({root:await R(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const l=i.value,d=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(d){if(d.state==="active"&&d.baseSha===e.baseSha&&d.graphRevision===e.graphRevision&&await this.ownershipProven(d,t))return await this.assertNoCleanupInProgress(t,d.leaseId),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};await this.reclaimStaleReservation(d,t)||o("story-worktree-entry-conflict")}await A(l)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const h=this.randomNonce(),y=this.now(),f={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:D(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:l,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,h),nonceDigest:D(h),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:y.toISOString(),expiresAt:new Date(y.getTime()+(this.options.ttlMs??N)).toISOString()};await this.mutate(p=>{const k=b(p);(k.entries[f.leaseId]||Object.values(k.entries).some(v=>v.worktreePath===l))&&o("story-worktree-entry-conflict"),k.entries[f.leaseId]=f});let I=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,l,e.baseSha])||o("story-worktree-add-failed"),I=!0,this.platform!=="win32"?await Z(l,448):await this.enableWindowsLongPaths(t,l);const p=await this.worktreeGitDir(l,t);await B(E(p,O),`${JSON.stringify({schemaVersion:1,leaseId:f.leaseId,nonce:h})}
2
+ `,{flag:"wx",mode:384});const k={...f,state:"active"};return await this.mutate(v=>{const u=b(v),g=u.entries[f.leaseId];(!g||g.state!=="creating"||g.nonceDigest!==f.nonceDigest)&&o("story-worktree-entry-conflict"),u.entries[f.leaseId]=k}),{ok:!0,value:this.leaseValue(k,!1),privatePath:l}}catch(p){throw await this.rollbackCreate(t,f,I),p}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),(typeof e.worktreePath!="string"||!W(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await R(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(g=>this.samePath(g.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(ke.test(i.branch)||i.branch===s[0]?.branch||await m(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const d=(await this.readDocument()).storyWorktrees?.entries??{},h=d[r.leaseId];if(h){if(this.samePath(h.worktreePath,a)&&h.state==="active"&&await this.ownershipProven(h,t))return await m(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,h.leaseId),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};o("story-worktree-entry-conflict")}Object.values(d).some(g=>this.samePath(g.worktreePath,a))&&o("story-worktree-entry-conflict"),await S(a,["rev-parse","HEAD"],"story-worktree-git-failed")!==e.baseSha&&o("native-worktree-base-mismatch"),(await w(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed"),await this.clean(a)||o("native-worktree-dirty");const I=await this.worktreeGitDir(a,t),p=E(I,O);await A(p)&&(await this.markerLeaseId(p)!==r.leaseId&&o("story-worktree-marker-exists"),await C(p));const k=this.randomNonce(),v=this.now(),u={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:D(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:i.branch,worktreeRef:r.worktreeRef,worktreePath:a,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(e.ownerId,k),nonceDigest:D(k),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"active",acquiredAt:v.toISOString(),expiresAt:new Date(v.getTime()+(this.options.ttlMs??N)).toISOString()};await B(p,`${JSON.stringify({schemaVersion:1,leaseId:u.leaseId,nonce:k})}
3
+ `,{flag:"wx",mode:384});try{await this.mutate(g=>{const _=b(g);(_.entries[u.leaseId]||Object.values(_.entries).some(J=>this.samePath(J.worktreePath,a)))&&o("story-worktree-entry-conflict"),_.entries[u.leaseId]=u})}catch(g){throw await this.removeOwnMarker(p,k),g}return{ok:!0,value:this.leaseValue(u,!1),privatePath:a}})}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const l=e.directive;(!ue(e.directive)||l.epicId!==t.epicId||l.storyId!==t.storyId||a!==void 0&&a!==l.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(l.integratedEpicHeadSha)}(typeof a!="string"||!P.test(a))&&o("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(!await m(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await w(t.worktreePath,["merge","--no-edit",a])).ok){const h=(await w(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(ge).sort().slice(0,me);return h.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:h}}c="synced"}const i=await S(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(l=>{const d=b(l),h=d.entries[t.leaseId];(!h||h.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),d.entries[t.leaseId]={...h,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{e.leaseId===void 0==(e.epicId===void 0)&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!T.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!V.test(e.epicId)&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await S(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await m(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await w(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await m(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,l=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${D(`${t.leaseId}|${t.nonceDigest}|${l}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:l};return oe(d)||o("story-worktree-receipt-invalid"),await this.mutate(h=>{const y=b(h),f=y.entries[t.leaseId];for(f&&f.nonceDigest===t.nonceDigest&&delete y.entries[t.leaseId],y.cleanupReceipts.push({...d});y.cleanupReceipts.length>re;)y.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:d,receiptDigest:$(d)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!T.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((u,g)=>g>0&&this.samePath(u.path,t.worktreePath)),c=a.some(u=>u.branch===t.temporaryBranch),i=await w(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),l=i.ok&&P.test(i.stdout.trim())?i.stdout.trim():void 0,d=await w(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),h=d.ok&&P.test(d.stdout.trim())?d.stdout.trim():void 0,y=await A(t.worktreePath),f=t.state==="active"&&y&&await this.ownershipProven(t,r);let I,p;if(f){const u=await w(t.worktreePath,["rev-parse","HEAD"]);u.ok&&P.test(u.stdout.trim())&&(I=u.stdout.trim()),p=await this.clean(t.worktreePath)}const k=I??(y?void 0:l),v=k&&h?await m(r.mainRoot,["merge-base","--is-ancestor",k,h]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:f?"proven":"unproven",pathExists:y,registered:s,...l?{branchSha:l}:{},branchCheckedOut:c,...I?{headSha:I}:{},...p!==void 0?{clean:p}:{},...h?{epicHead:h}:{},...v!==void 0?{integrated:v}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof G)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=he(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!z.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${D(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await R(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await S(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await R(r),s=F(await S(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await R(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!L.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!P.test(t)||!await m(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await m(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return S(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await R(await S(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await R(await S(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=E(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await m(s,c))return;await q(25*i)}o("story-worktree-config-failed")},a=await w(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await R(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await x(E(t,O),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||D(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!T.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async clean(e){const r=await w(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await w(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await w(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!P.test(s))return{...t,ownership:"proven"};const c=await w(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await m(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:$(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[ne]:a}}}async rollbackCreate(e,r,t){t&&(await w(e.mainRoot,["worktree","remove",r.worktreePath]),await w(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await w(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=b(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ae(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await x(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=F(await S(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await R(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await x(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await A(e.worktreePath)&&!await m(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=b(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return ie(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await se(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await q(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{O as STORY_WORKTREE_MARKER_FILE,le as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,_e as StoryWorktreeManager,$ as digestStoryWorktreeReceiptLocal,F as parseWorktreeList,Ae as runStoryWorktreeGit};