@ornexus/neocortex 4.61.5 → 4.62.0

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