@ornexus/neocortex 4.60.78 → 4.60.80

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 (247) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1206
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +214 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +443 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +260 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +338 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +358 -5
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.js +635 -2
  37. package/packages/client/dist/commands/invoke.js +7712 -143
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  39. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  40. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  42. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  43. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  44. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  45. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  47. package/packages/client/dist/commands/mutation-qa.js +220 -1
  48. package/packages/client/dist/commands/native-agent.js +136 -2
  49. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  50. package/packages/client/dist/commands/planning-generation.js +53 -1
  51. package/packages/client/dist/commands/planning-memory.js +40 -1
  52. package/packages/client/dist/commands/planning-research.js +42 -1
  53. package/packages/client/dist/commands/private-session.js +75 -1
  54. package/packages/client/dist/commands/property-qa.js +139 -1
  55. package/packages/client/dist/commands/qa-control.js +16 -1
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  58. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  59. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  60. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  66. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  67. package/packages/client/dist/commands/refactor-commit.js +399 -13
  68. package/packages/client/dist/commands/refactor-control.js +142 -3
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  70. package/packages/client/dist/commands/refactor-review.js +283 -5
  71. package/packages/client/dist/commands/refactor-root.js +588 -7
  72. package/packages/client/dist/commands/refresh-memory.d.ts +3 -1
  73. package/packages/client/dist/commands/refresh-memory.js +174 -3
  74. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  76. package/packages/client/dist/config/host-auth-broker.js +60 -1
  77. package/packages/client/dist/config/host-auth-reference.js +93 -1
  78. package/packages/client/dist/config/profile-directory.js +13 -1
  79. package/packages/client/dist/config/resolver-selection.js +278 -1
  80. package/packages/client/dist/config/secure-config.js +281 -12
  81. package/packages/client/dist/config.js +223 -2
  82. package/packages/client/dist/constants.js +25 -1
  83. package/packages/client/dist/context/context-collector.js +222 -2
  84. package/packages/client/dist/context/context-sanitizer.js +145 -1
  85. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  86. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  87. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  88. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  89. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  90. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  91. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  92. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  93. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  94. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  95. package/packages/client/dist/continuity/native-agent-types.js +105 -1
  96. package/packages/client/dist/continuity/outbox.js +117 -1
  97. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  98. package/packages/client/dist/continuity/sqlite-store.js +2612 -81
  99. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  100. package/packages/client/dist/errors/error-messages.js +258 -2
  101. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  102. package/packages/client/dist/evidence/collector.js +347 -1
  103. package/packages/client/dist/evidence/index.js +1 -1
  104. package/packages/client/dist/evidence/types.js +2 -0
  105. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  106. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  107. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  108. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  109. package/packages/client/dist/git/direct-yolo-checkpoint.js +1456 -4
  110. package/packages/client/dist/git/epic-operational-state.js +672 -2
  111. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  112. package/packages/client/dist/git/git-lifecycle-store.js +2188 -10
  113. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  114. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  115. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  116. package/packages/client/dist/git/neocortex-trailers.d.ts +26 -0
  117. package/packages/client/dist/git/neocortex-trailers.js +53 -0
  118. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  119. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  120. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  121. package/packages/client/dist/i18n/first-run.js +60 -2
  122. package/packages/client/dist/index.js +50 -1
  123. package/packages/client/dist/invocation/invoke-input.js +24 -1
  124. package/packages/client/dist/license/host-auth-recovery.js +401 -1
  125. package/packages/client/dist/license/index.js +5 -1
  126. package/packages/client/dist/license/license-client.js +337 -1
  127. package/packages/client/dist/machine/fingerprint.js +163 -2
  128. package/packages/client/dist/machine/index.js +5 -1
  129. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  130. package/packages/client/dist/memory/project-memory-writer.d.ts +16 -1
  131. package/packages/client/dist/memory/project-memory-writer.js +1117 -41
  132. package/packages/client/dist/memory/shared-project-memory-types.js +259 -2
  133. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -3
  134. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  135. package/packages/client/dist/migrations/project-identity.js +493 -7
  136. package/packages/client/dist/migrations/state-json.js +393 -4
  137. package/packages/client/dist/policy/architecture-policy.js +184 -2
  138. package/packages/client/dist/policy/index.js +7 -1
  139. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  140. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  141. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  142. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  143. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  144. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  145. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  146. package/packages/client/dist/private-execution/delivery.js +410 -13
  147. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  148. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  149. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  150. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  151. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  152. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  153. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  154. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  155. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  156. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  157. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  158. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  159. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  160. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  161. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  162. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  163. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  164. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  165. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  166. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  167. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  168. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  169. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  170. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  171. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  172. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  173. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  174. package/packages/client/dist/private-execution/session-lease.js +63 -1
  175. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  176. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  177. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  178. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  179. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  180. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  181. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  182. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  183. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  184. package/packages/client/dist/resilience/index.js +8 -1
  185. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  186. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  187. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  188. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  189. package/packages/client/dist/runner/binary.js +404 -1
  190. package/packages/client/dist/runner/cli.js +1571 -17
  191. package/packages/client/dist/runner/epic-background-dispatcher.js +124 -1
  192. package/packages/client/dist/runner/headless/adapters.js +49 -1
  193. package/packages/client/dist/runner/headless/background-root.js +85 -1
  194. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  195. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  196. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  197. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +111 -2
  198. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1464 -10
  199. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +357 -2
  200. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  201. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +274 -1
  202. package/packages/client/dist/runner/headless/managed-profile.js +149 -1
  203. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  204. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  205. package/packages/client/dist/runner/headless/resolver.js +231 -1
  206. package/packages/client/dist/runner/headless/run-yolo.js +886 -1
  207. package/packages/client/dist/runner/headless/run-yoloop.js +2586 -2
  208. package/packages/client/dist/runner/headless/types.js +575 -2
  209. package/packages/client/dist/runner/host-capacity.js +59 -1
  210. package/packages/client/dist/runner/local-console.js +396 -13
  211. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  212. package/packages/client/dist/runner/project-identity.js +106 -1
  213. package/packages/client/dist/runner/scheduler.js +995 -7
  214. package/packages/client/dist/runner-cli.js +18 -2
  215. package/packages/client/dist/state/invocation-shape.js +13 -1
  216. package/packages/client/dist/state/project-state-snapshot.js +1751 -1
  217. package/packages/client/dist/state/state-json-repair.js +785 -3
  218. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  219. package/packages/client/dist/telemetry/index.js +5 -1
  220. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  221. package/packages/client/dist/tier/index.js +5 -1
  222. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  223. package/packages/client/dist/types/index.js +38 -1
  224. package/packages/client/dist/version.js +27 -1
  225. package/packages/client/dist/yolo/change-evidence-collector.d.ts +1 -1
  226. package/packages/client/dist/yolo/change-evidence-collector.js +245 -1
  227. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  228. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  229. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  230. package/packages/client/dist/yoloop/index.js +8 -1
  231. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  232. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  233. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  234. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  235. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
  236. package/packages/shared/dist/yoloop/epic-terminal-git.js +12 -0
  237. package/targets-stubs/antigravity/gemini.md +1 -1
  238. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  239. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  240. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  241. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  242. package/targets-stubs/claude-code/neocortex.md +2 -2
  243. package/targets-stubs/codex/AGENTS.md +1 -1
  244. package/targets-stubs/cursor/agent.md +2 -2
  245. package/targets-stubs/gemini-cli/agent.md +2 -2
  246. package/targets-stubs/opencode/neocortex-root.md +1 -1
  247. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,4 +1,1456 @@
1
- import{execFile as He}from"node:child_process";import{createHash as Le,randomBytes as me,timingSafeEqual as Ce}from"node:crypto";import{readFile as Z}from"node:fs/promises";import{join as te,resolve as M}from"node:path";import{promisify as Oe}from"node:util";import{readRootMemoryEffectForCheckpoint as qe}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as $e,verifyRootMemoryPhysicalWriteSet as re}from"../private-execution/root-memory-git-evidence.js";import{acquireGitLifecyclePhysicalIntegrationLock as V,applyGitLifecycleRuntimeOverlay as Pe,computeImmutableStoryQaEvidenceDigest as ze,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as we,computeP205StoryQaEvidenceDigest as Ne,computeLegacyDirectYoloRecoveryReceiptRef as Ke,ensureRuntimeEpic as N,ensureRuntimeStory as Re,ensureGitLifecyclePrivateChildDirectory as Me,executeP205TransientAuthority as Ve,projectP205TransientExecutionEvidence as We,publicStoryReviewArtifactFromGit as Q,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Ge,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as Fe,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Te,assertGitLifecyclePrivateFile as Ie,releaseGitLifecyclePhysicalIntegrationLock as W,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as Je,verifyGitLifecyclePhysicalIntegrationLock as U,verifyAcceptedGitLifecycleStoryCheckpoint as ve}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ye}from"./secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ze,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as xe,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as X}from"./git-lifecycle-step-ids.js";const oe=Oe(He),ie=3600*1e3;async function gt(e){let t,o=!1;try{const r=await Se(e.projectRoot,e.storyId),i=K(e.nowIso),n=Date.parse(i),g=await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),s=await y(r.projectRoot,["rev-parse","HEAD"]),h=await C(r.projectRoot,{required:!0}),c=w(h.epics[r.epicId]),d=w(c?.branch_lease),l=e.expiredSetupRecovery;if(l&&!ot(l,h.revision,d,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const u=d&&Number.isFinite(Date.parse(String(d.expiresAt)))&&Date.parse(String(d.expiresAt))>n;if(u&&d?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let m=he(c?.origin_binding,r.executionBranch,r.originBranch);if(g===r.executionBranch){if(!m)return a("direct-yolo-origin-binding-invalid")}else{if(g!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(m&&m.originHeadSha!==s){if(!l||!await B(r.projectRoot,["merge-base","--is-ancestor",m.originHeadSha,s]))return a("direct-yolo-origin-binding-conflict");const p=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",p]))return a("direct-yolo-execution-branch-missing");const I=await y(r.projectRoot,["rev-parse",p]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",I,s]))return a("direct-yolo-execution-branch-diverged")}if(m??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:s,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await ye(r.projectRoot)).some(p=>p.branch===r.executionBranch&&M(p.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const f=await q(r.projectRoot),R=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",R])){const p=await y(r.projectRoot,["rev-parse",R]);if(p!==s){if(!await B(r.projectRoot,["merge-base","--is-ancestor",p,s]))return a("direct-yolo-execution-branch-diverged");l||await y(r.projectRoot,["update-ref",R,s,p])}l?t={checkoutBefore:f,executionRef:R,executionBranch:r.executionBranch,executionHead:p,originBranch:r.originBranch,originHead:s}:await y(r.projectRoot,["switch",r.executionBranch])}else{if(l)return a("direct-yolo-execution-branch-missing");await y(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await q(r.projectRoot)!==f)return a("direct-yolo-checkout-payload-raced")}const S=t?.originHead??await y(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return a("direct-yolo-current-branch-mismatch");if(u&&d?.ownerStoryId===e.storyId)return d.setupHeadSha!==S?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:pe(r,m,String(d.expiresAt),!0)};const v=i,x=new Date(n+3600*1e3).toISOString(),b=`setup-${me(32).toString("hex")}`,D=l?h:await C(r.projectRoot,{required:!0});return await P(r.projectRoot,A=>{const f=N(A,r.epicId),R=w(f.branch_lease);if(l&&JSON.stringify(R)!==JSON.stringify(l.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(R&&Date.parse(String(R.expiresAt))>n&&R.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const p=he(f.origin_binding,r.executionBranch,r.originBranch);if(f.origin_binding&&!p)throw new Error("direct-yolo-origin-binding-conflict");if(p&&JSON.stringify(p)!==JSON.stringify(m))throw new Error("direct-yolo-origin-binding-conflict");f.branch_mode="epic",f.execution_branch=r.executionBranch,f.origin_branch=r.originBranch,f.graph_revision=r.graphRevision,f.origin_binding=m,f.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:b,idempotencyKey:b,acquiredAt:v,expiresAt:x,setupHeadSha:S}},{expectedRevision:l?.expectedRuntimeRevision??D.revision,preCommit:async()=>{if(t){if((await ye(r.projectRoot)).some(f=>f.branch===r.executionBranch&&M(f.path)!==r.projectRoot)||await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await y(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await q(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await y(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await y(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await y(r.projectRoot,["switch",r.executionBranch]),await q(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await y(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await y(r.projectRoot,["rev-parse","HEAD"])!==S)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:pe(r,m,x,!1)}}catch(r){return o&&t&&await it(M(e.projectRoot),t).catch(()=>{}),a(Y(r,"direct-yolo-setup-failed"))}}async function mt(e){let t;try{const o=await F(e.projectRoot,e.storyId),r=K(e.nowIso),i=te(o.projectRoot,".neocortex/state.json"),n=await Z(i,"utf8"),g=await q(o.projectRoot),s=await y(o.projectRoot,["rev-parse","HEAD"]),h=`refs/heads/${o.executionBranch}`,c=await C(o.projectRoot,{required:!0}),d=w(c.epics[o.epicId]),l=he(d?.origin_binding,o.executionBranch,o.originBranch),u=w(d?.branch_lease);if(!l)return a("direct-yolo-origin-binding-invalid");if(!u||!ne(u,e.storyId,r)||u?.sessionId!==u?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const m=await V(o.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(u.sessionId),idempotencyKey:String(u.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!m.ok)return a(m.reasonCode);if(t=m,s!==u.setupHeadSha||!await B(o.projectRoot,["merge-base","--is-ancestor",l.originHeadSha,s])||await y(o.projectRoot,["rev-parse",h])!==s)return a("direct-yolo-setup-head-mismatch");if((await ye(o.projectRoot)).some(f=>f.branch===o.executionBranch&&M(f.path)!==o.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const v=w(JSON.parse(n)),x=w(w(v?.stories)?.[e.storyId]),b=w(c.stories[e.storyId]);if(!x||!["backlog","ready_to_start"].includes(String(x.status))||x.steps_completed!==void 0&&(!Array.isArray(x.steps_completed)||x.steps_completed.length>0)||x.branch_name||x.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const D=b?.status==="branch-ready"&&b.last_step===X&&Array.isArray(b.steps_completed)&&b.steps_completed.length===1&&b.steps_completed[0]===X&&Object.keys(b).sort().join(",")==="last_step,status,steps_completed";if(b&&Object.keys(b).length>0&&!D)return a("direct-yolo-setup-story-progress-conflict");const A=async()=>{if(Date.parse(String(u.expiresAt))<=(e.nowIso?Date.parse(r):Date.now())||!t||!await U(t.path,t.owner)||await Z(i,"utf8")!==n||await q(o.projectRoot)!==g||await y(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch||await y(o.projectRoot,["rev-parse","HEAD"])!==s||!await B(o.projectRoot,["merge-base","--is-ancestor",l.originHeadSha,s])||await y(o.projectRoot,["rev-parse",h])!==s)throw new Error("direct-yolo-setup-physical-state-raced")};return D?await A():await P(o.projectRoot,f=>{const R=w(f.epics[o.epicId]),p=Re(f,e.storyId);if(JSON.stringify(R?.branch_lease)!==JSON.stringify(u)||JSON.stringify(R?.origin_binding)!==JSON.stringify(l)||R?.graph_revision!==o.graphRevision||Object.keys(p).length>0)throw new Error("direct-yolo-setup-runtime-raced");p.status="branch-ready",p.last_step=X,p.steps_completed=[X]},{expectedRevision:c.revision,preCommit:A}),{ok:!0,value:Object.freeze({...pe(o,l,String(u.expiresAt),D),checkpointAccepted:!0,graphRevision:o.graphRevision,headSha:s})}}catch(o){return a(Y(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await W(t.path,t.owner).catch(()=>{})}}async function wt(e){try{const t=await F(e.projectRoot,e.storyId),o=O(await j(t.projectRoot,["diff","--cached","--name-only","-z"])),r=T(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return a(r.reasonCode);if(t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await y(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),Q(t.projectRoot,e.storyId,":")?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(O(await j(t.projectRoot,["diff","--name-only","-z"])).some(I=>o.includes(I)))return a("direct-yolo-user-overlap");const g=await j(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!g)return a("direct-yolo-staged-diff-empty");const s=k(g),h=k([...t.authorizedWriteSet].sort().join("\0")),c=K(e.nowIso),d=await C(t.projectRoot,{required:!0}),l=w(d.epics[t.epicId]?.branch_lease);if(!ne(l,e.storyId,c))return a("direct-yolo-setup-handoff-owner-invalid");const u=String(l.sessionId),m=String(l.expiresAt),S=new Date(Math.min(Date.parse(m),Date.parse(c)+300*1e3)).toISOString(),v=await G(t.projectRoot,e.storyId),x=v?.state==="issued"&&v.fromSessionId===u&&v.bundleDigest===s&&v.claimRevision===h&&Date.parse(v.expiresAt)>Date.parse(c),b=x?v.expiresAt:S,D=x?v.token:me(32).toString("base64url"),A=k(D),f=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:u,tokenDigest:A,bundleDigest:s,claimRevision:h,expiresAt:b}),R=k(JSON.stringify(f)),p=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:b,persistent:!1,createdAt:c});if(!p.ok)return a(p.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await ae(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:u,token:D,tokenDigest:A,bundleDigest:s,claimRevision:h,grantDigest:R,expiresAt:b}),await P(t.projectRoot,I=>{const E=w(N(I,t.epicId).branch_lease);if(!ne(E,e.storyId,c)||E?.sessionId!==u||E.idempotencyKey!==u)throw new Error("direct-yolo-setup-handoff-owner-raced");E.handoffGrant=f},{expectedRevision:d.revision,preCommit:async()=>{if(!await U(p.path,p.owner))throw new Error("direct-yolo-integration-lock-raced");const I=await G(t.projectRoot,e.storyId);if(!I||I.state!=="issued"||I.grantDigest!==R||I.tokenDigest!==A)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await W(p.path,p.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:u,bundleDigest:s,claimRevision:h,grantDigest:R,expiresAt:b,reused:x,publicSafe:!0})}}catch(t){return a(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function Rt(e){try{const t=await F(e.projectRoot,e.storyId),o=await y(t.projectRoot,["rev-parse","HEAD"]),r=O(await j(t.projectRoot,["diff","--cached","--name-only","-z"])),i=T(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&re(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=Q(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(O(await j(t.projectRoot,["diff","--name-only","-z"])).some(f=>r.includes(f)))return a("direct-yolo-user-overlap");const s=await j(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!s)return a("direct-yolo-staged-diff-empty");const h=k(s),c=k([...t.authorizedWriteSet].sort().join("\0")),d=k(["direct-yolo-commit-v1",e.storyId,t.epicId,t.executionBranch,o,h,t.graphRevision,c].join("\0")),l=K(e.nowIso);let u=e.setupLeaseHandoff??await Qe(t.projectRoot,e.storyId,h,c,l);const m=await C(t.projectRoot,{required:!0}),S=w(m.epics[t.epicId]?.branch_lease),v=S?.ownerStoryId===e.storyId&&S.sessionId===d&&S.idempotencyKey===d&&typeof S.expiresAt=="string"&&Date.parse(S.expiresAt)>Date.parse(l)?S:void 0;if(v&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const x=w(v?.handoffConsumption);if(x){const f=await G(t.projectRoot,e.storyId);if(!f||!["consuming","consumed"].includes(f.state)||f.fromSessionId!==x.fromSessionId||f.tokenDigest!==x.tokenDigest||f.bundleDigest!==h||f.claimRevision!==c||x.bundleDigest!==h||x.claimRevision!==c||f.consumedBySessionId!==d||x.consumedBySessionId!==d)return a("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(!f.token||k(f.token)!==f.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");u={sessionId:f.fromSessionId,token:f.token}}}const b=v?String(v.expiresAt):new Date(Date.parse(l)+ie).toISOString(),D=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:d,idempotencyKey:d,expiresAt:b,persistent:!0,createdAt:v&&typeof v.acquiredAt=="string"?v.acquiredAt:l});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{u&&e.setupLeaseHandoff===void 0&&(await Ue(t.projectRoot,e.storyId,u.sessionId,u.token,d,l),await e.setupHandoffFault?.("after-consuming-persisted")),await P(t.projectRoot,f=>{const R=N(f,t.epicId),p=w(R.branch_lease),I=p&&Date.parse(String(p.expiresAt))>Date.parse(l),E=p?.ownerStoryId===e.storyId&&p.sessionId===d&&p.idempotencyKey===d,$=p?.ownerStoryId===e.storyId&&p.sessionId===p.idempotencyKey&&typeof p.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(p.idempotencyKey),_=I&&$&&et({current:p,handoff:u,storyId:e.storyId,bundleDigest:h,claimRevision:c,nowIso:l});if(u&&I&&!E&&!_)throw new Error("direct-yolo-setup-handoff-invalid");if(I&&!E&&!_)throw new Error("direct-yolo-writer-active");const H=_?w(p?.handoffGrant):void 0,L=H?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(p?.sessionId),tokenDigest:String(H.tokenDigest),bundleDigest:h,claimRevision:c,consumedBySessionId:d,consumedAt:l}:void 0;R.branch_mode="epic",R.execution_branch=t.executionBranch,R.origin_branch=t.originBranch,R.graph_revision=t.graphRevision,R.branch_lease=I&&E?p:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:d,idempotencyKey:d,acquiredAt:l,expiresAt:b,...L?{handoffConsumption:L}:{}}},{expectedRevision:m.revision,preCommit:async()=>{if(!await U(D.path,D.owner))throw new Error("direct-yolo-integration-lock-raced")}})}catch(f){throw await W(D.path,D.owner).catch(()=>{}),f}u&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Xe(t.projectRoot,t.epicId,e.storyId,u.sessionId,u.token,h,c,d,l));const A=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${h}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${c}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${$e(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:h,reviewArtifactDigest:n.digest,graphRevision:t.graphRevision,claimRevision:c,idempotencyKey:d,changedPaths:Object.freeze(r),trailers:A})}}catch(t){return a(Y(t,"direct-yolo-begin-failed"))}}async function It(e){let t,o,r;try{const i=await F(e.projectRoot,e.storyId);t=i;const n=await y(i.projectRoot,["rev-parse","HEAD"]);let g=await C(i.projectRoot,{required:!0});const s=w(g.stories[e.storyId]?.checkpoint);if(s){const _=typeof s.headSha=="string"?s.headSha:"",H=typeof s.graphRevision=="string"?s.graphRevision:"",L=/^[a-f0-9]{40,64}$/.test(_)?O(await j(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",_])):[],z=T(L,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(_)&&await B(i.projectRoot,["merge-base","--is-ancestor",_,n]))||!/^[a-f0-9]{64}$/.test(H)||!z.ok)return a("direct-yolo-replay-invalid");const _e=await de(e,i.projectRoot,n,H);if(!await ve(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,_e.transientAuthority,i.authorizedWriteSet))return a("direct-yolo-replay-invalid");if(!await fe(i.projectRoot,i.executionBranch,n,L))return a("direct-yolo-replay-head-raced");if(e.push&&!await De(i.projectRoot,e.remote??"origin",i.executionBranch,_))return a("direct-yolo-remote-head-mismatch");const le=Array.isArray(s.receiptRefs)?s.receiptRefs.find(ge=>typeof ge=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(ge)):void 0;return le&&typeof s.idempotencyKey=="string"&&await Je(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:le.slice(20)}),{ok:!0,value:s}}const h=n,c=await y(i.projectRoot,["rev-parse",`${h}^`]),d=await j(i.projectRoot,["show","--no-patch","--format=%B",h]),l=O(await j(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",h])),u=T(l,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!u.ok)return a(u.reasonCode);i.rootMemoryEffect&&re(i.projectRoot,i.rootMemoryEffect,{storyId:e.storyId,executionBranch:i.executionBranch,baseSha:c,headRef:h,childPaths:i.authorizedWriteSet});const m=J(d,"Neocortex-Bundle-Digest"),S=J(d,"Neocortex-Graph-Revision"),v=J(d,"Neocortex-Claim-Revision"),x=new Map([["Neocortex-Story",e.storyId],["Neocortex-Epic",i.epicId],["Neocortex-Execution-Branch",i.executionBranch],["Neocortex-Prepared-Base",c],["Neocortex-Graph-Revision",i.graphRevision],["Neocortex-Claim-Revision",k([...i.authorizedWriteSet].sort().join("\0"))]]);if(!m||!/^[a-f0-9]{64}$/.test(m)||!S||!v||[...x].some(([_,H])=>J(d,_)!==H))return a("direct-yolo-trailers-invalid");const b=Q(i.projectRoot,e.storyId,h);if(b?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const D=J(d,"Neocortex-Review-Artifact-Digest");if(D!==void 0&&D!==b.digest)return a("direct-yolo-review-artifact-digest-mismatch");const A=k(await j(i.projectRoot,["diff","--binary","--full-index",`${c}..${h}`]));if(m!==A)return a("direct-yolo-bundle-digest-mismatch");const f=k(["direct-yolo-commit-v1",e.storyId,i.epicId,i.executionBranch,c,m,S,v].join("\0")),R=w(g.epics[i.epicId]?.branch_lease),p=K(e.nowIso),I=R?.ownerStoryId===e.storyId&&R.idempotencyKey===f&&R.sessionId===f&&Date.parse(String(R.expiresAt))>Date.now()?R:void 0;if(R&&Date.parse(String(R.expiresAt))>Date.now()&&!I)return a("direct-yolo-writer-active");const E=I??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:f,idempotencyKey:f,acquiredAt:p,expiresAt:new Date(Date.parse(p)+ie).toISOString()},$=await V(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:f,idempotencyKey:f,expiresAt:String(E.expiresAt),persistent:!0,createdAt:String(E.acquiredAt)});if(!$.ok)return a($.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=$,I||(g=(await P(i.projectRoot,H=>{const L=N(H,i.epicId),z=w(L.branch_lease);if(z&&Date.parse(String(z.expiresAt))>Date.parse(p))throw new Error("direct-yolo-writer-active");if(L.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");L.branch_lease=E},{expectedRevision:g.revision})).document),o=E;{const _=await de(e,i.projectRoot,h,i.graphRevision);if(!await fe(i.projectRoot,i.executionBranch,h,l))return a("direct-yolo-head-raced");if(e.push){const z=ee(e.remote??"origin");if(await y(i.projectRoot,["push",z,i.executionBranch]),!await Ae(i.projectRoot,z,i.executionBranch,h))return a("direct-yolo-remote-head-mismatch")}const H=await be({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:c,headSha:h,bundleDigest:m,graphRevision:S,claimRevision:v,idempotencyKey:f,qaExecution:_,physicalLockOwnerDigest:we($.owner),nowIso:K(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await ke({projectRoot:i.projectRoot,checkpoint:H,remote:e.push?e.remote??"origin":void 0,expectedRevision:g.revision,expectedLease:E,expectedGraphRevision:i.graphRevision,physicalLockPath:$.path,physicalLockOwner:$.owner,transientAuthority:_.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await e.afterCheckpointPersist?.(),{ok:!0,value:H}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(Y(i,"direct-yolo-finalize-failed"))}finally{r&&await W(r.path,r.owner).catch(()=>{}),t&&o?await se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await rt(t,e.storyId).catch(()=>{})}}async function vt(e){try{const t=await F(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return a("direct-yolo-recovery-commit-invalid");const o=await y(t.projectRoot,["rev-parse",e.commitSha]);if(Ge[e.storyId]!==o)return a("direct-yolo-recovery-not-allowlisted");if(await y(t.projectRoot,["rev-parse","HEAD"])!==o)return a("direct-yolo-recovery-head-mismatch");await y(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await y(t.projectRoot,["rev-parse",`${o}^`]),i=await j(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=O(await j(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!T(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const s=k(i),h=k([...n].sort().join("\0")),c=k(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),d=K(e.nowIso),l=new Date(Date.parse(d)+ie).toISOString(),u=await C(t.projectRoot,{required:!0}),m=await V(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:c,idempotencyKey:c,expiresAt:l,persistent:!0,createdAt:d});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const S={schemaVersion:1,ownerStoryId:e.storyId,sessionId:c,idempotencyKey:c,acquiredAt:d,expiresAt:l};let v=!1;try{const x=await P(t.projectRoot,p=>{const I=N(p,t.epicId),E=w(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(d)&&!ce(E,S))throw new Error("direct-yolo-recovery-writer-active");if(I.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.branch_lease=S},{expectedRevision:u.revision});v=!0;const b=await de(e,t.projectRoot,o,t.graphRevision);if(!await fe(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const p=ee(e.remote??"origin"),I=(await y(t.projectRoot,["ls-remote","--heads",p,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!I||!await B(t.projectRoot,["merge-base","--is-ancestor",o,I]))return a("direct-yolo-recovery-remote-proof-missing")}const D=await be({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision,claimRevision:h,idempotencyKey:c,qaExecution:b,physicalLockOwnerDigest:we(m.owner),nowIso:d,legacyReceiptRef:void 0}),A=await Ke(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:s,graphRevision:t.graphRevision});if(!A)return a("direct-yolo-recovery-evidence-invalid");const f=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,A])});return await ke({projectRoot:t.projectRoot,checkpoint:f,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:x.document.revision,expectedLease:S,expectedGraphRevision:t.graphRevision,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:b.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:f}:a("direct-yolo-recovery-persist-failed")}finally{await W(m.path,m.owner).catch(()=>{}),v&&await se(t.projectRoot,t.epicId,S).catch(()=>{})}}catch(t){return a(Y(t,"direct-yolo-recovery-failed"))}}async function Se(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=M(e),r=w(JSON.parse(await Z(te(o,".neocortex/state.json"),"utf8"))),i=await C(o,{required:!0}),n=Pe(r,i),g=w(n.stories),s=w(n.epics),h=w(g?.[t]),c=String(h?.epic_id??t.split(".")[0]),d=w(s?.[c]),l=String(d?.execution_branch??""),u=String(d?.origin_branch??""),m=String(d?.graph_revision??""),S=Array.isArray(h?.files_to_modify)?[...new Set(h.files_to_modify.filter(x=>typeof x=="string"&&ue(x)))].sort():[];if(!h)throw new Error("direct-yolo-story-state-missing");if(d?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Be(l)||!await B(o,["check-ref-format","--branch",l]))throw new Error("direct-yolo-execution-branch-invalid");if(!Be(u)||!await B(o,["check-ref-format","--branch",u]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(m))throw new Error("direct-yolo-graph-revision-invalid");const v=await qe({projectRoot:o,storyId:t,graphRevision:m,executionBranch:l,childPaths:S});return{projectRoot:o,storyId:t,story:h,epicId:c,executionBranch:l,originBranch:u,graphRevision:m,authorizedWriteSet:S,rootMemoryEffect:v}}async function F(e,t){const o=await Se(e,t);if(await y(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function be(e){const t=e.nowIso,o=await j(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=O(await j(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=ze({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ne({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),g=`story-qa:${n}`,s=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:g}),h=Q(e.projectRoot,e.storyId,e.headSha);if(h?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const c=k(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,g,k(o),[...r].sort().join(","),h.digest].join("\0")),d=`story-review:${c}`,l=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:c,reviewArtifactDigest:h.digest,qaReceiptRef:g,verdict:"approved",reviewedAt:t,receiptRef:d}),u=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,g,d,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(u),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:s,reviewReceipt:l,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ke(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await P(t,n=>{const g=N(n,o.epicId);if(e.expectedLease){const d=w(g.branch_lease);if(!ce(d,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(d?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(g.graph_revision!==e.expectedGraphRevision||o.graphRevision!==e.expectedGraphRevision)throw new Error("direct-yolo-graph-revision-raced")}const s=Re(n,o.storyId),h=w(s.checkpoint);if(h&&h.headSha!==o.headSha){i=!0;return}s.checkpoint=o,s.status="done",s.last_step=xe;const c=Array.isArray(s.steps_completed)?s.steps_completed.filter(d=>typeof d=="string"):[];s.steps_completed=[...new Set([...c,Ze,xe])],g.branch_lease=null},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");if(await y(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await y(t,["rev-parse","HEAD"])!==o.headSha)throw new Error("direct-yolo-checkpoint-head-raced");if(!await ve(t,o,o.storyId,o.epicId,o.branch,e.transientAuthority,e.authorizedWriteSet))throw new Error("direct-yolo-checkpoint-physical-invalid");if(e.physicalLockPath&&e.physicalLockOwner&&!await U(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await De(t,r,o.branch,o.headSha):await Ae(t,r,o.branch,o.headSha)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function De(e,t,o,r){const i=ee(t),n=(await y(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await B(e,["merge-base","--is-ancestor",r,n]))}function ne(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function je(e,t){const o=await Te(e),r=await Me(o,"handoffs"),i=`direct-${k(t)}.json`;return{parent:r,name:i,path:te(r,i)}}async function ae(e,t){const o=await je(e,t.storyId);await Ye(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
- `),await Ie(o.path,o.parent)}async function G(e,t){try{const o=await je(e,t);await Ie(o.path,o.parent);const r=JSON.parse(await Z(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function Qe(e,t,o,r,i){const n=await G(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||k(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Ue(e,t,o,r,i,n){const g=await G(e,t);if(!g||g.state==="consumed"||g.fromSessionId!==o||g.token!==r||g.tokenDigest!==k(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(g.state==="consuming"){if(g.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await ae(e,{...g,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Xe(e,t,o,r,i,n,g,s,h){const c=await G(e,o);if(c?.state==="consumed"&&c.fromSessionId===r&&c.consumedBySessionId===s)return;const d=await C(e,{required:!0}),l=w(d.epics[t]?.branch_lease),u=w(l?.handoffConsumption);if(!c||c.state!=="consuming"||c.fromSessionId!==r||c.token!==i||c.tokenDigest!==k(i)||c.bundleDigest!==n||c.claimRevision!==g||c.consumedBySessionId!==s||l?.ownerStoryId!==o||l.sessionId!==s||u?.kind!=="direct-yolo-setup-handoff-consumption"||u.state!=="consumed"||u.fromSessionId!==r||u.tokenDigest!==c.tokenDigest||u.bundleDigest!==n||u.claimRevision!==g||u.consumedBySessionId!==s)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await ae(e,{schemaVersion:1,kind:c.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:c.tokenDigest,bundleDigest:c.bundleDigest,claimRevision:c.claimRevision,grantDigest:c.grantDigest,expiresAt:c.expiresAt,consumedBySessionId:s,consumedAt:h})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function et(e){const t=w(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?k(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&tt(t.tokenDigest,r))}function tt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Ce(o,r)}function ce(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function se(e,t,o){await P(e,r=>{const i=N(r,t),n=w(i.branch_lease);ce(n,o)&&(i.branch_lease=null)})}async function rt(e,t){const o=await C(e.projectRoot,{required:!0}),r=w(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Ee(r.sessionId)||!Ee(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await V(e.projectRoot,{kind:"direct",storyId:t,sessionId:String(r.sessionId),idempotencyKey:String(r.idempotencyKey),createdAt:String(r.acquiredAt),expiresAt:String(r.expiresAt),persistent:!0});if(!i.ok)return;await W(i.path,i.owner)&&await se(e.projectRoot,e.epicId,r)}async function de(e,t,o,r){const i=await Ve(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=We(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Fe,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function fe(e,t,o,r){return await y(e,["rev-parse","HEAD"])!==o||await y(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function Ae(e,t,o,r){const i=ee(t);return(await y(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function T(e,t,o,r){if(e.length===0||e.some(n=>!ue(n)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`];return!i.every(n=>e.includes(n))||!i.every(n=>t.includes(n))?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==k([...t].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(n=>!t.includes(n)&&!r?.files.some(g=>g.path===n))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function ue(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Ee(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Be(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ee(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function J(e,t){const o=`${t}: `,r=e.split(`
3
- `).map(i=>i.trim()).filter(i=>i.startsWith(o)).map(i=>i.slice(o.length));return r.length===1?r[0]:void 0}function k(e){return Le("sha256").update(e).digest("hex")}function O(e){return e.split("\0").filter(Boolean)}function K(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ot(e,t,o,r,i){const n=w(e.expectedLease),g=n?.sessionId,s=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof g=="string"&&/^setup-[a-f0-9]{64}$/.test(g)&&n.idempotencyKey===g&&Number.isFinite(s)&&s<=i}async function it(e,t){let o=await y(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await y(e,["rev-parse","HEAD"])!==t.originHead||await q(e)!==t.checkoutBefore)return;await y(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await y(e,["rev-parse","HEAD"])!==t.originHead||await q(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await y(e,["rev-parse",t.executionRef])===t.originHead&&await y(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}function he(e,t,o){const r=w(e);if(!(!r||r.schemaVersion!==1||r.originBranch!==o||r.executionBranch!==t||r.capturedFromCurrentCheckout!==!0||typeof r.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.originHeadSha)||typeof r.capturedAt!="string"||!Number.isFinite(Date.parse(r.capturedAt))))return r}function pe(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function q(e){const t=O(await j(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!ue(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await y(e,["hash-object","--no-filters","--",r])}`}));return k([await j(e,["diff","--cached","--binary","--full-index"]),await j(e,["diff","--binary","--full-index"]),await j(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function xt(e){const t=M(e),o=await y(t,["rev-parse","HEAD"]),r=await y(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await q(t);if(await y(t,["rev-parse","HEAD"])!==o||await y(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function ye(e){const t=[];let o;for(const r of(await j(e,["worktree","list","--porcelain"])).split(`
4
- `))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function Y(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(e.message)?e.message:t}function a(e){return{ok:!1,reasonCode:e}}async function y(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function j(e,t){return String((await oe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await oe("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{mt as acceptDirectYoloSetupCheckpoint,Rt as beginDirectYoloStoryCommit,xt as captureDirectYoloCheckoutEvidence,It as finalizeDirectYoloStoryCheckpoint,wt as issueDirectYoloSetupLeaseHandoff,gt as prepareDirectYoloSetup,vt as recoverLegacyDirectYoloStoryCheckpoint};
1
+ /** Root-owned two-phase commit/checkpoint boundary for direct `*yolo` runs. */
2
+ import { execFile } from 'node:child_process';
3
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
4
+ import { existsSync } from 'node:fs';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { join, resolve } from 'node:path';
7
+ import { promisify } from 'node:util';
8
+ import { readRootMemoryEffectForCheckpoint } from '../private-execution/root-memory-scope.js';
9
+ import { rootMemoryEffectDigest, verifyRootMemoryPhysicalWriteSet } from '../private-execution/root-memory-git-evidence.js';
10
+ import { acquireGitLifecyclePhysicalIntegrationLock, applyGitLifecycleRuntimeOverlay, computeImmutableStoryQaEvidenceDigest, computeGitLifecyclePhysicalIntegrationLockOwnerDigest, computeP205StoryQaEvidenceDigest, computeLegacyDirectYoloRecoveryReceiptRef, ensureRuntimeEpic, ensureRuntimeStory, ensureGitLifecyclePrivateChildDirectory, executeP205TransientAuthority, projectP205TransientExecutionEvidence, publicStoryReviewArtifactFromGit, LEGACY_DIRECT_YOLO_RECOVERY_COMMITS, mutateGitLifecycleRuntime, P205_COMPLETE_COMMAND, readGitLifecycleRuntime, gitLifecycleRuntimeDirectory, assertGitLifecyclePrivateFile, releaseGitLifecyclePhysicalIntegrationLock, releaseGitLifecyclePhysicalIntegrationLockForCheckpoint, verifyGitLifecyclePhysicalIntegrationLock, verifyAcceptedGitLifecycleStoryCheckpoint, } from './git-lifecycle-store.js';
11
+ import { anchoredAtomicWriteFile, anchoredRemoveFile } from './secure-filesystem-boundary.js';
12
+ import { parseNeocortexTrailers, trailerReasonKey, trailerValue } from './neocortex-trailers.js';
13
+ import { GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID, GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID, } from './git-lifecycle-step-ids.js';
14
+ const execFileAsync = promisify(execFile);
15
+ // The canonical complete P205 gate can legitimately exceed the former
16
+ // 30-minute C08 window on constrained hosts. Keep one finite lease, aligned
17
+ // with setup authority, rather than retrying or renewing after QA.
18
+ const DIRECT_STORY_CHECKPOINT_LEASE_MS = 60 * 60 * 1000;
19
+ /**
20
+ * Productive P207 setup boundary. It owns only the current checkout and the
21
+ * epic branch; it never creates, removes or repositions a worktree. Existing
22
+ * staged and unstaged bytes must remain identical across the branch switch.
23
+ */
24
+ export async function prepareDirectYoloSetup(options) {
25
+ let recoveryPhysical;
26
+ let recoveryPhysicalStarted = false;
27
+ try {
28
+ const authority = await resolveLogicalAuthority(options.projectRoot, options.storyId);
29
+ const nowIso = normalizedTime(options.nowIso);
30
+ const nowMs = Date.parse(nowIso);
31
+ const currentBranch = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
32
+ const currentHead = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
33
+ const runtimeBefore = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
34
+ const runtimeEpic = asRecord(runtimeBefore.epics[authority.epicId]);
35
+ const currentLease = asRecord(runtimeEpic?.branch_lease);
36
+ const expiredSetupRecovery = options.expiredSetupRecovery;
37
+ if (expiredSetupRecovery && !validExpiredSetupRecovery(expiredSetupRecovery, runtimeBefore.revision, currentLease, options.storyId, nowMs)) {
38
+ return failure('direct-yolo-expired-setup-recovery-invalid');
39
+ }
40
+ const liveLease = currentLease && Number.isFinite(Date.parse(String(currentLease.expiresAt)))
41
+ && Date.parse(String(currentLease.expiresAt)) > nowMs;
42
+ if (liveLease && currentLease?.ownerStoryId !== options.storyId) {
43
+ return failure('direct-yolo-writer-active');
44
+ }
45
+ let originBinding = validOriginBinding(runtimeEpic?.origin_binding, authority.executionBranch, authority.originBranch);
46
+ if (currentBranch === authority.executionBranch) {
47
+ if (!originBinding)
48
+ return failure('direct-yolo-origin-binding-invalid');
49
+ }
50
+ else {
51
+ if (currentBranch !== authority.originBranch)
52
+ return failure('direct-yolo-current-branch-mismatch');
53
+ if (originBinding && originBinding.originHeadSha !== currentHead) {
54
+ if (!expiredSetupRecovery)
55
+ return failure('direct-yolo-origin-binding-conflict');
56
+ if (!(await gitExitOk(authority.projectRoot, [
57
+ 'merge-base', '--is-ancestor', originBinding.originHeadSha, currentHead,
58
+ ])))
59
+ return failure('direct-yolo-origin-binding-conflict');
60
+ const recoveryExecutionRef = `refs/heads/${authority.executionBranch}`;
61
+ if (!(await gitExitOk(authority.projectRoot, [
62
+ 'show-ref', '--verify', '--quiet', recoveryExecutionRef,
63
+ ])))
64
+ return failure('direct-yolo-execution-branch-missing');
65
+ const recoveryExecutionHead = await git(authority.projectRoot, ['rev-parse', recoveryExecutionRef]);
66
+ if (!(await gitExitOk(authority.projectRoot, [
67
+ 'merge-base', '--is-ancestor', recoveryExecutionHead, currentHead,
68
+ ])))
69
+ return failure('direct-yolo-execution-branch-diverged');
70
+ }
71
+ originBinding ??= {
72
+ schemaVersion: 1,
73
+ originBranch: authority.originBranch,
74
+ originHeadSha: currentHead,
75
+ executionBranch: authority.executionBranch,
76
+ capturedFromCurrentCheckout: true,
77
+ capturedAt: nowIso,
78
+ };
79
+ const occupiedElsewhere = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
80
+ if (occupiedElsewhere)
81
+ return failure('direct-yolo-execution-branch-checked-out-elsewhere');
82
+ const checkoutBefore = await checkoutPayload(authority.projectRoot);
83
+ const executionRef = `refs/heads/${authority.executionBranch}`;
84
+ if (await gitExitOk(authority.projectRoot, ['show-ref', '--verify', '--quiet', executionRef])) {
85
+ const executionHead = await git(authority.projectRoot, ['rev-parse', executionRef]);
86
+ if (executionHead !== currentHead) {
87
+ if (!(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', executionHead, currentHead]))) {
88
+ return failure('direct-yolo-execution-branch-diverged');
89
+ }
90
+ if (!expiredSetupRecovery) {
91
+ await git(authority.projectRoot, ['update-ref', executionRef, currentHead, executionHead]);
92
+ }
93
+ }
94
+ if (expiredSetupRecovery) {
95
+ recoveryPhysical = {
96
+ checkoutBefore, executionRef, executionBranch: authority.executionBranch,
97
+ executionHead, originBranch: authority.originBranch, originHead: currentHead,
98
+ };
99
+ }
100
+ else {
101
+ await git(authority.projectRoot, ['switch', authority.executionBranch]);
102
+ }
103
+ }
104
+ else if (expiredSetupRecovery) {
105
+ return failure('direct-yolo-execution-branch-missing');
106
+ }
107
+ else {
108
+ await git(authority.projectRoot, ['switch', '-c', authority.executionBranch]);
109
+ }
110
+ if (!recoveryPhysical && await checkoutPayload(authority.projectRoot) !== checkoutBefore) {
111
+ return failure('direct-yolo-checkout-payload-raced');
112
+ }
113
+ }
114
+ const headAfter = recoveryPhysical?.originHead ?? await git(authority.projectRoot, ['rev-parse', 'HEAD']);
115
+ if (!recoveryPhysical) {
116
+ const branchAfter = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
117
+ if (branchAfter !== authority.executionBranch)
118
+ return failure('direct-yolo-current-branch-mismatch');
119
+ }
120
+ if (liveLease && currentLease?.ownerStoryId === options.storyId) {
121
+ if (currentLease.setupHeadSha !== headAfter)
122
+ return failure('direct-yolo-setup-lease-head-unbound');
123
+ return { ok: true, value: setupReceipt(authority, originBinding, String(currentLease.expiresAt), true) };
124
+ }
125
+ const acquiredAt = nowIso;
126
+ const expiresAt = new Date(nowMs + 60 * 60 * 1000).toISOString();
127
+ const sessionId = `setup-${randomBytes(32).toString('hex')}`;
128
+ const runtimeAtCas = expiredSetupRecovery
129
+ ? runtimeBefore
130
+ : await readGitLifecycleRuntime(authority.projectRoot, { required: true });
131
+ await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
132
+ const epic = ensureRuntimeEpic(document, authority.epicId);
133
+ const lease = asRecord(epic.branch_lease);
134
+ if (expiredSetupRecovery
135
+ && JSON.stringify(lease) !== JSON.stringify(expiredSetupRecovery.expectedLease)) {
136
+ throw new Error('direct-yolo-expired-setup-recovery-raced');
137
+ }
138
+ if (lease && Date.parse(String(lease.expiresAt)) > nowMs && lease.ownerStoryId !== options.storyId) {
139
+ throw new Error('direct-yolo-writer-active');
140
+ }
141
+ const persistedBinding = validOriginBinding(epic.origin_binding, authority.executionBranch, authority.originBranch);
142
+ if (epic.origin_binding && !persistedBinding)
143
+ throw new Error('direct-yolo-origin-binding-conflict');
144
+ if (persistedBinding && JSON.stringify(persistedBinding) !== JSON.stringify(originBinding)) {
145
+ throw new Error('direct-yolo-origin-binding-conflict');
146
+ }
147
+ epic.branch_mode = 'epic';
148
+ epic.execution_branch = authority.executionBranch;
149
+ epic.origin_branch = authority.originBranch;
150
+ epic.graph_revision = authority.graphRevision;
151
+ epic.origin_binding = originBinding;
152
+ epic.branch_lease = {
153
+ schemaVersion: 1, ownerStoryId: options.storyId, sessionId, idempotencyKey: sessionId,
154
+ acquiredAt, expiresAt, setupHeadSha: headAfter,
155
+ };
156
+ }, {
157
+ expectedRevision: expiredSetupRecovery?.expectedRuntimeRevision ?? runtimeAtCas.revision,
158
+ preCommit: async () => {
159
+ if (recoveryPhysical) {
160
+ const occupiedAtCas = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
161
+ if (occupiedAtCas
162
+ || await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.originBranch
163
+ || await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== recoveryPhysical.originHead
164
+ || await checkoutPayload(authority.projectRoot) !== recoveryPhysical.checkoutBefore
165
+ || !(await gitExitOk(authority.projectRoot, ['show-ref', '--verify', '--quiet', recoveryPhysical.executionRef]))
166
+ || await git(authority.projectRoot, ['rev-parse', recoveryPhysical.executionRef]) !== recoveryPhysical.executionHead) {
167
+ throw new Error('direct-yolo-expired-setup-recovery-raced');
168
+ }
169
+ recoveryPhysicalStarted = true;
170
+ if (recoveryPhysical.executionHead !== recoveryPhysical.originHead) {
171
+ await git(authority.projectRoot, [
172
+ 'update-ref', recoveryPhysical.executionRef,
173
+ recoveryPhysical.originHead, recoveryPhysical.executionHead,
174
+ ]);
175
+ }
176
+ await git(authority.projectRoot, ['switch', authority.executionBranch]);
177
+ if (await checkoutPayload(authority.projectRoot) !== recoveryPhysical.checkoutBefore) {
178
+ throw new Error('direct-yolo-checkout-payload-raced');
179
+ }
180
+ }
181
+ if (await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.executionBranch
182
+ || await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headAfter) {
183
+ throw new Error('direct-yolo-setup-physical-state-raced');
184
+ }
185
+ },
186
+ });
187
+ return { ok: true, value: setupReceipt(authority, originBinding, expiresAt, false) };
188
+ }
189
+ catch (error) {
190
+ if (recoveryPhysicalStarted && recoveryPhysical) {
191
+ await rollbackExpiredSetupRecoveryPhysical(resolve(options.projectRoot), recoveryPhysical).catch(() => undefined);
192
+ }
193
+ return failure(publicReason(error, 'direct-yolo-setup-failed'));
194
+ }
195
+ }
196
+ /** Accept C01 only from the root after its own physical setup and live lease. */
197
+ export async function acceptDirectYoloSetupCheckpoint(options) {
198
+ let physicalLock;
199
+ try {
200
+ const authority = await resolveAuthority(options.projectRoot, options.storyId);
201
+ const nowIso = normalizedTime(options.nowIso);
202
+ const statePath = join(authority.projectRoot, '.neocortex/state.json');
203
+ const trackedBefore = await readFile(statePath, 'utf8');
204
+ const payloadBefore = await checkoutPayload(authority.projectRoot);
205
+ const headSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
206
+ const executionRef = `refs/heads/${authority.executionBranch}`;
207
+ const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
208
+ const epic = asRecord(runtime.epics[authority.epicId]);
209
+ const binding = validOriginBinding(epic?.origin_binding, authority.executionBranch, authority.originBranch);
210
+ const lease = asRecord(epic?.branch_lease);
211
+ if (!binding)
212
+ return failure('direct-yolo-origin-binding-invalid');
213
+ if (!lease || !isLiveSameStorySetupLease(lease, options.storyId, nowIso)
214
+ || lease?.sessionId !== lease?.idempotencyKey)
215
+ return failure('direct-yolo-setup-lease-invalid');
216
+ const acquired = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
217
+ kind: 'direct', storyId: options.storyId,
218
+ sessionId: String(lease.sessionId), idempotencyKey: String(lease.idempotencyKey),
219
+ expiresAt: new Date(Date.now() + 5 * 60 * 1000).toISOString(), persistent: false,
220
+ });
221
+ if (!acquired.ok)
222
+ return failure(acquired.reasonCode);
223
+ physicalLock = acquired;
224
+ if (headSha !== lease.setupHeadSha
225
+ || !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, headSha]))
226
+ || await git(authority.projectRoot, ['rev-parse', executionRef]) !== headSha) {
227
+ return failure('direct-yolo-setup-head-mismatch');
228
+ }
229
+ const occupiedElsewhere = (await worktreeBranches(authority.projectRoot)).some((item) => item.branch === authority.executionBranch && resolve(item.path) !== authority.projectRoot);
230
+ if (occupiedElsewhere)
231
+ return failure('direct-yolo-execution-branch-checked-out-elsewhere');
232
+ const tracked = asRecord(JSON.parse(trackedBefore));
233
+ const trackedStory = asRecord(asRecord(tracked?.stories)?.[options.storyId]);
234
+ const runtimeStory = asRecord(runtime.stories[options.storyId]);
235
+ if (!trackedStory || !['backlog', 'ready_to_start'].includes(String(trackedStory.status))
236
+ || (trackedStory.steps_completed !== undefined
237
+ && (!Array.isArray(trackedStory.steps_completed) || trackedStory.steps_completed.length > 0))
238
+ || trackedStory.branch_name || trackedStory.checkpoint) {
239
+ return failure('direct-yolo-setup-story-progress-conflict');
240
+ }
241
+ const accepted = runtimeStory?.status === 'branch-ready'
242
+ && runtimeStory.last_step === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
243
+ && Array.isArray(runtimeStory.steps_completed)
244
+ && runtimeStory.steps_completed.length === 1
245
+ && runtimeStory.steps_completed[0] === GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID
246
+ && Object.keys(runtimeStory).sort().join(',') === 'last_step,status,steps_completed';
247
+ if (runtimeStory && Object.keys(runtimeStory).length > 0 && !accepted) {
248
+ return failure('direct-yolo-setup-story-progress-conflict');
249
+ }
250
+ const physicalGuard = async () => {
251
+ if (Date.parse(String(lease.expiresAt)) <= (options.nowIso ? Date.parse(nowIso) : Date.now())
252
+ || !physicalLock || !(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))
253
+ || await readFile(statePath, 'utf8') !== trackedBefore
254
+ || await checkoutPayload(authority.projectRoot) !== payloadBefore
255
+ || await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== authority.executionBranch
256
+ || await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headSha
257
+ || !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', binding.originHeadSha, headSha]))
258
+ || await git(authority.projectRoot, ['rev-parse', executionRef]) !== headSha) {
259
+ throw new Error('direct-yolo-setup-physical-state-raced');
260
+ }
261
+ };
262
+ if (accepted) {
263
+ await physicalGuard();
264
+ }
265
+ else {
266
+ await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
267
+ const currentEpic = asRecord(document.epics[authority.epicId]);
268
+ const currentStory = ensureRuntimeStory(document, options.storyId);
269
+ if (JSON.stringify(currentEpic?.branch_lease) !== JSON.stringify(lease)
270
+ || JSON.stringify(currentEpic?.origin_binding) !== JSON.stringify(binding)
271
+ || currentEpic?.graph_revision !== authority.graphRevision
272
+ || Object.keys(currentStory).length > 0) {
273
+ throw new Error('direct-yolo-setup-runtime-raced');
274
+ }
275
+ currentStory.status = 'branch-ready';
276
+ currentStory.last_step = GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID;
277
+ currentStory.steps_completed = [GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID];
278
+ }, { expectedRevision: runtime.revision, preCommit: physicalGuard });
279
+ }
280
+ return { ok: true, value: Object.freeze({
281
+ ...setupReceipt(authority, binding, String(lease.expiresAt), accepted),
282
+ checkpointAccepted: true, graphRevision: authority.graphRevision, headSha,
283
+ }) };
284
+ }
285
+ catch (error) {
286
+ return failure(publicReason(error, 'direct-yolo-setup-acceptance-failed'));
287
+ }
288
+ finally {
289
+ if (physicalLock) {
290
+ await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
291
+ }
292
+ }
293
+ }
294
+ /**
295
+ * Productive setup-owner handoff emitter used immediately before C08. The
296
+ * one-time token never crosses stdout; only a public receipt is returned.
297
+ */
298
+ export async function issueDirectYoloSetupLeaseHandoff(options) {
299
+ try {
300
+ const authority = await resolveAuthority(options.projectRoot, options.storyId);
301
+ const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--cached', '--name-only', '-z']));
302
+ const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
303
+ if (!writeSet.ok)
304
+ return failure(writeSet.reasonCode);
305
+ if (authority.rootMemoryEffect)
306
+ verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch,
307
+ baseSha: await git(authority.projectRoot, ['rev-parse', 'HEAD']), headRef: ':', childPaths: authority.authorizedWriteSet });
308
+ const stagedReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, ':');
309
+ if (stagedReview?.verdict !== 'approved')
310
+ return failure('direct-yolo-review-artifact-not-approved');
311
+ const unstagedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--name-only', '-z']));
312
+ if (unstagedPaths.some((path) => changedPaths.includes(path)))
313
+ return failure('direct-yolo-user-overlap');
314
+ const payload = await gitRaw(authority.projectRoot, ['diff', '--cached', '--binary', '--full-index']);
315
+ if (!payload)
316
+ return failure('direct-yolo-staged-diff-empty');
317
+ const bundleDigest = digest(payload);
318
+ const claimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
319
+ const nowIso = normalizedTime(options.nowIso);
320
+ const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
321
+ const setupLease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
322
+ if (!isLiveSameStorySetupLease(setupLease, options.storyId, nowIso)) {
323
+ return failure('direct-yolo-setup-handoff-owner-invalid');
324
+ }
325
+ const sessionId = String(setupLease.sessionId);
326
+ const leaseExpiresAt = String(setupLease.expiresAt);
327
+ const candidateExpiresAt = new Date(Math.min(Date.parse(leaseExpiresAt), Date.parse(nowIso) + 5 * 60 * 1000)).toISOString();
328
+ const prior = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
329
+ const reused = Boolean(prior?.state === 'issued'
330
+ && prior.fromSessionId === sessionId && prior.bundleDigest === bundleDigest
331
+ && prior.claimRevision === claimRevision
332
+ && Date.parse(prior.expiresAt) > Date.parse(nowIso));
333
+ const expiresAt = reused ? prior.expiresAt : candidateExpiresAt;
334
+ const token = reused ? prior.token : randomBytes(32).toString('base64url');
335
+ const tokenDigest = digest(token);
336
+ const grant = Object.freeze({
337
+ schemaVersion: 1,
338
+ kind: 'direct-yolo-setup-handoff',
339
+ storyId: options.storyId,
340
+ fromSessionId: sessionId,
341
+ tokenDigest,
342
+ bundleDigest,
343
+ claimRevision,
344
+ expiresAt,
345
+ });
346
+ const grantDigest = digest(JSON.stringify(grant));
347
+ const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
348
+ kind: 'direct', storyId: options.storyId, sessionId, idempotencyKey: sessionId,
349
+ expiresAt, persistent: false, createdAt: nowIso,
350
+ });
351
+ if (!physicalLock.ok)
352
+ return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
353
+ ? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
354
+ try {
355
+ await writeSetupHandoffTokenRecord(authority.projectRoot, {
356
+ schemaVersion: 1, kind: 'direct-yolo-setup-handoff-token', state: 'issued',
357
+ storyId: options.storyId, fromSessionId: sessionId, token, tokenDigest,
358
+ bundleDigest, claimRevision, grantDigest, expiresAt,
359
+ });
360
+ await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
361
+ const current = asRecord(ensureRuntimeEpic(document, authority.epicId).branch_lease);
362
+ if (!isLiveSameStorySetupLease(current, options.storyId, nowIso)
363
+ || current?.sessionId !== sessionId || current.idempotencyKey !== sessionId) {
364
+ throw new Error('direct-yolo-setup-handoff-owner-raced');
365
+ }
366
+ current.handoffGrant = grant;
367
+ }, {
368
+ expectedRevision: runtime.revision,
369
+ preCommit: async () => {
370
+ if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
371
+ throw new Error('direct-yolo-integration-lock-raced');
372
+ }
373
+ const persisted = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
374
+ if (!persisted || persisted.state !== 'issued' || persisted.grantDigest !== grantDigest
375
+ || persisted.tokenDigest !== tokenDigest)
376
+ throw new Error('direct-yolo-setup-handoff-token-raced');
377
+ },
378
+ });
379
+ }
380
+ finally {
381
+ await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
382
+ }
383
+ return { ok: true, value: Object.freeze({
384
+ schemaVersion: 1, kind: 'direct-yolo-setup-handoff-receipt', storyId: options.storyId,
385
+ sessionId, bundleDigest, claimRevision, grantDigest, expiresAt, reused, publicSafe: true,
386
+ }) };
387
+ }
388
+ catch (error) {
389
+ return failure(error instanceof Error && /^direct-yolo-/.test(error.message)
390
+ ? error.message : 'direct-yolo-setup-handoff-failed');
391
+ }
392
+ }
393
+ export async function beginDirectYoloStoryCommit(options) {
394
+ try {
395
+ const authority = await resolveAuthority(options.projectRoot, options.storyId);
396
+ const baseSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
397
+ const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--cached', '--name-only', '-z']));
398
+ const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
399
+ if (!writeSet.ok)
400
+ return failure(writeSet.reasonCode);
401
+ if (authority.rootMemoryEffect)
402
+ verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch, baseSha, headRef: ':', childPaths: authority.authorizedWriteSet });
403
+ const stagedReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, ':');
404
+ if (stagedReview?.verdict !== 'approved')
405
+ return failure('direct-yolo-review-artifact-not-approved');
406
+ const unstagedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff', '--name-only', '-z']));
407
+ if (unstagedPaths.some((path) => changedPaths.includes(path)))
408
+ return failure('direct-yolo-user-overlap');
409
+ const payload = await gitRaw(authority.projectRoot, ['diff', '--cached', '--binary', '--full-index']);
410
+ if (!payload)
411
+ return failure('direct-yolo-staged-diff-empty');
412
+ const bundleDigest = digest(payload);
413
+ const claimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
414
+ // A begin replay for the exact same staged content keeps the graph epoch it
415
+ // was first issued under; the epic epoch may advance while no lease is held.
416
+ const priorPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
417
+ const replayedPlan = priorPlan.state === 'valid'
418
+ && priorPlan.plan.epicId === authority.epicId
419
+ && priorPlan.plan.executionBranch === authority.executionBranch
420
+ && priorPlan.plan.preparedBase === baseSha
421
+ && priorPlan.plan.bundleDigest === bundleDigest
422
+ && priorPlan.plan.claimRevision === claimRevision
423
+ ? priorPlan.plan : undefined;
424
+ const boundGraphRevision = replayedPlan?.graphRevision ?? authority.graphRevision;
425
+ const idempotencyKey = directCommitIdempotencyKey({
426
+ storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
427
+ baseSha, bundleDigest, graphRevision: boundGraphRevision, claimRevision,
428
+ });
429
+ const nowIso = normalizedTime(options.nowIso);
430
+ const commitPlan = {
431
+ schemaVersion: 1, kind: 'direct-yolo-commit-plan', storyId: options.storyId,
432
+ epicId: authority.epicId, executionBranch: authority.executionBranch,
433
+ graphRevision: boundGraphRevision, preparedBase: baseSha, bundleDigest, claimRevision,
434
+ idempotencyKey, issuedAt: replayedPlan?.issuedAt ?? nowIso,
435
+ };
436
+ let issuedHandoff = options.setupLeaseHandoff
437
+ ?? await resolveIssuedSetupLeaseHandoff(authority.projectRoot, options.storyId, bundleDigest, claimRevision, nowIso);
438
+ const runtimeBeforeLock = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
439
+ const priorDirectLease = asRecord(runtimeBeforeLock.epics[authority.epicId]?.branch_lease);
440
+ const reusableDirectLease = priorDirectLease?.ownerStoryId === options.storyId
441
+ && priorDirectLease.sessionId === idempotencyKey && priorDirectLease.idempotencyKey === idempotencyKey
442
+ && typeof priorDirectLease.expiresAt === 'string'
443
+ && Date.parse(priorDirectLease.expiresAt) > Date.parse(nowIso)
444
+ ? priorDirectLease : undefined;
445
+ if (reusableDirectLease && options.setupLeaseHandoff) {
446
+ return failure('direct-yolo-setup-handoff-replayed');
447
+ }
448
+ const priorConsumption = asRecord(reusableDirectLease?.handoffConsumption);
449
+ if (priorConsumption) {
450
+ const privateRecord = await readSetupHandoffTokenRecord(authority.projectRoot, options.storyId);
451
+ if (!privateRecord || !['consuming', 'consumed'].includes(privateRecord.state)
452
+ || privateRecord.fromSessionId !== priorConsumption.fromSessionId
453
+ || privateRecord.tokenDigest !== priorConsumption.tokenDigest
454
+ || privateRecord.bundleDigest !== bundleDigest || privateRecord.claimRevision !== claimRevision
455
+ || priorConsumption.bundleDigest !== bundleDigest || priorConsumption.claimRevision !== claimRevision
456
+ || privateRecord.consumedBySessionId !== idempotencyKey
457
+ || priorConsumption.consumedBySessionId !== idempotencyKey) {
458
+ return failure('direct-yolo-setup-handoff-consume-invalid');
459
+ }
460
+ // The runtime CAS already consumed this exact grant. Recovery may finish
461
+ // its private receipt after expiry; it never promotes a second writer.
462
+ if (privateRecord.state === 'consuming') {
463
+ if (!privateRecord.token || digest(privateRecord.token) !== privateRecord.tokenDigest) {
464
+ return failure('direct-yolo-setup-handoff-consume-invalid');
465
+ }
466
+ issuedHandoff = { sessionId: privateRecord.fromSessionId, token: privateRecord.token };
467
+ }
468
+ }
469
+ const expiresAt = reusableDirectLease
470
+ ? String(reusableDirectLease.expiresAt)
471
+ : new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString();
472
+ const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
473
+ kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
474
+ expiresAt, persistent: true,
475
+ createdAt: reusableDirectLease && typeof reusableDirectLease.acquiredAt === 'string'
476
+ ? reusableDirectLease.acquiredAt : nowIso,
477
+ });
478
+ if (!physicalLock.ok)
479
+ return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
480
+ ? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
481
+ try {
482
+ if (issuedHandoff && options.setupLeaseHandoff === undefined) {
483
+ await markSetupHandoffTokenConsuming(authority.projectRoot, options.storyId, issuedHandoff.sessionId, issuedHandoff.token, idempotencyKey, nowIso);
484
+ await options.setupHandoffFault?.('after-consuming-persisted');
485
+ }
486
+ await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
487
+ const epic = ensureRuntimeEpic(document, authority.epicId);
488
+ const current = asRecord(epic.branch_lease);
489
+ const live = current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso);
490
+ const alreadyPromoted = current?.ownerStoryId === options.storyId
491
+ && current.sessionId === idempotencyKey && current.idempotencyKey === idempotencyKey;
492
+ const sameStorySetup = current?.ownerStoryId === options.storyId
493
+ && current.sessionId === current.idempotencyKey
494
+ && typeof current.idempotencyKey === 'string'
495
+ && /^setup-[a-f0-9]{64}$/.test(current.idempotencyKey);
496
+ const setupHandoffAuthorized = live && sameStorySetup && validSetupLeaseHandoff({
497
+ current,
498
+ handoff: issuedHandoff,
499
+ storyId: options.storyId,
500
+ bundleDigest,
501
+ claimRevision,
502
+ nowIso,
503
+ });
504
+ if (issuedHandoff && live && !alreadyPromoted && !setupHandoffAuthorized) {
505
+ throw new Error('direct-yolo-setup-handoff-invalid');
506
+ }
507
+ if (live && !alreadyPromoted && !setupHandoffAuthorized) {
508
+ throw new Error('direct-yolo-writer-active');
509
+ }
510
+ const setupGrant = setupHandoffAuthorized ? asRecord(current?.handoffGrant) : undefined;
511
+ const handoffConsumption = setupGrant ? {
512
+ schemaVersion: 1,
513
+ kind: 'direct-yolo-setup-handoff-consumption',
514
+ state: 'consumed',
515
+ storyId: options.storyId,
516
+ fromSessionId: String(current?.sessionId),
517
+ tokenDigest: String(setupGrant.tokenDigest),
518
+ bundleDigest,
519
+ claimRevision,
520
+ consumedBySessionId: idempotencyKey,
521
+ consumedAt: nowIso,
522
+ } : undefined;
523
+ epic.branch_mode = 'epic';
524
+ epic.execution_branch = authority.executionBranch;
525
+ epic.origin_branch = authority.originBranch;
526
+ epic.graph_revision = authority.graphRevision;
527
+ epic.branch_lease = live && alreadyPromoted ? current : {
528
+ schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
529
+ idempotencyKey, acquiredAt: nowIso, expiresAt,
530
+ ...(handoffConsumption ? { handoffConsumption } : {}),
531
+ };
532
+ }, {
533
+ expectedRevision: runtimeBeforeLock.revision,
534
+ preCommit: async () => {
535
+ if (!(await verifyGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner))) {
536
+ throw new Error('direct-yolo-integration-lock-raced');
537
+ }
538
+ // Durable under the runtime lock and independent of the lease: a
539
+ // failed/expired finalize releases the lease, never the plan epoch.
540
+ await writeDirectCommitPlan(authority.projectRoot, commitPlan);
541
+ },
542
+ });
543
+ }
544
+ catch (error) {
545
+ await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
546
+ throw error;
547
+ }
548
+ if (issuedHandoff && options.setupLeaseHandoff === undefined) {
549
+ await options.setupHandoffFault?.('before-consumed-persist');
550
+ await markSetupHandoffTokenConsumed(authority.projectRoot, authority.epicId, options.storyId, issuedHandoff.sessionId, issuedHandoff.token, bundleDigest, claimRevision, idempotencyKey, nowIso);
551
+ }
552
+ const trailers = Object.freeze([
553
+ `Neocortex-Story: ${options.storyId}`,
554
+ `Neocortex-Epic: ${authority.epicId}`,
555
+ `Neocortex-Execution-Branch: ${authority.executionBranch}`,
556
+ `Neocortex-Prepared-Base: ${baseSha}`,
557
+ `Neocortex-Bundle-Digest: ${bundleDigest}`,
558
+ `Neocortex-Review-Artifact-Digest: ${stagedReview.digest}`,
559
+ `Neocortex-Graph-Revision: ${boundGraphRevision}`,
560
+ `Neocortex-Claim-Revision: ${claimRevision}`,
561
+ ...(authority.rootMemoryEffect ? [`Neocortex-Root-Memory-Effect: ${rootMemoryEffectDigest(authority.rootMemoryEffect)}`] : []),
562
+ ]);
563
+ return { ok: true, value: Object.freeze({
564
+ schemaVersion: 1, storyId: options.storyId, epicId: authority.epicId,
565
+ executionBranch: authority.executionBranch, baseSha, bundleDigest,
566
+ reviewArtifactDigest: stagedReview.digest,
567
+ graphRevision: boundGraphRevision, claimRevision, idempotencyKey,
568
+ changedPaths: Object.freeze(changedPaths), trailers,
569
+ }) };
570
+ }
571
+ catch (error) {
572
+ return failure(publicReason(error, 'direct-yolo-begin-failed'));
573
+ }
574
+ }
575
+ export async function finalizeDirectYoloStoryCheckpoint(options) {
576
+ let cleanupAuthority;
577
+ let cleanupLease;
578
+ let cleanupPhysical;
579
+ try {
580
+ const authority = await resolveAuthority(options.projectRoot, options.storyId);
581
+ cleanupAuthority = authority;
582
+ const aggregateHeadSha = await git(authority.projectRoot, ['rev-parse', 'HEAD']);
583
+ let runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
584
+ const existing = asRecord(runtime.stories[options.storyId]?.checkpoint);
585
+ if (existing) {
586
+ const checkpointHeadSha = typeof existing.headSha === 'string' ? existing.headSha : '';
587
+ const checkpointGraphRevision = typeof existing.graphRevision === 'string' ? existing.graphRevision : '';
588
+ const checkpointPaths = /^[a-f0-9]{40,64}$/.test(checkpointHeadSha)
589
+ ? splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', checkpointHeadSha]))
590
+ : [];
591
+ const replayWriteSet = validateDirectWriteSet(checkpointPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
592
+ const ancestral = /^[a-f0-9]{40,64}$/.test(checkpointHeadSha)
593
+ && await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', checkpointHeadSha, aggregateHeadSha]);
594
+ if (!ancestral || !/^[a-f0-9]{64}$/.test(checkpointGraphRevision) || !replayWriteSet.ok) {
595
+ return failure('direct-yolo-replay-invalid');
596
+ }
597
+ const replayQa = await runQa(options, authority.projectRoot, aggregateHeadSha, checkpointGraphRevision);
598
+ if (!(await verifyAcceptedGitLifecycleStoryCheckpoint(authority.projectRoot, existing, options.storyId, authority.epicId, authority.executionBranch, replayQa.transientAuthority, authority.authorizedWriteSet)))
599
+ return failure('direct-yolo-replay-invalid');
600
+ if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, aggregateHeadSha, checkpointPaths)))
601
+ return failure('direct-yolo-replay-head-raced');
602
+ if (options.push && !(await remoteContainsHead(authority.projectRoot, options.remote ?? 'origin', authority.executionBranch, checkpointHeadSha)))
603
+ return failure('direct-yolo-remote-head-mismatch');
604
+ const physicalOwnerRef = Array.isArray(existing.receiptRefs)
605
+ ? existing.receiptRefs.find((item) => typeof item === 'string' && /^physical-lock-owner:[a-f0-9]{64}$/.test(item))
606
+ : undefined;
607
+ if (physicalOwnerRef && typeof existing.idempotencyKey === 'string') {
608
+ await releaseGitLifecyclePhysicalIntegrationLockForCheckpoint(authority.projectRoot, {
609
+ storyId: options.storyId,
610
+ idempotencyKey: existing.idempotencyKey,
611
+ ownerDigest: physicalOwnerRef.slice('physical-lock-owner:'.length),
612
+ });
613
+ }
614
+ await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
615
+ return { ok: true, value: existing };
616
+ }
617
+ const headSha = aggregateHeadSha;
618
+ const baseSha = await git(authority.projectRoot, ['rev-parse', `${headSha}^`]);
619
+ const commitBody = await gitRaw(authority.projectRoot, ['show', '--no-patch', '--format=%B', headSha]);
620
+ const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha]));
621
+ const writeSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet, options.storyId, authority.rootMemoryEffect);
622
+ if (!writeSet.ok)
623
+ return failure(writeSet.reasonCode);
624
+ if (authority.rootMemoryEffect)
625
+ verifyRootMemoryPhysicalWriteSet(authority.projectRoot, authority.rootMemoryEffect, { storyId: options.storyId, executionBranch: authority.executionBranch, baseSha, headRef: headSha, childPaths: authority.authorizedWriteSet });
626
+ const expectedClaimRevision = digest([...authority.authorizedWriteSet].sort().join('\0'));
627
+ // The begin plan binds the graph epoch the trailers were issued under. The
628
+ // epic epoch may legitimately advance after the lease is released (failed
629
+ // finalize, expiry); the checkpoint keeps its own epoch, as in terminal
630
+ // readiness. Content, claim and base bindings remain exact.
631
+ const storedPlan = await readDirectCommitPlan(authority.projectRoot, options.storyId);
632
+ if (storedPlan.state === 'invalid')
633
+ return failure('direct-yolo-commit-plan-invalid');
634
+ const plan = storedPlan.state === 'valid' ? storedPlan.plan : undefined;
635
+ if (plan && (plan.epicId !== authority.epicId || plan.executionBranch !== authority.executionBranch)) {
636
+ return failure('direct-yolo-commit-plan-invalid');
637
+ }
638
+ if (plan && plan.claimRevision !== expectedClaimRevision)
639
+ return failure('direct-yolo-commit-plan-claim-changed');
640
+ if (plan && plan.preparedBase !== baseSha)
641
+ return failure('direct-yolo-commit-plan-base-mismatch');
642
+ const parsedTrailers = parseNeocortexTrailers(commitBody);
643
+ if (!parsedTrailers.ok)
644
+ return failure(`direct-yolo-trailer-duplicate:${parsedTrailers.key}`);
645
+ const trailers = parsedTrailers.values;
646
+ const graphRevision = plan?.graphRevision ?? authority.graphRevision;
647
+ const claimRevision = expectedClaimRevision;
648
+ const required = [
649
+ ['Neocortex-Story', options.storyId], ['Neocortex-Epic', authority.epicId],
650
+ ['Neocortex-Execution-Branch', authority.executionBranch], ['Neocortex-Prepared-Base', baseSha],
651
+ ['Neocortex-Bundle-Digest', plan?.bundleDigest ?? ''],
652
+ ['Neocortex-Graph-Revision', graphRevision],
653
+ ['Neocortex-Claim-Revision', claimRevision],
654
+ ];
655
+ for (const [key, value] of required) {
656
+ const actual = trailerValue(trailers, key);
657
+ if (actual === undefined)
658
+ return failure(`direct-yolo-trailer-missing:${trailerReasonKey(key)}`);
659
+ if (key === 'Neocortex-Bundle-Digest' && !plan) {
660
+ if (!/^[a-f0-9]{64}$/.test(actual))
661
+ return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
662
+ continue;
663
+ }
664
+ if (actual !== value)
665
+ return failure(`direct-yolo-trailer-mismatch:${trailerReasonKey(key)}`);
666
+ }
667
+ const bundleDigest = trailerValue(trailers, 'Neocortex-Bundle-Digest');
668
+ const publicReview = publicStoryReviewArtifactFromGit(authority.projectRoot, options.storyId, headSha);
669
+ if (publicReview?.verdict !== 'approved')
670
+ return failure('direct-yolo-review-artifact-not-approved');
671
+ const reviewTrailer = trailerValue(trailers, 'Neocortex-Review-Artifact-Digest');
672
+ if (reviewTrailer !== undefined && reviewTrailer !== publicReview.digest) {
673
+ return failure('direct-yolo-review-artifact-digest-mismatch');
674
+ }
675
+ const expectedPayloadDigest = digest(await gitRaw(authority.projectRoot, ['diff', '--binary', '--full-index', `${baseSha}..${headSha}`]));
676
+ if (bundleDigest !== expectedPayloadDigest)
677
+ return failure('direct-yolo-bundle-digest-mismatch');
678
+ const idempotencyKey = directCommitIdempotencyKey({
679
+ storyId: options.storyId, epicId: authority.epicId, executionBranch: authority.executionBranch,
680
+ baseSha, bundleDigest, graphRevision, claimRevision,
681
+ });
682
+ if (plan && plan.idempotencyKey !== idempotencyKey)
683
+ return failure('direct-yolo-commit-plan-invalid');
684
+ const currentLease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
685
+ const nowIso = normalizedTime(options.nowIso);
686
+ const matchingLease = currentLease?.ownerStoryId === options.storyId
687
+ && currentLease.idempotencyKey === idempotencyKey
688
+ && currentLease.sessionId === idempotencyKey
689
+ && Date.parse(String(currentLease.expiresAt)) > Date.now()
690
+ ? currentLease : undefined;
691
+ if (currentLease && Date.parse(String(currentLease.expiresAt)) > Date.now() && !matchingLease) {
692
+ return failure('direct-yolo-writer-active');
693
+ }
694
+ const requestedLease = matchingLease ?? {
695
+ schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
696
+ idempotencyKey, acquiredAt: nowIso,
697
+ expiresAt: new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString(),
698
+ };
699
+ const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
700
+ kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
701
+ expiresAt: String(requestedLease.expiresAt), persistent: true,
702
+ createdAt: String(requestedLease.acquiredAt),
703
+ });
704
+ if (!physicalLock.ok)
705
+ return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
706
+ ? 'direct-yolo-integration-backpressure' : 'direct-yolo-integration-lock-failed');
707
+ cleanupPhysical = physicalLock;
708
+ if (!matchingLease) {
709
+ const leased = await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
710
+ const epic = ensureRuntimeEpic(document, authority.epicId);
711
+ const current = asRecord(epic.branch_lease);
712
+ if (current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso)) {
713
+ throw new Error('direct-yolo-writer-active');
714
+ }
715
+ // Race guard only: the epic epoch must not move while this finalize
716
+ // owns the writer; the checkpoint itself stays bound to the plan epoch.
717
+ if (epic.graph_revision !== authority.graphRevision)
718
+ throw new Error('direct-yolo-graph-revision-raced');
719
+ epic.branch_lease = requestedLease;
720
+ }, { expectedRevision: runtime.revision });
721
+ runtime = leased.document;
722
+ }
723
+ cleanupLease = requestedLease;
724
+ {
725
+ const qaExecution = await runQa(options, authority.projectRoot, headSha, graphRevision);
726
+ if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, headSha, changedPaths))) {
727
+ return failure('direct-yolo-head-raced');
728
+ }
729
+ if (options.push) {
730
+ const remote = safeRemote(options.remote ?? 'origin');
731
+ await git(authority.projectRoot, ['push', remote, authority.executionBranch]);
732
+ if (!(await remoteHeadIsExact(authority.projectRoot, remote, authority.executionBranch, headSha))) {
733
+ return failure('direct-yolo-remote-head-mismatch');
734
+ }
735
+ }
736
+ const checkpoint = await buildCheckpoint({
737
+ projectRoot: authority.projectRoot, storyId: options.storyId, epicId: authority.epicId,
738
+ executionBranch: authority.executionBranch, baseSha, headSha, bundleDigest,
739
+ graphRevision, claimRevision, idempotencyKey, qaExecution,
740
+ physicalLockOwnerDigest: computeGitLifecyclePhysicalIntegrationLockOwnerDigest(physicalLock.owner),
741
+ nowIso: normalizedTime(options.nowIso), legacyReceiptRef: undefined, rootMemoryEffect: authority.rootMemoryEffect,
742
+ });
743
+ await options.beforeCheckpointPersist?.();
744
+ const persisted = await persistCheckpoint({
745
+ projectRoot: authority.projectRoot, checkpoint,
746
+ remote: options.push ? options.remote ?? 'origin' : undefined,
747
+ expectedRevision: runtime.revision, expectedLease: requestedLease,
748
+ expectedGraphRevision: authority.graphRevision,
749
+ expectedCheckpointGraphRevision: graphRevision,
750
+ physicalLockPath: physicalLock.path, physicalLockOwner: physicalLock.owner,
751
+ transientAuthority: qaExecution.transientAuthority,
752
+ authorizedWriteSet: authority.authorizedWriteSet,
753
+ });
754
+ if (!persisted)
755
+ return failure('direct-yolo-checkpoint-persist-failed');
756
+ await removeDirectCommitPlan(authority.projectRoot, options.storyId).catch(() => undefined);
757
+ await options.afterCheckpointPersist?.();
758
+ return { ok: true, value: checkpoint };
759
+ }
760
+ }
761
+ catch (error) {
762
+ return failure(publicReason(error, 'direct-yolo-finalize-failed'));
763
+ }
764
+ finally {
765
+ if (cleanupPhysical) {
766
+ await releaseGitLifecyclePhysicalIntegrationLock(cleanupPhysical.path, cleanupPhysical.owner).catch(() => undefined);
767
+ }
768
+ if (cleanupAuthority && cleanupLease) {
769
+ await releaseOwnedDirectLease(cleanupAuthority.projectRoot, cleanupAuthority.epicId, cleanupLease).catch(() => undefined);
770
+ }
771
+ else if (cleanupAuthority) {
772
+ await cleanupOwnedDirectAuthority(cleanupAuthority, options.storyId).catch(() => undefined);
773
+ }
774
+ }
775
+ }
776
+ export async function recoverLegacyDirectYoloStoryCheckpoint(options) {
777
+ try {
778
+ const authority = await resolveAuthority(options.projectRoot, options.storyId);
779
+ if (!/^[a-f0-9]{40,64}$/.test(options.commitSha))
780
+ return failure('direct-yolo-recovery-commit-invalid');
781
+ const headSha = await git(authority.projectRoot, ['rev-parse', options.commitSha]);
782
+ if (LEGACY_DIRECT_YOLO_RECOVERY_COMMITS[options.storyId] !== headSha) {
783
+ return failure('direct-yolo-recovery-not-allowlisted');
784
+ }
785
+ if (await git(authority.projectRoot, ['rev-parse', 'HEAD']) !== headSha) {
786
+ return failure('direct-yolo-recovery-head-mismatch');
787
+ }
788
+ await git(authority.projectRoot, ['merge-base', '--is-ancestor', headSha, `refs/heads/${authority.executionBranch}`]);
789
+ const baseSha = await git(authority.projectRoot, ['rev-parse', `${headSha}^`]);
790
+ const payload = await gitRaw(authority.projectRoot, ['diff', '--binary', '--full-index', `${baseSha}..${headSha}`]);
791
+ const changedPaths = splitNull(await gitRaw(authority.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', headSha]));
792
+ const recoveryWriteSet = validateDirectWriteSet(changedPaths, authority.authorizedWriteSet.length > 0 ? authority.authorizedWriteSet : changedPaths, options.storyId);
793
+ if (!recoveryWriteSet.ok)
794
+ return failure('direct-yolo-recovery-write-set-invalid');
795
+ const bundleDigest = digest(payload);
796
+ const claimRevision = digest([...changedPaths].sort().join('\0'));
797
+ const idempotencyKey = digest(['legacy-direct-yolo-recovery-v1', options.storyId, headSha].join('\0'));
798
+ const nowIso = normalizedTime(options.nowIso);
799
+ const expiresAt = new Date(Date.parse(nowIso) + DIRECT_STORY_CHECKPOINT_LEASE_MS).toISOString();
800
+ const initialRuntime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
801
+ const physicalLock = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
802
+ kind: 'direct', storyId: options.storyId, sessionId: idempotencyKey, idempotencyKey,
803
+ expiresAt, persistent: true, createdAt: nowIso,
804
+ });
805
+ if (!physicalLock.ok)
806
+ return failure(physicalLock.reasonCode === 'git-lifecycle-integration-backpressure'
807
+ ? 'direct-yolo-recovery-integration-backpressure' : 'direct-yolo-recovery-integration-lock-failed');
808
+ const requestedLease = {
809
+ schemaVersion: 1, ownerStoryId: options.storyId, sessionId: idempotencyKey,
810
+ idempotencyKey, acquiredAt: nowIso, expiresAt,
811
+ };
812
+ let leaseAcquired = false;
813
+ try {
814
+ const leased = await mutateGitLifecycleRuntime(authority.projectRoot, (document) => {
815
+ const epic = ensureRuntimeEpic(document, authority.epicId);
816
+ const current = asRecord(epic.branch_lease);
817
+ if (current && Date.parse(String(current.expiresAt)) > Date.parse(nowIso)
818
+ && !sameLease(current, requestedLease))
819
+ throw new Error('direct-yolo-recovery-writer-active');
820
+ if (epic.graph_revision !== authority.graphRevision)
821
+ throw new Error('direct-yolo-recovery-graph-raced');
822
+ epic.branch_mode = 'epic';
823
+ epic.execution_branch = authority.executionBranch;
824
+ epic.origin_branch = authority.originBranch;
825
+ epic.branch_lease = requestedLease;
826
+ }, { expectedRevision: initialRuntime.revision });
827
+ leaseAcquired = true;
828
+ const qaExecution = await runQa(options, authority.projectRoot, headSha, authority.graphRevision);
829
+ if (!(await physicalCheckoutUnchanged(authority.projectRoot, authority.executionBranch, headSha, changedPaths))) {
830
+ return failure('direct-yolo-recovery-head-raced');
831
+ }
832
+ if (options.push) {
833
+ const remote = safeRemote(options.remote ?? 'origin');
834
+ const remoteHead = (await git(authority.projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${authority.executionBranch}`])).split(/\s+/)[0];
835
+ if (!remoteHead || !(await gitExitOk(authority.projectRoot, ['merge-base', '--is-ancestor', headSha, remoteHead]))) {
836
+ return failure('direct-yolo-recovery-remote-proof-missing');
837
+ }
838
+ }
839
+ const provisional = await buildCheckpoint({
840
+ projectRoot: authority.projectRoot, storyId: options.storyId, epicId: authority.epicId,
841
+ executionBranch: authority.executionBranch, baseSha, headSha, bundleDigest,
842
+ graphRevision: authority.graphRevision, claimRevision, idempotencyKey,
843
+ qaExecution,
844
+ physicalLockOwnerDigest: computeGitLifecyclePhysicalIntegrationLockOwnerDigest(physicalLock.owner),
845
+ nowIso, legacyReceiptRef: undefined,
846
+ });
847
+ const legacyReceiptRef = await computeLegacyDirectYoloRecoveryReceiptRef(authority.projectRoot, {
848
+ storyId: options.storyId,
849
+ epicId: authority.epicId,
850
+ executionBranch: authority.executionBranch,
851
+ baseSha,
852
+ headSha,
853
+ bundleDigest,
854
+ graphRevision: authority.graphRevision,
855
+ });
856
+ if (!legacyReceiptRef)
857
+ return failure('direct-yolo-recovery-evidence-invalid');
858
+ const checkpoint = Object.freeze({
859
+ ...provisional,
860
+ receiptRefs: Object.freeze([...provisional.receiptRefs, legacyReceiptRef]),
861
+ });
862
+ const persisted = await persistCheckpoint({
863
+ projectRoot: authority.projectRoot, checkpoint,
864
+ remote: options.push ? options.remote ?? 'origin' : undefined,
865
+ remotePolicy: 'ancestor-recovery',
866
+ expectedRevision: leased.document.revision,
867
+ expectedLease: requestedLease,
868
+ expectedGraphRevision: authority.graphRevision,
869
+ physicalLockPath: physicalLock.path,
870
+ physicalLockOwner: physicalLock.owner,
871
+ transientAuthority: qaExecution.transientAuthority,
872
+ authorizedWriteSet: authority.authorizedWriteSet,
873
+ });
874
+ return persisted ? { ok: true, value: checkpoint } : failure('direct-yolo-recovery-persist-failed');
875
+ }
876
+ finally {
877
+ await releaseGitLifecyclePhysicalIntegrationLock(physicalLock.path, physicalLock.owner).catch(() => undefined);
878
+ if (leaseAcquired)
879
+ await releaseOwnedDirectLease(authority.projectRoot, authority.epicId, requestedLease).catch(() => undefined);
880
+ }
881
+ }
882
+ catch (error) {
883
+ return failure(publicReason(error, 'direct-yolo-recovery-failed'));
884
+ }
885
+ }
886
+ async function resolveLogicalAuthority(projectRootInput, storyId) {
887
+ if (!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(storyId))
888
+ throw new Error('direct-yolo-story-id-invalid');
889
+ const projectRoot = resolve(projectRootInput);
890
+ const tracked = asRecord(JSON.parse(await readFile(join(projectRoot, '.neocortex/state.json'), 'utf8')));
891
+ const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
892
+ const effective = applyGitLifecycleRuntimeOverlay(tracked, runtime);
893
+ const stories = asRecord(effective.stories);
894
+ const epics = asRecord(effective.epics);
895
+ const story = asRecord(stories?.[storyId]);
896
+ const epicId = String(story?.epic_id ?? storyId.split('.')[0]);
897
+ const epic = asRecord(epics?.[epicId]);
898
+ const executionBranch = String(epic?.execution_branch ?? '');
899
+ const originBranch = String(epic?.origin_branch ?? '');
900
+ const graphRevision = String(epic?.graph_revision ?? '');
901
+ const authorizedWriteSet = Array.isArray(story?.files_to_modify)
902
+ ? [...new Set(story.files_to_modify.filter((item) => typeof item === 'string' && safePath(item)))].sort()
903
+ : [];
904
+ if (!story)
905
+ throw new Error('direct-yolo-story-state-missing');
906
+ if (epic?.branch_mode !== 'epic')
907
+ throw new Error('direct-yolo-branch-mode-invalid');
908
+ if (!safeRef(executionBranch)
909
+ || !(await gitExitOk(projectRoot, ['check-ref-format', '--branch', executionBranch]))) {
910
+ throw new Error('direct-yolo-execution-branch-invalid');
911
+ }
912
+ if (!safeRef(originBranch)
913
+ || !(await gitExitOk(projectRoot, ['check-ref-format', '--branch', originBranch]))) {
914
+ throw new Error('direct-yolo-origin-branch-invalid');
915
+ }
916
+ if (!/^[a-f0-9]{64}$/.test(graphRevision))
917
+ throw new Error('direct-yolo-graph-revision-invalid');
918
+ const rootMemoryEffect = await readRootMemoryEffectForCheckpoint({ projectRoot, storyId, graphRevision,
919
+ executionBranch, childPaths: authorizedWriteSet });
920
+ return { projectRoot, storyId, story, epicId, executionBranch, originBranch, graphRevision, authorizedWriteSet, rootMemoryEffect };
921
+ }
922
+ async function resolveAuthority(projectRootInput, storyId) {
923
+ const authority = await resolveLogicalAuthority(projectRootInput, storyId);
924
+ const currentBranch = await git(authority.projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
925
+ if (currentBranch !== authority.executionBranch)
926
+ throw new Error('direct-yolo-current-branch-mismatch');
927
+ return authority;
928
+ }
929
+ async function buildCheckpoint(input) {
930
+ const checkedAt = input.nowIso;
931
+ const commitBody = await gitRaw(input.projectRoot, ['show', '--no-patch', '--format=%H%n%P%n%B', input.headSha]);
932
+ const changedPaths = splitNull(await gitRaw(input.projectRoot, ['diff-tree', '--no-commit-id', '--name-only', '-r', '-z', input.headSha]));
933
+ const gitEvidenceDigest = computeImmutableStoryQaEvidenceDigest({
934
+ storyId: input.storyId, baseSha: input.baseSha, headSha: input.headSha,
935
+ bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
936
+ commitBody, changedPaths,
937
+ });
938
+ const qaDigest = computeP205StoryQaEvidenceDigest({
939
+ gitEvidenceDigest, headSha: input.headSha, graphRevision: input.graphRevision,
940
+ manifestDigest: input.qaExecution.manifestDigest, gateIds: input.qaExecution.gateIds,
941
+ resultDigest: input.qaExecution.resultDigest,
942
+ });
943
+ const qaReceiptRef = `story-qa:${qaDigest}`;
944
+ const qaReceipt = Object.freeze({
945
+ schemaVersion: 1, kind: 'story_qa_evidence', producer: 'local-yolo-tdd', evidenceVersion: 'p205-execution-v2',
946
+ storyId: input.storyId, epicId: input.epicId, baseSha: input.baseSha, headSha: input.headSha,
947
+ bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
948
+ contract: input.qaExecution.contract, command: input.qaExecution.command,
949
+ manifestDigest: input.qaExecution.manifestDigest, gateIds: input.qaExecution.gateIds,
950
+ resultDigest: input.qaExecution.resultDigest,
951
+ sourceEvidenceDigest: qaDigest, verdict: 'passed', checkedAt, receiptRef: qaReceiptRef,
952
+ });
953
+ const publicReview = publicStoryReviewArtifactFromGit(input.projectRoot, input.storyId, input.headSha);
954
+ if (publicReview?.verdict !== 'approved')
955
+ throw new Error('direct-yolo-review-artifact-not-approved');
956
+ const reviewDigest = digest([
957
+ 'root-commit-range-review-v2', input.storyId, input.baseSha, input.headSha,
958
+ input.bundleDigest, input.graphRevision, qaReceiptRef, digest(commitBody), [...changedPaths].sort().join(','),
959
+ publicReview.digest,
960
+ ].join('\0'));
961
+ const reviewReceiptRef = `story-review:${reviewDigest}`;
962
+ const reviewReceipt = Object.freeze({
963
+ schemaVersion: 1, kind: 'story_review_evidence', producer: 'root-commit-range-review',
964
+ storyId: input.storyId, epicId: input.epicId, baseSha: input.baseSha, headSha: input.headSha,
965
+ bundleDigest: input.bundleDigest, graphRevision: input.graphRevision,
966
+ sourceEvidenceDigest: reviewDigest, reviewArtifactDigest: publicReview.digest,
967
+ qaReceiptRef, verdict: 'approved', reviewedAt: checkedAt,
968
+ receiptRef: reviewReceiptRef,
969
+ });
970
+ const evidenceRefs = [
971
+ `.neocortex/stories/${input.storyId}/qa-gate-result.json`,
972
+ `.neocortex/stories/${input.storyId}/validation-evidence.md`, qaReceiptRef, reviewReceiptRef,
973
+ ...(input.physicalLockOwnerDigest ? [`physical-lock-owner:${input.physicalLockOwnerDigest}`] : []),
974
+ ...(input.legacyReceiptRef ? [input.legacyReceiptRef] : []),
975
+ ];
976
+ return Object.freeze({
977
+ schemaVersion: 1, storyId: input.storyId, epicId: input.epicId, branch: input.executionBranch,
978
+ baseSha: input.baseSha, headSha: input.headSha, commits: Object.freeze([input.headSha]),
979
+ idempotencyKey: input.idempotencyKey, bundleDigest: input.bundleDigest,
980
+ graphRevision: input.graphRevision, claimRevision: input.claimRevision,
981
+ receiptRefs: Object.freeze(evidenceRefs), qaVerdict: 'passed', reviewVerdict: 'approved',
982
+ qaReceipt, reviewReceipt, recordedAt: checkedAt,
983
+ ...(input.rootMemoryEffect ? { rootMemoryEffect: input.rootMemoryEffect } : {}),
984
+ });
985
+ }
986
+ async function persistCheckpoint(input) {
987
+ const { projectRoot, checkpoint, remote } = input;
988
+ let conflict = false;
989
+ await mutateGitLifecycleRuntime(projectRoot, (document) => {
990
+ const epic = ensureRuntimeEpic(document, checkpoint.epicId);
991
+ if (input.expectedLease) {
992
+ const currentLease = asRecord(epic.branch_lease);
993
+ if (!sameLease(currentLease, input.expectedLease))
994
+ throw new Error('direct-yolo-runtime-revision-conflict');
995
+ if (Date.parse(String(currentLease?.expiresAt)) <= Date.now())
996
+ throw new Error('direct-yolo-writer-lease-expired');
997
+ if (epic.graph_revision !== input.expectedGraphRevision
998
+ || checkpoint.graphRevision !== (input.expectedCheckpointGraphRevision ?? input.expectedGraphRevision)) {
999
+ throw new Error('direct-yolo-graph-revision-raced');
1000
+ }
1001
+ }
1002
+ const story = ensureRuntimeStory(document, checkpoint.storyId);
1003
+ const existing = asRecord(story.checkpoint);
1004
+ if (existing && existing.headSha !== checkpoint.headSha) {
1005
+ conflict = true;
1006
+ return;
1007
+ }
1008
+ story.checkpoint = checkpoint;
1009
+ story.status = 'done';
1010
+ story.last_step = GIT_LIFECYCLE_REVIEW_PR_STEP_ID;
1011
+ const steps = Array.isArray(story.steps_completed) ? story.steps_completed.filter((item) => typeof item === 'string') : [];
1012
+ story.steps_completed = [...new Set([...steps, GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID, GIT_LIFECYCLE_REVIEW_PR_STEP_ID])];
1013
+ epic.branch_lease = null;
1014
+ }, { expectedRevision: input.expectedRevision, preCommit: async () => {
1015
+ if (conflict)
1016
+ throw new Error('direct-yolo-checkpoint-conflict');
1017
+ const currentBranch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
1018
+ if (currentBranch !== checkpoint.branch || await git(projectRoot, ['rev-parse', 'HEAD']) !== checkpoint.headSha) {
1019
+ throw new Error('direct-yolo-checkpoint-head-raced');
1020
+ }
1021
+ if (!(await verifyAcceptedGitLifecycleStoryCheckpoint(projectRoot, checkpoint, checkpoint.storyId, checkpoint.epicId, checkpoint.branch, input.transientAuthority, input.authorizedWriteSet)))
1022
+ throw new Error('direct-yolo-checkpoint-physical-invalid');
1023
+ if (input.physicalLockPath && input.physicalLockOwner
1024
+ && !(await verifyGitLifecyclePhysicalIntegrationLock(input.physicalLockPath, input.physicalLockOwner))) {
1025
+ throw new Error('direct-yolo-integration-lock-raced');
1026
+ }
1027
+ if (remote) {
1028
+ const accepted = input.remotePolicy === 'ancestor-recovery'
1029
+ ? await remoteContainsHead(projectRoot, remote, checkpoint.branch, checkpoint.headSha)
1030
+ : await remoteHeadIsExact(projectRoot, remote, checkpoint.branch, checkpoint.headSha);
1031
+ if (!accepted) {
1032
+ throw new Error('direct-yolo-checkpoint-remote-raced');
1033
+ }
1034
+ }
1035
+ } });
1036
+ return !conflict;
1037
+ }
1038
+ async function remoteContainsHead(projectRoot, remoteInput, branch, headSha) {
1039
+ const remote = safeRemote(remoteInput);
1040
+ const remoteHead = (await git(projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])).split(/\s+/)[0];
1041
+ return Boolean(remoteHead && await gitExitOk(projectRoot, ['merge-base', '--is-ancestor', headSha, remoteHead]));
1042
+ }
1043
+ function directCommitIdempotencyKey(input) {
1044
+ return digest([
1045
+ 'direct-yolo-commit-v1', input.storyId, input.epicId, input.executionBranch,
1046
+ input.baseSha, input.bundleDigest, input.graphRevision, input.claimRevision,
1047
+ ].join('\0'));
1048
+ }
1049
+ const DIRECT_COMMIT_PLAN_KEYS = [
1050
+ 'schemaVersion', 'kind', 'storyId', 'epicId', 'executionBranch', 'graphRevision',
1051
+ 'preparedBase', 'bundleDigest', 'claimRevision', 'idempotencyKey', 'issuedAt',
1052
+ ];
1053
+ async function directCommitPlanLocation(projectRoot, storyId) {
1054
+ const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
1055
+ const parent = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'commit-plans');
1056
+ const name = `direct-${digest(storyId)}.json`;
1057
+ return { parent, name, path: join(parent, name) };
1058
+ }
1059
+ async function writeDirectCommitPlan(projectRoot, plan) {
1060
+ const location = await directCommitPlanLocation(projectRoot, plan.storyId);
1061
+ await anchoredAtomicWriteFile(location.parent, location.name, `${JSON.stringify(plan, null, 2)}\n`);
1062
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1063
+ }
1064
+ async function readDirectCommitPlan(projectRoot, storyId) {
1065
+ let location;
1066
+ try {
1067
+ location = await directCommitPlanLocation(projectRoot, storyId);
1068
+ }
1069
+ catch {
1070
+ return { state: 'invalid' };
1071
+ }
1072
+ try {
1073
+ if (!existsSync(location.path))
1074
+ return { state: 'absent' };
1075
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1076
+ const raw = await readFile(location.path, 'utf8');
1077
+ if (raw.length > 16 * 1024)
1078
+ return { state: 'invalid' };
1079
+ const item = asRecord(JSON.parse(raw));
1080
+ if (!item || Object.keys(item).sort().join('\0') !== [...DIRECT_COMMIT_PLAN_KEYS].sort().join('\0')
1081
+ || item.schemaVersion !== 1 || item.kind !== 'direct-yolo-commit-plan' || item.storyId !== storyId
1082
+ || typeof item.epicId !== 'string' || typeof item.executionBranch !== 'string' || !safeRef(item.executionBranch)
1083
+ || typeof item.preparedBase !== 'string' || !/^[a-f0-9]{40,64}$/.test(item.preparedBase)
1084
+ || ![item.graphRevision, item.bundleDigest, item.claimRevision, item.idempotencyKey].every((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
1085
+ || typeof item.issuedAt !== 'string' || !Number.isFinite(Date.parse(item.issuedAt))) {
1086
+ return { state: 'invalid' };
1087
+ }
1088
+ const plan = item;
1089
+ if (plan.idempotencyKey !== directCommitIdempotencyKey({ ...plan, baseSha: plan.preparedBase })) {
1090
+ return { state: 'invalid' };
1091
+ }
1092
+ return { state: 'valid', plan };
1093
+ }
1094
+ catch {
1095
+ return { state: 'invalid' };
1096
+ }
1097
+ }
1098
+ async function removeDirectCommitPlan(projectRoot, storyId) {
1099
+ const location = await directCommitPlanLocation(projectRoot, storyId);
1100
+ if (!existsSync(location.path))
1101
+ return;
1102
+ await anchoredRemoveFile(location.parent, location.name);
1103
+ }
1104
+ function isLiveSameStorySetupLease(lease, storyId, nowIso) {
1105
+ return Boolean(lease?.ownerStoryId === storyId
1106
+ && lease.sessionId === lease.idempotencyKey
1107
+ && typeof lease.idempotencyKey === 'string'
1108
+ && /^setup-[a-f0-9]{64}$/.test(lease.idempotencyKey)
1109
+ && typeof lease.expiresAt === 'string'
1110
+ && Date.parse(lease.expiresAt) > Date.parse(nowIso));
1111
+ }
1112
+ async function setupHandoffTokenLocation(projectRoot, storyId) {
1113
+ const runtimeDirectory = await gitLifecycleRuntimeDirectory(projectRoot);
1114
+ const parent = await ensureGitLifecyclePrivateChildDirectory(runtimeDirectory, 'handoffs');
1115
+ const name = `direct-${digest(storyId)}.json`;
1116
+ return { parent, name, path: join(parent, name) };
1117
+ }
1118
+ async function writeSetupHandoffTokenRecord(projectRoot, record) {
1119
+ const location = await setupHandoffTokenLocation(projectRoot, record.storyId);
1120
+ await anchoredAtomicWriteFile(location.parent, location.name, `${JSON.stringify(record, null, 2)}\n`);
1121
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1122
+ }
1123
+ async function readSetupHandoffTokenRecord(projectRoot, storyId) {
1124
+ try {
1125
+ const location = await setupHandoffTokenLocation(projectRoot, storyId);
1126
+ await assertGitLifecyclePrivateFile(location.path, location.parent);
1127
+ const item = JSON.parse(await readFile(location.path, 'utf8'));
1128
+ const exactKeys = item.state === 'issued'
1129
+ ? ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'token', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt']
1130
+ : item.state === 'consuming'
1131
+ ? ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'token', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt', 'consumedBySessionId', 'consumeStartedAt']
1132
+ : ['schemaVersion', 'kind', 'state', 'storyId', 'fromSessionId', 'tokenDigest', 'bundleDigest', 'claimRevision', 'grantDigest', 'expiresAt', 'consumedBySessionId', 'consumedAt'];
1133
+ if (Object.keys(item).sort().join('\0') !== [...exactKeys].sort().join('\0')
1134
+ || item.schemaVersion !== 1 || item.kind !== 'direct-yolo-setup-handoff-token'
1135
+ || (item.state !== 'issued' && item.state !== 'consuming' && item.state !== 'consumed') || item.storyId !== storyId
1136
+ || typeof item.fromSessionId !== 'string' || !/^setup-[a-f0-9]{64}$/.test(item.fromSessionId)
1137
+ || ![item.tokenDigest, item.bundleDigest, item.claimRevision, item.grantDigest].every((value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value))
1138
+ || typeof item.expiresAt !== 'string' || !Number.isFinite(Date.parse(item.expiresAt))
1139
+ || (item.state === 'issued' || item.state === 'consuming')
1140
+ && (typeof item.token !== 'string' || !/^[A-Za-z0-9_-]{32,256}$/.test(item.token))
1141
+ || item.state === 'consuming' && (typeof item.consumedBySessionId !== 'string'
1142
+ || !/^[a-f0-9]{64}$/.test(item.consumedBySessionId)
1143
+ || typeof item.consumeStartedAt !== 'string' || !Number.isFinite(Date.parse(item.consumeStartedAt)))
1144
+ || item.state === 'consumed' && (typeof item.consumedBySessionId !== 'string'
1145
+ || !/^[a-f0-9]{64}$/.test(item.consumedBySessionId)
1146
+ || typeof item.consumedAt !== 'string' || !Number.isFinite(Date.parse(item.consumedAt))))
1147
+ return undefined;
1148
+ return item;
1149
+ }
1150
+ catch {
1151
+ return undefined;
1152
+ }
1153
+ }
1154
+ async function resolveIssuedSetupLeaseHandoff(projectRoot, storyId, bundleDigest, claimRevision, nowIso) {
1155
+ const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
1156
+ if (!record || record.state === 'consumed' || !record.token
1157
+ || record.bundleDigest !== bundleDigest || record.claimRevision !== claimRevision
1158
+ || Date.parse(record.expiresAt) <= Date.parse(nowIso)
1159
+ || digest(record.token) !== record.tokenDigest)
1160
+ return undefined;
1161
+ return { sessionId: record.fromSessionId, token: record.token };
1162
+ }
1163
+ async function markSetupHandoffTokenConsuming(projectRoot, storyId, fromSessionId, token, consumedBySessionId, consumeStartedAt) {
1164
+ const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
1165
+ if (!record || record.state === 'consumed' || record.fromSessionId !== fromSessionId
1166
+ || record.token !== token || record.tokenDigest !== digest(token)) {
1167
+ throw new Error('direct-yolo-setup-handoff-consume-invalid');
1168
+ }
1169
+ if (record.state === 'consuming') {
1170
+ if (record.consumedBySessionId !== consumedBySessionId) {
1171
+ throw new Error('direct-yolo-setup-handoff-consume-raced');
1172
+ }
1173
+ return;
1174
+ }
1175
+ await writeSetupHandoffTokenRecord(projectRoot, {
1176
+ ...record,
1177
+ state: 'consuming',
1178
+ consumedBySessionId,
1179
+ consumeStartedAt,
1180
+ });
1181
+ }
1182
+ async function markSetupHandoffTokenConsumed(projectRoot, epicId, storyId, fromSessionId, token, bundleDigest, claimRevision, consumedBySessionId, consumedAt) {
1183
+ const record = await readSetupHandoffTokenRecord(projectRoot, storyId);
1184
+ if (record?.state === 'consumed' && record.fromSessionId === fromSessionId
1185
+ && record.consumedBySessionId === consumedBySessionId)
1186
+ return;
1187
+ const runtime = await readGitLifecycleRuntime(projectRoot, { required: true });
1188
+ const lease = asRecord(runtime.epics[epicId]?.branch_lease);
1189
+ const consumption = asRecord(lease?.handoffConsumption);
1190
+ if (!record || record.state !== 'consuming' || record.fromSessionId !== fromSessionId
1191
+ || record.token !== token || record.tokenDigest !== digest(token)
1192
+ || record.bundleDigest !== bundleDigest || record.claimRevision !== claimRevision
1193
+ || record.consumedBySessionId !== consumedBySessionId
1194
+ || lease?.ownerStoryId !== storyId || lease.sessionId !== consumedBySessionId
1195
+ || consumption?.kind !== 'direct-yolo-setup-handoff-consumption'
1196
+ || consumption.state !== 'consumed' || consumption.fromSessionId !== fromSessionId
1197
+ || consumption.tokenDigest !== record.tokenDigest || consumption.bundleDigest !== bundleDigest
1198
+ || consumption.claimRevision !== claimRevision || consumption.consumedBySessionId !== consumedBySessionId) {
1199
+ throw new Error('direct-yolo-setup-handoff-consume-invalid');
1200
+ }
1201
+ try {
1202
+ await writeSetupHandoffTokenRecord(projectRoot, {
1203
+ schemaVersion: 1, kind: record.kind, state: 'consumed', storyId,
1204
+ fromSessionId, tokenDigest: record.tokenDigest, bundleDigest: record.bundleDigest,
1205
+ claimRevision: record.claimRevision, grantDigest: record.grantDigest, expiresAt: record.expiresAt,
1206
+ consumedBySessionId, consumedAt,
1207
+ });
1208
+ }
1209
+ catch {
1210
+ throw new Error('direct-yolo-setup-handoff-consume-persist-failed');
1211
+ }
1212
+ }
1213
+ function validSetupLeaseHandoff(input) {
1214
+ const grant = asRecord(input.current?.handoffGrant);
1215
+ const token = input.handoff?.token;
1216
+ const tokenDigest = typeof token === 'string' && /^[A-Za-z0-9_-]{32,256}$/.test(token)
1217
+ ? digest(token)
1218
+ : undefined;
1219
+ return Boolean(grant && tokenDigest && input.handoff
1220
+ && input.handoff.sessionId === input.current?.sessionId
1221
+ && grant.schemaVersion === 1
1222
+ && grant.kind === 'direct-yolo-setup-handoff'
1223
+ && grant.storyId === input.storyId
1224
+ && grant.fromSessionId === input.current?.sessionId
1225
+ && grant.bundleDigest === input.bundleDigest
1226
+ && grant.claimRevision === input.claimRevision
1227
+ && typeof grant.expiresAt === 'string'
1228
+ && Date.parse(grant.expiresAt) > Date.parse(input.nowIso)
1229
+ && typeof grant.tokenDigest === 'string'
1230
+ && /^[a-f0-9]{64}$/.test(grant.tokenDigest)
1231
+ && safeDigestEqual(grant.tokenDigest, tokenDigest));
1232
+ }
1233
+ function safeDigestEqual(left, right) {
1234
+ const leftBytes = Buffer.from(left, 'hex');
1235
+ const rightBytes = Buffer.from(right, 'hex');
1236
+ return leftBytes.length === 32 && rightBytes.length === 32 && timingSafeEqual(leftBytes, rightBytes);
1237
+ }
1238
+ function sameLease(left, right) {
1239
+ return Boolean(left && ['schemaVersion', 'ownerStoryId', 'sessionId', 'idempotencyKey', 'acquiredAt', 'expiresAt']
1240
+ .every((key) => left[key] === right[key]));
1241
+ }
1242
+ async function releaseOwnedDirectLease(projectRoot, epicId, expected) {
1243
+ await mutateGitLifecycleRuntime(projectRoot, (document) => {
1244
+ const epic = ensureRuntimeEpic(document, epicId);
1245
+ const current = asRecord(epic.branch_lease);
1246
+ if (sameLease(current, expected))
1247
+ epic.branch_lease = null;
1248
+ });
1249
+ }
1250
+ async function cleanupOwnedDirectAuthority(authority, storyId) {
1251
+ const runtime = await readGitLifecycleRuntime(authority.projectRoot, { required: true });
1252
+ const lease = asRecord(runtime.epics[authority.epicId]?.branch_lease);
1253
+ if (!lease || lease.ownerStoryId !== storyId || !safeTokenValue(lease.sessionId)
1254
+ || !safeTokenValue(lease.idempotencyKey) || !Number.isFinite(Date.parse(String(lease.acquiredAt)))
1255
+ || !Number.isFinite(Date.parse(String(lease.expiresAt))))
1256
+ return;
1257
+ const physical = await acquireGitLifecyclePhysicalIntegrationLock(authority.projectRoot, {
1258
+ kind: 'direct', storyId, sessionId: String(lease.sessionId), idempotencyKey: String(lease.idempotencyKey),
1259
+ createdAt: String(lease.acquiredAt), expiresAt: String(lease.expiresAt), persistent: true,
1260
+ });
1261
+ if (!physical.ok)
1262
+ return;
1263
+ const released = await releaseGitLifecyclePhysicalIntegrationLock(physical.path, physical.owner);
1264
+ if (released)
1265
+ await releaseOwnedDirectLease(authority.projectRoot, authority.epicId, lease);
1266
+ }
1267
+ async function runQa(options, projectRoot, headSha, graphRevision) {
1268
+ const transientAuthority = await executeP205TransientAuthority(projectRoot, {
1269
+ headSha,
1270
+ graphRevision,
1271
+ nowIso: options.nowIso,
1272
+ });
1273
+ await options.qaRunner?.({ projectRoot, storyId: options.storyId, headSha });
1274
+ const evidence = projectP205TransientExecutionEvidence(transientAuthority);
1275
+ if (!evidence)
1276
+ throw new Error('p205-transient-authority-invalid');
1277
+ return {
1278
+ contract: 'P205-CI-02', command: P205_COMPLETE_COMMAND,
1279
+ manifestDigest: evidence.manifestDigest, gateIds: evidence.gateIds,
1280
+ resultDigest: evidence.resultDigest, transientAuthority,
1281
+ };
1282
+ }
1283
+ async function physicalCheckoutUnchanged(projectRoot, executionBranch, headSha, committedPaths) {
1284
+ if (await git(projectRoot, ['rev-parse', 'HEAD']) !== headSha
1285
+ || await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== executionBranch
1286
+ || !(await gitExitOk(projectRoot, ['diff', '--cached', '--quiet'])))
1287
+ return false;
1288
+ return gitExitOk(projectRoot, ['diff', '--quiet', 'HEAD', '--', ...committedPaths]);
1289
+ }
1290
+ async function remoteHeadIsExact(projectRoot, remoteInput, branch, headSha) {
1291
+ const remote = safeRemote(remoteInput);
1292
+ const remoteHead = (await git(projectRoot, ['ls-remote', '--heads', remote, `refs/heads/${branch}`])).split(/\s+/)[0];
1293
+ return remoteHead === headSha;
1294
+ }
1295
+ function validateDirectWriteSet(paths, authorizedWriteSet, storyId, rootMemoryEffect) {
1296
+ if (paths.length === 0 || paths.some((path) => !safePath(path))) {
1297
+ return { ok: false, reasonCode: 'direct-yolo-write-set-invalid' };
1298
+ }
1299
+ const required = [
1300
+ '.neocortex/state.json', `docs/stories/${storyId}.story.md`,
1301
+ `.neocortex/stories/${storyId}/qa-gate-result.json`,
1302
+ `.neocortex/stories/${storyId}/validation-evidence.md`,
1303
+ `.neocortex/stories/${storyId}/review.md`,
1304
+ ];
1305
+ if (!required.every((path) => paths.includes(path)) || !required.every((path) => authorizedWriteSet.includes(path))) {
1306
+ return { ok: false, reasonCode: 'direct-yolo-write-set-invalid' };
1307
+ }
1308
+ if (rootMemoryEffect && (rootMemoryEffect.storyId !== storyId
1309
+ || rootMemoryEffect.childClaimRevision !== digest([...authorizedWriteSet].sort().join('\0')))) {
1310
+ return { ok: false, reasonCode: 'direct-yolo-root-memory-claim-mismatch' };
1311
+ }
1312
+ if (paths.some((path) => !authorizedWriteSet.includes(path) && !rootMemoryEffect?.files.some(file => file.path === path))) {
1313
+ return { ok: false, reasonCode: 'direct-yolo-write-set-unauthorized' };
1314
+ }
1315
+ return { ok: true };
1316
+ }
1317
+ function safePath(value) {
1318
+ return value.length > 0 && value.length <= 1024 && !value.startsWith('/') && !value.includes('\\')
1319
+ && !value.split('/').includes('..') && !value.startsWith('.git/') && !value.includes('\0');
1320
+ }
1321
+ function safeTokenValue(value) {
1322
+ return typeof value === 'string' && value.length > 0 && value.length <= 512
1323
+ && /^[A-Za-z0-9._:@/+\-=]+$/.test(value);
1324
+ }
1325
+ function safeRef(value) {
1326
+ return value.length > 0 && value.length <= 240 && !value.startsWith('-') && !/[\s~^:?*[\\]/.test(value) && !value.includes('..');
1327
+ }
1328
+ function safeRemote(value) {
1329
+ if (!/^[A-Za-z0-9._-]{1,128}$/.test(value))
1330
+ throw new Error('direct-yolo-remote-invalid');
1331
+ return value;
1332
+ }
1333
+ function digest(value) { return createHash('sha256').update(value).digest('hex'); }
1334
+ function splitNull(value) { return value.split('\0').filter(Boolean); }
1335
+ function normalizedTime(value) {
1336
+ return value && Number.isFinite(Date.parse(value)) ? new Date(Date.parse(value)).toISOString() : new Date().toISOString();
1337
+ }
1338
+ function asRecord(value) {
1339
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
1340
+ }
1341
+ function validExpiredSetupRecovery(value, runtimeRevision, currentLease, storyId, nowMs) {
1342
+ const expectedLease = asRecord(value.expectedLease);
1343
+ const sessionId = expectedLease?.sessionId;
1344
+ const expiry = Date.parse(String(expectedLease?.expiresAt ?? ''));
1345
+ return value.schemaVersion === 1
1346
+ && Number.isSafeInteger(value.expectedRuntimeRevision)
1347
+ && value.expectedRuntimeRevision === runtimeRevision
1348
+ && Boolean(currentLease) && JSON.stringify(currentLease) === JSON.stringify(expectedLease)
1349
+ && expectedLease?.schemaVersion === 1
1350
+ && expectedLease.ownerStoryId === storyId
1351
+ && typeof sessionId === 'string' && /^setup-[a-f0-9]{64}$/.test(sessionId)
1352
+ && expectedLease.idempotencyKey === sessionId
1353
+ && Number.isFinite(expiry) && expiry <= nowMs;
1354
+ }
1355
+ async function rollbackExpiredSetupRecoveryPhysical(projectRoot, recovery) {
1356
+ let branch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
1357
+ if (branch === recovery.executionBranch) {
1358
+ if (await git(projectRoot, ['rev-parse', 'HEAD']) !== recovery.originHead
1359
+ || await checkoutPayload(projectRoot) !== recovery.checkoutBefore)
1360
+ return;
1361
+ await git(projectRoot, ['switch', recovery.originBranch]);
1362
+ branch = recovery.originBranch;
1363
+ }
1364
+ if (branch !== recovery.originBranch
1365
+ || await git(projectRoot, ['rev-parse', 'HEAD']) !== recovery.originHead
1366
+ || await checkoutPayload(projectRoot) !== recovery.checkoutBefore
1367
+ || recovery.executionHead === recovery.originHead
1368
+ || !(await gitExitOk(projectRoot, ['show-ref', '--verify', '--quiet', recovery.executionRef])))
1369
+ return;
1370
+ const executionHead = await git(projectRoot, ['rev-parse', recovery.executionRef]);
1371
+ if (executionHead === recovery.originHead) {
1372
+ await git(projectRoot, [
1373
+ 'update-ref', recovery.executionRef, recovery.executionHead, recovery.originHead,
1374
+ ]);
1375
+ }
1376
+ }
1377
+ function validOriginBinding(value, executionBranch, originBranch) {
1378
+ const item = asRecord(value);
1379
+ if (!item || item.schemaVersion !== 1 || item.originBranch !== originBranch
1380
+ || item.executionBranch !== executionBranch || item.capturedFromCurrentCheckout !== true
1381
+ || typeof item.originHeadSha !== 'string' || !/^[a-f0-9]{40,64}$/.test(item.originHeadSha)
1382
+ || typeof item.capturedAt !== 'string' || !Number.isFinite(Date.parse(item.capturedAt)))
1383
+ return undefined;
1384
+ return item;
1385
+ }
1386
+ function setupReceipt(authority, binding, leaseExpiresAt, reused) {
1387
+ return Object.freeze({
1388
+ schemaVersion: 1, kind: 'direct-yolo-setup-receipt', storyId: authority.storyId,
1389
+ epicId: authority.epicId, executionBranch: authority.executionBranch, originBranch: authority.originBranch,
1390
+ originHeadSha: binding.originHeadSha, leaseExpiresAt, reused, publicSafe: true,
1391
+ });
1392
+ }
1393
+ async function checkoutPayload(projectRoot) {
1394
+ const untrackedPaths = splitNull(await gitRaw(projectRoot, [
1395
+ 'ls-files', '--others', '--exclude-standard', '-z',
1396
+ ])).sort();
1397
+ const untrackedBlobs = await Promise.all(untrackedPaths.map(async (path) => {
1398
+ if (!safePath(path))
1399
+ throw new Error('direct-yolo-checkout-payload-invalid');
1400
+ return `${path}\0${await git(projectRoot, ['hash-object', '--no-filters', '--', path])}`;
1401
+ }));
1402
+ return digest([
1403
+ await gitRaw(projectRoot, ['diff', '--cached', '--binary', '--full-index']),
1404
+ await gitRaw(projectRoot, ['diff', '--binary', '--full-index']),
1405
+ await gitRaw(projectRoot, ['status', '--porcelain=v1', '-z', '--untracked-files=all']),
1406
+ ...untrackedBlobs,
1407
+ ].join('\0'));
1408
+ }
1409
+ /** Physical observation for a private YOLO agent step; this is not actor attribution. */
1410
+ export async function captureDirectYoloCheckoutEvidence(projectRootInput) {
1411
+ const projectRoot = resolve(projectRootInput);
1412
+ const headSha = await git(projectRoot, ['rev-parse', 'HEAD']);
1413
+ const branch = await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
1414
+ const payloadDigest = await checkoutPayload(projectRoot);
1415
+ if (await git(projectRoot, ['rev-parse', 'HEAD']) !== headSha
1416
+ || await git(projectRoot, ['symbolic-ref', '--quiet', '--short', 'HEAD']) !== branch) {
1417
+ throw new Error('direct-yolo-checkout-observation-raced');
1418
+ }
1419
+ return Object.freeze({ headSha, branch, payloadDigest });
1420
+ }
1421
+ async function worktreeBranches(projectRoot) {
1422
+ const records = [];
1423
+ let current;
1424
+ for (const line of (await gitRaw(projectRoot, ['worktree', 'list', '--porcelain'])).split('\n')) {
1425
+ if (line.startsWith('worktree ')) {
1426
+ current = { path: line.slice('worktree '.length) };
1427
+ records.push(current);
1428
+ }
1429
+ else if (current && line.startsWith('branch refs/heads/')) {
1430
+ current.branch = line.slice('branch refs/heads/'.length);
1431
+ }
1432
+ }
1433
+ return records;
1434
+ }
1435
+ function publicReason(error, fallback) {
1436
+ if (error instanceof Error && error.message === 'git-lifecycle-runtime-revision-conflict') {
1437
+ return 'direct-yolo-runtime-revision-conflict';
1438
+ }
1439
+ return error instanceof Error && /^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(error.message) ? error.message : fallback;
1440
+ }
1441
+ function failure(reasonCode) { return { ok: false, reasonCode }; }
1442
+ async function git(cwd, args) {
1443
+ return String((await execFileAsync('git', [...args], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout).trim();
1444
+ }
1445
+ async function gitRaw(cwd, args) {
1446
+ return String((await execFileAsync('git', [...args], { cwd, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })).stdout);
1447
+ }
1448
+ async function gitExitOk(cwd, args) {
1449
+ try {
1450
+ await execFileAsync('git', [...args], { cwd, maxBuffer: 8 * 1024 * 1024 });
1451
+ return true;
1452
+ }
1453
+ catch {
1454
+ return false;
1455
+ }
1456
+ }