@ornexus/neocortex 4.66.0 → 4.66.1

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 (90) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/install.ps1 +1 -1
  4. package/install.sh +2 -2
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/doctor.d.ts +26 -1
  7. package/packages/client/dist/commands/doctor.js +2 -2
  8. package/packages/client/dist/commands/invoke.d.ts +149 -1
  9. package/packages/client/dist/commands/invoke.js +88 -83
  10. package/packages/client/dist/commands/planning-qa.d.ts +57 -0
  11. package/packages/client/dist/commands/planning-qa.js +1 -1
  12. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
  13. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  14. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  15. package/packages/client/dist/commands/story-worktree.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  18. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  19. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  20. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
  21. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  22. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  23. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  24. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  25. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  26. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  27. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  28. package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
  29. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  30. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  31. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  32. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  33. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  34. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  35. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  36. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  37. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  38. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  39. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  40. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  41. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  42. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  43. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  44. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  45. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  46. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  47. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  48. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  49. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  50. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  51. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  52. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  53. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  54. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  55. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  56. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  57. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  58. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  59. package/packages/client/dist/private-execution/harness-process.js +1 -0
  60. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  61. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  62. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  63. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  64. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  65. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  66. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  67. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  68. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  69. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  71. package/packages/shared/dist/compatibility/index.js +28 -0
  72. package/targets-stubs/antigravity/gemini.md +1 -1
  73. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  74. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  75. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  76. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  77. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  78. package/targets-stubs/claude-code/neocortex.md +2 -2
  79. package/targets-stubs/codex/AGENTS.md +1 -1
  80. package/targets-stubs/cursor/agent.md +2 -2
  81. package/targets-stubs/gemini-cli/agent.md +2 -2
  82. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  83. package/targets-stubs/grok/SKILL.md +3 -3
  84. package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
  85. package/targets-stubs/grok/install-grok.sh +45 -8
  86. package/targets-stubs/lib/managed-config-merge.js +21 -1
  87. package/targets-stubs/lib/mcp-merge.js +12 -3
  88. package/targets-stubs/opencode/neocortex-root.md +1 -1
  89. package/targets-stubs/opencode/neocortex.md +1 -1
  90. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,3 +1,4 @@
1
- import{execFile as ht}from"node:child_process";import{createHash as lt,randomBytes as Ge,timingSafeEqual as pt}from"node:crypto";import{existsSync as We}from"node:fs";import{readFile as F,realpath as ye}from"node:fs/promises";import{join as ee,resolve as L}from"node:path";import{promisify as yt}from"node:util";import{readRootMemoryEffectForCheckpoint as gt}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as mt,verifyRootMemoryPhysicalWriteSet as ge}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as wt,resolveEpicStoryIds as vt}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as me,storyWriteSetCovers as Ve,validateStoryWriteScope as Rt}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as Y,applyGitLifecycleRuntimeOverlay as we,computeImmutableStoryQaEvidenceDigest as St,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as ve,computeP205StoryQaEvidenceDigest as It,computeLegacyDirectYoloRecoveryReceiptRef as xt,ensureRuntimeEpic as z,ensureRuntimeStory as Re,ensureGitLifecyclePrivateChildDirectory as Ke,executeP205TransientAuthorities as bt,executeP205TransientAuthority as kt,isP226GateReasonCode as Se,projectP205TransientExecutionEvidence as Fe,publicStoryReviewArtifactFromBytes as Dt,publicStoryReviewArtifactFromGit as ie,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Et,mutateGitLifecycleRuntime as $,P205_COMPLETE_COMMAND as Ye,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as Je,STORY_WRITE_SET_MAX_ENTRIES as jt,storyWriteSetExtensionPaths as At,assertGitLifecyclePrivateFile as ne,releaseGitLifecyclePhysicalIntegrationLock as J,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as _t,verifyGitLifecyclePhysicalIntegrationLock as ae,verifyAcceptedGitLifecycleStoryCheckpoint as Ie}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ze,anchoredRemoveFile as Bt}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as Ct,GOVERNANCE_DIGEST_TRAILER as Ue,GOVERNANCE_REASON_CODES as ce,captureStoryGovernanceSync as Ht,detectGovernanceModeSync as Ot,governanceReceiptRefs as Lt,isGovernanceRepositoryPath as $t,readGovernanceStateSourceSync as Nt,storyReviewGovernancePath as Pt,verifyStoryGovernanceBinding as qt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as Tt,trailerReasonKey as xe,trailerValue as se}from"./neocortex-trailers.js";import{StoryWorktreeManager as zt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Mt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Qe,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as M}from"./git-lifecycle-step-ids.js";const te=yt(ht),de=3600*1e3;async function jr(e){let t,o=!1;try{const r=await fe(e.projectRoot,e.storyId);if(await be(r.projectRoot)){if(e.expiredSetupRecovery)return s("direct-yolo-expired-setup-recovery-invalid");const v=await et(r);return{ok:!0,value:tt(r,v,!1)}}const i=q(e.nowIso),n=Date.parse(i),d=await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await u(r.projectRoot,["rev-parse","HEAD"]),h=await O(r.projectRoot,{required:!0}),a=m(h.epics[r.epicId]),f=m(a?.branch_lease),y=e.expiredSetupRecovery;if(y&&!rr(y,h.revision,f,e.storyId,n))return s("direct-yolo-expired-setup-recovery-invalid");const I=f&&Number.isFinite(Date.parse(String(f.expiresAt)))&&Date.parse(String(f.expiresAt))>n;if(I&&f?.ownerStoryId!==e.storyId)return s("direct-yolo-writer-active");let l=W(a?.origin_binding,r.executionBranch,r.originBranch),w;if(d===r.executionBranch){if(!l){if(a?.origin_binding!==void 0&&a?.origin_binding!==null||I)return s("direct-yolo-origin-binding-invalid");const v=await ar(r,c,i);if(!v.ok)return v;l=v.value.binding,w={originRef:v.value.originRef,originHeadSha:v.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return s("direct-yolo-current-branch-mismatch");if(l&&l.originHeadSha!==c){if(!y||!await _(r.projectRoot,["merge-base","--is-ancestor",l.originHeadSha,c]))return s("direct-yolo-origin-binding-conflict");const p=`refs/heads/${r.executionBranch}`;if(!await _(r.projectRoot,["show-ref","--verify","--quiet",p]))return s("direct-yolo-execution-branch-missing");const D=await u(r.projectRoot,["rev-parse",p]);if(!await _(r.projectRoot,["merge-base","--is-ancestor",D,c]))return s("direct-yolo-execution-branch-diverged")}if(l??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await oe(r.projectRoot)).some(p=>p.branch===r.executionBranch&&L(p.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const S=await T(r.projectRoot),x=`refs/heads/${r.executionBranch}`;if(await _(r.projectRoot,["show-ref","--verify","--quiet",x])){const p=await u(r.projectRoot,["rev-parse",x]);if(p!==c){if(!await _(r.projectRoot,["merge-base","--is-ancestor",p,c]))return s("direct-yolo-execution-branch-diverged");y||await u(r.projectRoot,["update-ref",x,c,p])}y?t={checkoutBefore:S,executionRef:x,executionBranch:r.executionBranch,executionHead:p,originBranch:r.originBranch,originHead:c}:await u(r.projectRoot,["switch",r.executionBranch])}else{if(y)return s("direct-yolo-execution-branch-missing");await u(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await T(r.projectRoot)!==S)return s("direct-yolo-checkout-payload-raced")}const g=t?.originHead??await u(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return s("direct-yolo-current-branch-mismatch");if(I&&f?.ownerStoryId===e.storyId)return f.setupHeadSha!==g?s("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:le(r,l,String(f.expiresAt),!0)};const j=i,R=new Date(n+3600*1e3).toISOString(),b=`setup-${Ge(32).toString("hex")}`,E=y?h:await O(r.projectRoot,{required:!0});return await $(r.projectRoot,v=>{const S=z(v,r.epicId),x=m(S.branch_lease);if(y&&JSON.stringify(x)!==JSON.stringify(y.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(x&&Date.parse(String(x.expiresAt))>n&&x.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const p=W(S.origin_binding,r.executionBranch,r.originBranch);if(S.origin_binding&&!p)throw new Error("direct-yolo-origin-binding-conflict");if(p&&JSON.stringify(p)!==JSON.stringify(l))throw new Error("direct-yolo-origin-binding-conflict");S.branch_mode="epic",S.execution_branch=r.executionBranch,S.origin_branch=r.originBranch,S.graph_revision=r.graphRevision,S.origin_binding=l,S.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:b,idempotencyKey:b,acquiredAt:j,expiresAt:R,setupHeadSha:g}},{expectedRevision:y?.expectedRuntimeRevision??E.revision,preCommit:async()=>{if(t){if((await oe(r.projectRoot)).some(S=>S.branch===r.executionBranch&&L(S.path)!==r.projectRoot)||await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await T(r.projectRoot)!==t.checkoutBefore||!await _(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await u(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 u(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await u(r.projectRoot,["switch",r.executionBranch]),await T(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==g)throw new Error("direct-yolo-setup-physical-state-raced");if(w&&(await u(r.projectRoot,["rev-parse","--verify","--quiet",`${w.originRef}^{commit}`]).catch(()=>"")!==w.originHeadSha||await Te(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,g])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:le(r,l,R,!1)}}catch(r){return o&&t&&await or(L(e.projectRoot),t).catch(()=>{}),s(V(r,"direct-yolo-setup-failed"))}}async function Ar(e){let t;try{const o=await fe(e.projectRoot,e.storyId);if(await be(o.projectRoot))return await Gt(o);const r=await G(e.projectRoot,e.storyId),i=q(e.nowIso),n=ee(r.projectRoot,".neocortex/state.json"),d=await F(n,"utf8"),c=await T(r.projectRoot),h=await u(r.projectRoot,["rev-parse","HEAD"]),a=`refs/heads/${r.executionBranch}`,f=await O(r.projectRoot,{required:!0}),y=m(f.epics[r.epicId]),I=W(y?.origin_binding,r.executionBranch,r.originBranch),l=m(y?.branch_lease);if(!I)return s("direct-yolo-origin-binding-invalid");if(!l||!Ce(l,e.storyId,i)||l?.sessionId!==l?.idempotencyKey)return s("direct-yolo-setup-lease-invalid");const w=await Y(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(l.sessionId),idempotencyKey:String(l.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!w.ok)return s(w.reasonCode);if(t=w,h!==l.setupHeadSha||!await _(r.projectRoot,["merge-base","--is-ancestor",I.originHeadSha,h])||await u(r.projectRoot,["rev-parse",a])!==h)return s("direct-yolo-setup-head-mismatch");if((await oe(r.projectRoot)).some(S=>S.branch===r.executionBranch&&L(S.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const j=m(JSON.parse(d)),R=m(m(j?.stories)?.[e.storyId]),b=m(f.stories[e.storyId]);if(!R||!["backlog","ready_to_start"].includes(String(R.status))||R.steps_completed!==void 0&&(!Array.isArray(R.steps_completed)||R.steps_completed.length>0)||R.branch_name||R.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const E=b?.status==="branch-ready"&&b.last_step===M&&Array.isArray(b.steps_completed)&&b.steps_completed.length===1&&b.steps_completed[0]===M&&Q(b).sort().join(",")==="last_step,status,steps_completed";if(b&&Q(b).length>0&&!E)return s("direct-yolo-setup-story-progress-conflict");const v=async()=>{if(Date.parse(String(l.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await ae(t.path,t.owner)||await F(n,"utf8")!==d||await T(r.projectRoot)!==c||await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==h||!await _(r.projectRoot,["merge-base","--is-ancestor",I.originHeadSha,h])||await u(r.projectRoot,["rev-parse",a])!==h)throw new Error("direct-yolo-setup-physical-state-raced")};return E?await v():await $(r.projectRoot,S=>{const x=m(S.epics[r.epicId]),p=Re(S,e.storyId);if(JSON.stringify(x?.branch_lease)!==JSON.stringify(l)||JSON.stringify(x?.origin_binding)!==JSON.stringify(I)||x?.graph_revision!==r.graphRevision||Q(p).length>0)throw new Error("direct-yolo-setup-runtime-raced");p.status="branch-ready",p.last_step=M,p.steps_completed=[M]},{expectedRevision:f.revision,preCommit:v}),{ok:!0,value:Object.freeze({...le(r,I,String(l.expiresAt),E),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:h})}}catch(o){return s(V(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await J(t.path,t.owner).catch(()=>{})}}async function _r(e){try{const t=await G(e.projectRoot,e.storyId),o=P(await C(t.projectRoot,["diff","--cached","--name-only","-z"])),r=U(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return s(r.reasonCode);t.rootMemoryEffect&&ge(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await u(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet});const i=t.governanceMode==="runtime-store"?De(t):void 0;if((i?i.review:ie(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(P(await C(t.projectRoot,["diff","--name-only","-z"])).some(D=>o.includes(D)))return s("direct-yolo-user-overlap");const c=await C(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return s("direct-yolo-staged-diff-empty");const h=A(c),a=A([...t.authorizedWriteSet].sort().join("\0")),f=q(e.nowIso),y=await O(t.projectRoot,{required:!0}),I=m(y.epics[t.epicId]?.branch_lease);if(!Ce(I,e.storyId,f))return s("direct-yolo-setup-handoff-owner-invalid");const l=String(I.sessionId),w=String(I.expiresAt),g=new Date(Math.min(Date.parse(w),Date.parse(f)+300*1e3)).toISOString(),j=await Z(t.projectRoot,e.storyId),R=j?.state==="issued"&&j.fromSessionId===l&&j.bundleDigest===h&&j.claimRevision===a&&Date.parse(j.expiresAt)>Date.parse(f),b=R?j.expiresAt:g,E=R?j.token:Ge(32).toString("base64url"),v=A(E),S=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:l,tokenDigest:v,bundleDigest:h,claimRevision:a,expiresAt:b}),x=A(JSON.stringify(S)),p=await Y(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:l,idempotencyKey:l,expiresAt:b,persistent:!1,createdAt:f});if(!p.ok)return s(p.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await He(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:l,token:E,tokenDigest:v,bundleDigest:h,claimRevision:a,grantDigest:x,expiresAt:b}),await $(t.projectRoot,D=>{const k=m(z(D,t.epicId).branch_lease);if(!Ce(k,e.storyId,f)||k?.sessionId!==l||k.idempotencyKey!==l)throw new Error("direct-yolo-setup-handoff-owner-raced");k.handoffGrant=S},{expectedRevision:y.revision,preCommit:async()=>{if(!await ae(p.path,p.owner))throw new Error("direct-yolo-integration-lock-raced");const D=await Z(t.projectRoot,e.storyId);if(!D||D.state!=="issued"||D.grantDigest!==x||D.tokenDigest!==v)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await J(p.path,p.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:l,bundleDigest:h,claimRevision:a,grantDigest:x,expiresAt:b,reused:R,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return s(t instanceof Error&&(/^direct-yolo-/.test(t.message)||ft.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function Br(e){try{const t=await G(e.projectRoot,e.storyId),o=await u(t.projectRoot,["rev-parse","HEAD"]),r=P(await C(t.projectRoot,["diff","--cached","--name-only","-z"])),i=U(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return s(i.reasonCode);t.rootMemoryEffect&&ge(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?De(t):void 0,d=n?n.review:ie(t.projectRoot,e.storyId,":");if(d?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(P(await C(t.projectRoot,["diff","--name-only","-z"])).some(k=>r.includes(k)))return s("direct-yolo-user-overlap");const h=await C(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!h)return s("direct-yolo-staged-diff-empty");const a=A(h),f=A([...t.authorizedWriteSet].sort().join("\0")),y=await ot(t.projectRoot,e.storyId),I=y.state==="valid"&&y.plan.epicId===t.epicId&&y.plan.executionBranch===t.executionBranch&&y.plan.preparedBase===o&&y.plan.bundleDigest===a&&y.plan.claimRevision===f?y.plan:void 0,l=I?.graphRevision??t.graphRevision,w=_e({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:a,graphRevision:l,claimRevision:f}),g=q(e.nowIso),j={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:l,preparedBase:o,bundleDigest:a,claimRevision:f,idempotencyKey:w,issuedAt:I?.issuedAt??g};let R=e.setupLeaseHandoff??await Yt(t.projectRoot,e.storyId,a,f,g);const b=await O(t.projectRoot,{required:!0}),E=m(b.epics[t.epicId]?.branch_lease),v=E?.ownerStoryId===e.storyId&&E.sessionId===w&&E.idempotencyKey===w&&typeof E.expiresAt=="string"&&Date.parse(E.expiresAt)>Date.parse(g)?E:void 0;if(v&&e.setupLeaseHandoff)return s("direct-yolo-setup-handoff-replayed");const S=m(v?.handoffConsumption);if(S){const k=await Z(t.projectRoot,e.storyId);if(!k||!["consuming","consumed"].includes(k.state)||k.fromSessionId!==S.fromSessionId||k.tokenDigest!==S.tokenDigest||k.bundleDigest!==a||k.claimRevision!==f||S.bundleDigest!==a||S.claimRevision!==f||k.consumedBySessionId!==w||S.consumedBySessionId!==w)return s("direct-yolo-setup-handoff-consume-invalid");if(k.state==="consuming"){if(!k.token||A(k.token)!==k.tokenDigest)return s("direct-yolo-setup-handoff-consume-invalid");R={sessionId:k.fromSessionId,token:k.token}}}const x=v?String(v.expiresAt):new Date(Date.parse(g)+de).toISOString(),p=await Y(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:x,persistent:!0,createdAt:v&&typeof v.acquiredAt=="string"?v.acquiredAt:g});if(!p.ok)return s(p.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{R&&e.setupLeaseHandoff===void 0&&(await Jt(t.projectRoot,e.storyId,R.sessionId,R.token,w,g),await e.setupHandoffFault?.("after-consuming-persisted")),await $(t.projectRoot,k=>{const H=z(k,t.epicId),B=m(H.branch_lease),N=B&&Date.parse(String(B.expiresAt))>Date.parse(g),K=B?.ownerStoryId===e.storyId&&B.sessionId===w&&B.idempotencyKey===w,ut=B?.ownerStoryId===e.storyId&&B.sessionId===B.idempotencyKey&&typeof B.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(B.idempotencyKey),pe=N&&ut&&Ut({current:B,handoff:R,storyId:e.storyId,bundleDigest:a,claimRevision:f,nowIso:g});if(R&&N&&!K&&!pe)throw new Error("direct-yolo-setup-handoff-invalid");if(N&&!K&&!pe)throw new Error("direct-yolo-writer-active");const ze=pe?m(B?.handoffGrant):void 0,Me=ze?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(B?.sessionId),tokenDigest:String(ze.tokenDigest),bundleDigest:a,claimRevision:f,consumedBySessionId:w,consumedAt:g}:void 0;H.branch_mode="epic",H.execution_branch=t.executionBranch,H.origin_branch=t.originBranch,H.graph_revision=t.graphRevision,H.branch_lease=N&&K?B:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:w,idempotencyKey:w,acquiredAt:g,expiresAt:x,...Me?{handoffConsumption:Me}:{}}},{expectedRevision:b.revision,preCommit:async()=>{if(!await ae(p.path,p.owner))throw new Error("direct-yolo-integration-lock-raced");await Ft(t.projectRoot,j)}})}catch(k){throw await J(p.path,p.owner).catch(()=>{}),k}R&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Zt(t.projectRoot,t.epicId,e.storyId,R.sessionId,R.token,a,f,w,g));const D=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${a}`,`Neocortex-Review-Artifact-Digest: ${d.digest}`,`Neocortex-Graph-Revision: ${l}`,`Neocortex-Claim-Revision: ${f}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${mt(t.rootMemoryEffect)}`]:[],...n?[`${Ue}: ${n.receipt.governanceDigest}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:a,reviewArtifactDigest:d.digest,graphRevision:l,claimRevision:f,idempotencyKey:w,changedPaths:Object.freeze(r),trailers:D,...n?{governance:n.receipt}:{}})}}catch(t){return s(V(t,"direct-yolo-begin-failed"))}}async function Cr(e){let t,o,r;try{const i=await G(e.projectRoot,e.storyId);t=i;const n=await u(i.projectRoot,["rev-parse","HEAD"]);let d=await O(i.projectRoot,{required:!0});const c=m(d.stories[e.storyId]?.checkpoint);if(c){const x=typeof c.headSha=="string"?c.headSha:"",p=typeof c.graphRevision=="string"?c.graphRevision:"",D=/^[a-f0-9]{40,64}$/.test(x)?P(await C(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",x])):[],k=U(D,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(x)&&await _(i.projectRoot,["merge-base","--is-ancestor",x,n]))||!/^[a-f0-9]{64}$/.test(p)||!k.ok)return s("direct-yolo-replay-invalid");const B=await $e(e,i.projectRoot,n,p);if(!await Ie(i.projectRoot,c,e.storyId,i.epicId,i.executionBranch,B.transientAuthority,i.authorizedWriteSet))return s("direct-yolo-replay-invalid");if(!await Ne(i.projectRoot,i.executionBranch,n,D))return s("direct-yolo-replay-head-raced");if(e.push&&!await rt(i.projectRoot,e.remote??"origin",i.executionBranch,x))return s("direct-yolo-remote-head-mismatch");const N=Array.isArray(c.receiptRefs)?c.receiptRefs.find(K=>typeof K=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(K)):void 0;return N&&typeof c.idempotencyKey=="string"&&await _t(i.projectRoot,{storyId:e.storyId,idempotencyKey:c.idempotencyKey,ownerDigest:N.slice(20)}),await ue(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:c}}const h=n,a=await Xe(i,e.storyId,h);if(!a.ok)return s(a.reasonCode);const{baseSha:f,changedPaths:y,bundleDigest:I,graphRevision:l,claimRevision:w,idempotencyKey:g,governance:j}=a.value,R=m(d.epics[i.epicId]?.branch_lease),b=q(e.nowIso),E=R?.ownerStoryId===e.storyId&&R.idempotencyKey===g&&R.sessionId===g&&Date.parse(String(R.expiresAt))>Date.now()?R:void 0;if(R&&Date.parse(String(R.expiresAt))>Date.now()&&!E)return s("direct-yolo-writer-active");const v=E??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:g,idempotencyKey:g,acquiredAt:b,expiresAt:new Date(Date.parse(b)+de).toISOString()},S=await Y(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:g,idempotencyKey:g,expiresAt:String(v.expiresAt),persistent:!0,createdAt:String(v.acquiredAt)});if(!S.ok)return s(S.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=S,E||(d=(await $(i.projectRoot,p=>{const D=z(p,i.epicId),k=m(D.branch_lease);if(k&&Date.parse(String(k.expiresAt))>Date.parse(b))throw new Error("direct-yolo-writer-active");if(D.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");D.branch_lease=v},{expectedRevision:d.revision})).document),o=v;{const x=await $e(e,i.projectRoot,h,l);if(!await Ne(i.projectRoot,i.executionBranch,h,y))return s("direct-yolo-head-raced");if(e.push){const k=re(e.remote??"origin");if(await u(i.projectRoot,["push",k,i.executionBranch]),!await Pe(i.projectRoot,k,i.executionBranch,h))return s("direct-yolo-remote-head-mismatch")}const p=await je({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:f,headSha:h,bundleDigest:I,graphRevision:l,claimRevision:w,idempotencyKey:g,qaExecution:x,physicalLockOwnerDigest:ve(S.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...j?{governance:j}:{}});return await e.beforeCheckpointPersist?.(),await Ae({projectRoot:i.projectRoot,checkpoint:p,remote:e.push?e.remote??"origin":void 0,expectedRevision:d.revision,expectedLease:v,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:l,physicalLockPath:S.path,physicalLockOwner:S.owner,transientAuthority:x.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ue(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:p}):s("direct-yolo-checkpoint-persist-failed")}}catch(i){return s(V(i,"direct-yolo-finalize-failed"))}finally{r&&await J(r.path,r.owner).catch(()=>{}),t&&o?await Le(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await Xt(t,e.storyId).catch(()=>{})}}async function Xe(e,t,o){const r=await u(e.projectRoot,["rev-parse",`${o}^`]),i=await C(e.projectRoot,["show","--no-patch","--format=%B",o]),n=P(await C(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),d=U(n,e.authorizedWriteSet,t,e.rootMemoryEffect,e.governanceMode);if(!d.ok)return s(d.reasonCode);e.rootMemoryEffect&&ge(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const c=A([...e.authorizedWriteSet].sort().join("\0")),h=await ot(e.projectRoot,t);if(h.state==="invalid")return s("direct-yolo-commit-plan-invalid");const a=h.state==="valid"?h.plan:void 0;if(a&&(a.epicId!==e.epicId||a.executionBranch!==e.executionBranch))return s("direct-yolo-commit-plan-invalid");if(a&&a.claimRevision!==c)return s("direct-yolo-commit-plan-claim-changed");if(a&&a.preparedBase!==r)return s("direct-yolo-commit-plan-base-mismatch");const f=Tt(i,Ct);if(!f.ok)return s(`direct-yolo-trailer-duplicate:${f.key}`);const y=f.values,I=a?.graphRevision??e.graphRevision,l=c,w=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",a?.bundleDigest??""],["Neocortex-Graph-Revision",I],["Neocortex-Claim-Revision",l]];for(const[x,p]of w){const D=se(y,x);if(D===void 0)return s(`direct-yolo-trailer-missing:${xe(x)}`);if(x==="Neocortex-Bundle-Digest"&&!a){if(!/^[a-f0-9]{64}$/.test(D))return s(`direct-yolo-trailer-mismatch:${xe(x)}`);continue}if(D!==p)return s(`direct-yolo-trailer-mismatch:${xe(x)}`)}const g=se(y,"Neocortex-Bundle-Digest"),j=se(y,Ue);if(e.governanceMode!=="runtime-store"&&j!==void 0)return s(ce.MISMATCH);const R=e.governanceMode==="runtime-store"?Ee({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},j):void 0,b=R?R.review:ie(e.projectRoot,t,o);if(b?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");const E=se(y,"Neocortex-Review-Artifact-Digest");if(E!==void 0&&E!==b.digest)return s("direct-yolo-review-artifact-digest-mismatch");const v=A(await C(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(g!==v)return s("direct-yolo-bundle-digest-mismatch");const S=_e({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:g,graphRevision:I,claimRevision:l});return a&&a.idempotencyKey!==S?s("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:n,bundleDigest:g,graphRevision:I,claimRevision:l,idempotencyKey:S,...R?{governance:R.receipt}:{}}}}async function Hr(e){try{const t=await G(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return s("direct-yolo-recovery-commit-invalid");const o=await u(t.projectRoot,["rev-parse",e.commitSha]);if(Et[e.storyId]!==o)return s("direct-yolo-recovery-not-allowlisted");if(await u(t.projectRoot,["rev-parse","HEAD"])!==o)return s("direct-yolo-recovery-head-mismatch");await u(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await u(t.projectRoot,["rev-parse",`${o}^`]),i=await C(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=P(await C(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!U(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return s("direct-yolo-recovery-write-set-invalid");const c=A(i),h=A([...n].sort().join("\0")),a=A(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),f=q(e.nowIso),y=new Date(Date.parse(f)+de).toISOString(),I=await O(t.projectRoot,{required:!0}),l=await Y(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:a,idempotencyKey:a,expiresAt:y,persistent:!0,createdAt:f});if(!l.ok)return s(l.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const w={schemaVersion:1,ownerStoryId:e.storyId,sessionId:a,idempotencyKey:a,acquiredAt:f,expiresAt:y};let g=!1;try{const j=await $(t.projectRoot,x=>{const p=z(x,t.epicId),D=m(p.branch_lease);if(D&&Date.parse(String(D.expiresAt))>Date.parse(f)&&!Oe(D,w))throw new Error("direct-yolo-recovery-writer-active");if(p.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");p.branch_mode="epic",p.execution_branch=t.executionBranch,p.origin_branch=t.originBranch,p.branch_lease=w},{expectedRevision:I.revision});g=!0;const R=await $e(e,t.projectRoot,o,t.graphRevision);if(!await Ne(t.projectRoot,t.executionBranch,o,n))return s("direct-yolo-recovery-head-raced");if(e.push){const x=re(e.remote??"origin"),p=(await u(t.projectRoot,["ls-remote","--heads",x,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!p||!await _(t.projectRoot,["merge-base","--is-ancestor",o,p]))return s("direct-yolo-recovery-remote-proof-missing")}const b=await je({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:h,idempotencyKey:a,qaExecution:R,physicalLockOwnerDigest:ve(l.owner),nowIso:f,legacyReceiptRef:void 0}),E=await xt(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!E)return s("direct-yolo-recovery-evidence-invalid");const v=Object.freeze({...b,receiptRefs:Object.freeze([...b.receiptRefs,E])});return await Ae({projectRoot:t.projectRoot,checkpoint:v,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:j.document.revision,expectedLease:w,expectedGraphRevision:t.graphRevision,physicalLockPath:l.path,physicalLockOwner:l.owner,transientAuthority:R.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:v}:s("direct-yolo-recovery-persist-failed")}finally{await J(l.path,l.owner).catch(()=>{}),g&&await Le(t.projectRoot,t.epicId,w).catch(()=>{})}}catch(t){return s(V(t,"direct-yolo-recovery-failed"))}}async function be(e){const t=await ye(await u(e,["rev-parse","--absolute-git-dir"])),o=await ye(await u(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function et(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(y=>y.storyId===e.storyId&&y.epicId===e.epicId&&y.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 ye(await u(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await u(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const d=await new zt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=W(m(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const h=r.syncedSha??r.baseSha,a=await u(e.projectRoot,["rev-parse","HEAD"]),f=`refs/heads/${e.executionBranch}`;if(a!==h||!await _(e.projectRoot,["merge-base","--is-ancestor",h,f])||!await _(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,h]))throw new Error("direct-yolo-worktree-base-divergent");if(d.value.clean!==!0||(await C(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:a,expiresAt:r.expiresAt,binding:c}}function tt(e,t,o){return Object.freeze({...le(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Gt(e){const t=await et(e),o=ke(e.projectRoot),r=m(JSON.parse(o)),i=m(m(r?.stories)?.[e.storyId]),n=await O(e.projectRoot,{required:!0}),d=m(n.stories[e.storyId]);if(!i||!["backlog","ready_to_start"].includes(String(i.status))||i.steps_completed!==void 0&&(!Array.isArray(i.steps_completed)||i.steps_completed.length>0)||i.branch_name||i.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const c=d?.status==="branch-ready"&&d.last_step===M&&Array.isArray(d.steps_completed)&&d.steps_completed.length===1&&d.steps_completed[0]===M&&Q(d).sort().join(",")==="last_step,status,steps_completed";return d&&Q(d).length>0&&!c?s("direct-yolo-setup-story-progress-conflict"):(c||await $(e.projectRoot,h=>{const a=Re(h,e.storyId);if(Q(a).length>0)throw new Error("direct-yolo-setup-runtime-raced");a.status="branch-ready",a.last_step=M,a.steps_completed=[M]},{expectedRevision:n.revision,preCommit:async()=>{if(ke(e.projectRoot)!==o||await u(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await u(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await C(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({...tt(e,t,c),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function Or(e,t){const o=await G(e,t),r=await O(o.projectRoot,{required:!0}),i=W(m(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Lr(e,t,o,r,i="tracked"){return U(e,t,o,r,i)}function $r(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Nr=de,Wt="p205-wave:";function Pr(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=A(["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 Vt(e){return`${Wt}${e.waveHeadSha}:${e.waveDigest}`}async function qr(e){let t;try{t=await bt(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:Se(r)?r:"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/^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:Se(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Tr(e,t,o,r){const i=re(t);return await u(e,["push",i,o]),Pe(e,i,o,r)}async function zr(e){try{const t=await G(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 s("direct-yolo-wave-coverage-invalid");if(await u(t.projectRoot,["rev-parse","HEAD"])!==o||await u(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await _(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return s("direct-yolo-wave-head-raced");const i=await O(t.projectRoot,{required:!0}),n=m(i.stories[e.storyId]?.checkpoint);if(n){if(n.headSha!==e.headSha)return s("direct-yolo-checkpoint-conflict");const b=e.authorities.get(String(n.graphRevision));return await Ie(t.projectRoot,n,e.storyId,t.epicId,t.executionBranch,b??null,t.authorizedWriteSet)?(await ue(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:n}):s("direct-yolo-replay-invalid")}const d=await Xe(t,e.storyId,e.headSha);if(!d.ok)return s(d.reasonCode);const{baseSha:c,bundleDigest:h,graphRevision:a,claimRevision:f,idempotencyKey:y,governance:I}=d.value,l=r===0?void 0:e.coverage.waveCommitShas[r-1];if(l!==void 0&&c!==l)return s("direct-yolo-wave-chain-invalid");const w=e.authorities.get(a),g=Fe(w);if(!w||!g||g.executionHeadSha!==o||g.graphRevision!==a)return s("direct-yolo-wave-qa-unbound");const j=await je({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:c,headSha:e.headSha,bundleDigest:h,graphRevision:a,claimRevision:f,idempotencyKey:y,qaExecution:{contract:"P205-CI-02",command:Ye,manifestDigest:g.manifestDigest,gateIds:g.gateIds,resultDigest:g.resultDigest,transientAuthority:w},physicalLockOwnerDigest:ve(e.physicalLock.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Vt(e.coverage)],...I?{governance:I}:{}});return await Ae({projectRoot:t.projectRoot,checkpoint:j,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:a,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:w,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ue(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:j}):s("direct-yolo-checkpoint-persist-failed")}catch(t){return s(V(t,"direct-yolo-wave-persist-failed"))}}async function fe(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=L(e),r=m(JSON.parse(ke(o))),i=await O(o,{required:!0}),n=we(r,i),d=Ot({projectRoot:o,storyId:t});if(!d.ok)throw new Error(d.reasonCode);const c=d.mode,h=m(n.stories),a=m(n.epics),f=m(h?.[t]),y=String(f?.epic_id??t.split(".")[0]),I=m(a?.[y]),l=String(I?.execution_branch??""),w=String(I?.origin_branch??""),g=String(I?.graph_revision??""),j=Array.isArray(f?.files_to_modify)?f.files_to_modify:[],R=At(f).filter(tr),b=[...j,...R],E=b.length>0?me(t,b):void 0,v=E?.ok?E.scopes:[];if(!f)throw new Error("direct-yolo-story-state-missing");if(R.length>0&&v.length>jt)throw new Error("direct-yolo-write-set-too-large");if(I?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!X(l)||!await _(o,["check-ref-format","--branch",l]))throw new Error("direct-yolo-execution-branch-invalid");if(!X(w)||!await _(o,["check-ref-format","--branch",w]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(g))throw new Error("direct-yolo-graph-revision-invalid");const S=await gt({projectRoot:o,storyId:t,graphRevision:g,executionBranch:l,childPaths:v});return{projectRoot:o,storyId:t,story:f,epicId:y,executionBranch:l,originBranch:w,graphRevision:g,authorizedWriteSet:v,rootMemoryEffect:S,governanceMode:c}}async function Mr(e){try{const t=await fe(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?s("governance-capture-not-applicable"):await be(t.projectRoot)?s("governance-capture-root-required"):{ok:!0,value:De(t).receipt}}catch(t){return s(V(t,"governance-capture-failed"))}}function ke(e){const t=Nt(e);if(!t.ok)throw new Error(t.reasonCode);if(!t.value)throw new Error("direct-yolo-story-state-missing");return t.value.toString("utf8")}function De(e){const t=Ht(e);if(!t.ok)throw new Error(t.reasonCode);return Ee(e,t.value.governanceDigest)}function Ee(e,t){const o=qt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Pt(e.storyId));if(!r)throw new Error(ce.MISMATCH);return{receipt:o.value.receipt,review:Dt(e.storyId,r)}}async function G(e,t){const o=await fe(e,t);if(await u(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function je(e){const t=e.nowIso,o=await C(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=P(await C(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=St({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=It({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),d=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:d}),h=e.governance?Ee(e,e.governance.governanceDigest).review:ie(e.projectRoot,e.storyId,e.headSha);if(h?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const a=A(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,d,A(o),[...r].sort().join(","),h.digest].join("\0")),f=`story-review:${a}`,y=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:a,reviewArtifactDigest:h.digest,qaReceiptRef:d,verdict:"approved",reviewedAt:t,receiptRef:f}),I=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,d,f,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[],...e.governance?Lt(e.governance):[]];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(I),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:y,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function Ae(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await $(t,n=>{const d=z(n,o.epicId);if(e.expectedLease){const f=m(d.branch_lease);if(!Oe(f,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(f?.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 c=Re(n,o.storyId),h=m(c.checkpoint);if(h&&h.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=Qe;const a=Array.isArray(c.steps_completed)?c.steps_completed.filter(f=>typeof f=="string"):[];c.steps_completed=[...new Set([...a,Mt,Qe])],e.keepLease||(d.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await u(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await u(t,["rev-parse","HEAD"])!==n||await u(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await _(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await Ie(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 ae(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await rt(t,r,o.branch,o.headSha):await Pe(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function rt(e,t,o,r){const i=re(t),n=(await u(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await _(e,["merge-base","--is-ancestor",r,n]))}function _e(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Kt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Be(e,t){const o=await Je(e),r=await Ke(o,"commit-plans"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:ee(r,i)}}async function Ft(e,t){const o=await Be(e,t.storyId);await Ze(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
- `),await ne(o.path,o.parent)}async function ot(e,t){let o;try{o=await Be(e,t)}catch{return{state:"invalid"}}try{if(!We(o.path))return{state:"absent"};await ne(o.path,o.parent);const r=await F(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=m(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...Kt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!X(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 n=i;return n.idempotencyKey!==_e({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ue(e,t){const o=await Be(e,t);We(o.path)&&await Bt(o.parent,o.name)}function Ce(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 it(e,t){const o=await Je(e),r=await Ke(o,"handoffs"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:ee(r,i)}}async function He(e,t){const o=await it(e,t.storyId);await Ze(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
- `),await ne(o.path,o.parent)}async function Z(e,t){try{const o=await it(e,t);await ne(o.path,o.parent);const r=JSON.parse(await F(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function Yt(e,t,o,r,i){const n=await Z(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||A(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Jt(e,t,o,r,i,n){const d=await Z(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==A(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 He(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Zt(e,t,o,r,i,n,d,c,h){const a=await Z(e,o);if(a?.state==="consumed"&&a.fromSessionId===r&&a.consumedBySessionId===c)return;const f=await O(e,{required:!0}),y=m(f.epics[t]?.branch_lease),I=m(y?.handoffConsumption);if(!a||a.state!=="consuming"||a.fromSessionId!==r||a.token!==i||a.tokenDigest!==A(i)||a.bundleDigest!==n||a.claimRevision!==d||a.consumedBySessionId!==c||y?.ownerStoryId!==o||y.sessionId!==c||I?.kind!=="direct-yolo-setup-handoff-consumption"||I.state!=="consumed"||I.fromSessionId!==r||I.tokenDigest!==a.tokenDigest||I.bundleDigest!==n||I.claimRevision!==d||I.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await He(e,{schemaVersion:1,kind:a.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:a.tokenDigest,bundleDigest:a.bundleDigest,claimRevision:a.claimRevision,grantDigest:a.grantDigest,expiresAt:a.expiresAt,consumedBySessionId:c,consumedAt:h})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function Ut(e){const t=m(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?A(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)&&Qt(t.tokenDigest,r))}function Qt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&pt(o,r)}function Oe(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Le(e,t,o){await $(e,r=>{const i=z(r,t),n=m(i.branch_lease);Oe(n,o)&&(i.branch_lease=null)})}async function Xt(e,t){const o=await O(e.projectRoot,{required:!0}),r=m(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!nt(r.sessionId)||!nt(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await Y(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 J(i.path,i.owner)&&await Le(e.projectRoot,e.epicId,r)}async function $e(e,t,o,r){const i=await kt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=Fe(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Ye,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function Ne(e,t,o,r){return await u(e,["rev-parse","HEAD"])!==o||await u(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await _(e,["diff","--cached","--quiet"])?!1:_(e,["diff","--quiet","HEAD","--",...r])}async function Pe(e,t,o,r){const i=re(t);return(await u(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function U(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!qe(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return er(e,t,o,r);const n=t.length>0?me(o,t):void 0;return n?.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(c=>e.includes(c))?r&&(r.storyId!==o||r.childClaimRevision!==A([...n.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(c=>!Ve(n.scopes,c)&&!r?.files.some(h=>h.path===c))?{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 er(e,t,o,r){if(e.some($t))return{ok:!1,reasonCode:ce.WRITE_SET_FORBIDDEN};const i=t.length>0?me(o,t):void 0;if(!i?.ok)return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const n=`docs/stories/${o}.story.md`;return!e.includes(n)||!e.some(d=>d!==n)?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==A([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!Ve(i.scopes,d)&&!r?.files.some(c=>c.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function Q(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function tr(e){return typeof e!="string"||e.length>512||!qe(e)||!Rt(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function qe(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function nt(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function X(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function re(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function A(e){return lt("sha256").update(e).digest("hex")}function P(e){return e.split("\0").filter(Boolean)}function q(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function m(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function rr(e,t,o,r,i){const n=m(e.expectedLease),d=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof d=="string"&&/^setup-[a-f0-9]{64}$/.test(d)&&n.idempotencyKey===d&&Number.isFinite(c)&&c<=i}async function or(e,t){let o=await u(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await u(e,["rev-parse","HEAD"])!==t.originHead||await T(e)!==t.checkoutBefore)return;await u(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await u(e,["rev-parse","HEAD"])!==t.originHead||await T(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await _(e,["show-ref","--verify","--quiet",t.executionRef]))return;await u(e,["rev-parse",t.executionRef])===t.originHead&&await u(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const ir=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],nr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function W(e,t,o){const r=m(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!==ir.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==nr.join("\0")?void 0:r}async function ar(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await _(e.projectRoot,["show-ref","--verify","--quiet",r]))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await u(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await oe(e.projectRoot)).some(h=>h.branch===e.executionBranch&&L(h.path)!==e.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await u(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return s("direct-yolo-setup-physical-state-raced");const c=await Te(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?s("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?s("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}}}}const at=3e4,cr=3,sr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class he extends Error{}function dr(e,t=at){return{timeout:t,killSignal:"SIGKILL",env:{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...e.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:sr}}}}async function fr(e){if(!X(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await te("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:L(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...dr(process.env,e.fetchTimeoutMs??at)}),{ok:!0}}catch(t){const o=String(t.stderr??"");return{ok:!1,reasonCode:/non-fast-forward|\[rejected\]/.test(o)?"origin-binding-start-fetch-non-fast-forward":"origin-binding-start-fetch-unavailable"}}}const ur=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function Gr(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=L(e),i=m(JSON.parse(await F(ee(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),d=we(i,n),c=m(m(d.epics)?.[t]);if(!c)return o;const h=st(d,t,c),a=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,f=await ct(r,c,i),y=m(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:h,terminal:ur.has(String(c.status??"").toLowerCase()),bound:!!W(y,a,f),executionBranch:a,originBranch:f})}catch{return o}}async function ct(e,t,o){if(typeof t.origin_branch=="string"&&t.origin_branch.length>0)return t.origin_branch;const r=m(o.config)?.default_branch;if(r!=null&&String(r).length>0)return String(r);const i=await u(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]).catch(()=>"");if(i.startsWith("origin/")&&i.length>7)return i.slice(7);const n=[];for(const d of["main","master"])await _(e,["rev-parse","--verify","--quiet",`refs/heads/${d}^{commit}`])&&await _(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${d}^{commit}`])&&n.push(d);return n.length===1?n[0]:""}function st(e,t,o){if(o.branch_mode==="epic")return"recorded-epic";if(o.branch_mode!==void 0&&o.branch_mode!==null)return"not-epic";const r=m(e.stories)??{},n=vt(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const h=m(r[c]);return h?[{...h,id:c}]:[]}),d=wt({...o,id:t},n);return d.mode==="epic"&&(d.source==="new-epic-default"||d.source==="epic-boundary")?"resolved-epic":"not-epic"}function dt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function Wr(e){const t=q(e.nowIso),o=Date.parse(t),r=(c,h={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...h,outcome:"refused",reasonCode:c,executionRefCreated:!1,capturedAt:t});if(!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e.epicId))return r("origin-binding-start-target-ambiguous");const i=L(e.projectRoot);let n=e.originFetch,d="origin-binding-start-raced";for(let c=0;c<cr;c+=1){let h,a={};try{const f=m(JSON.parse(await F(ee(i,".neocortex/state.json"),"utf8")));if(!f)return r("origin-binding-start-state-invalid");const y=await O(i),I=we(f,y),l=m(m(I.epics)?.[e.epicId]);if(!l)return r("origin-binding-start-target-ambiguous");if(st(I,e.epicId,l)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const w=typeof l.execution_branch=="string"&&l.execution_branch.length>0?l.execution_branch:`epic/${e.epicId}`,g=await ct(i,l,f);if(a={executionBranch:w,originBranch:g},!X(w)||!X(g)||w===g||!await _(i,["check-ref-format","--branch",w])||!await _(i,["check-ref-format","--branch",g]))return r("origin-binding-start-branch-invalid",a);const j=m(y.epics[e.epicId]),R=j?.origin_binding??l.origin_binding;if(R!=null){const H=W(R,w,g);return H?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:H.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",a)}if(dt(m(j?.branch_lease??l.branch_lease),o))return r("origin-binding-start-lease-inconsistent",a);if(n??=await fr({projectRoot:i,originBranch:g,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,a);const b=`refs/remotes/origin/${g}`,E=`refs/heads/${g}`,v=await u(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>""),S=await u(i,["rev-parse","--verify","--quiet",`${b}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(v)||v!==S)return r("origin-binding-start-origin-stale",a);if((await oe(i)).some(H=>H.branch===w&&L(H.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",a);const p=`refs/heads/${w}`,D=await u(i,["rev-parse","--verify","--quiet",`${p}^{commit}`]).catch(()=>"");if(D){const H=await Te(i,["merge-base","--is-ancestor",v,D]);if(H===1)return r("direct-yolo-origin-not-ancestor",a);if(H!==0)return r("direct-yolo-origin-ancestry-unverifiable",a)}const k={schemaVersion:2,originBranch:g,originHeadSha:v,executionBranch:w,capturedFrom:"branch-ref",capturedAt:t};return await $(i,H=>{const B=z(H,e.epicId);if(B.origin_binding!==void 0&&B.origin_binding!==null)throw new he("origin-binding-start-raced");if(dt(m(B.branch_lease),o))throw new he("origin-binding-start-lease-inconsistent");B.origin_binding=k},{expectedRevision:y.revision,preCommit:async()=>{const H=await u(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>""),B=await u(i,["rev-parse","--verify","--quiet",`${b}^{commit}`]).catch(()=>""),N=await u(i,["rev-parse","--verify","--quiet",`${p}^{commit}`]).catch(()=>"");if(H!==v||B!==v||N!==D)throw new he("origin-binding-start-raced");D||(await u(i,["update-ref",p,v,""]),h={ref:p,sha:v})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:v,outcome:"captured",executionRefCreated:h!==void 0,capturedAt:t})}catch(f){if(h&&await u(i,["update-ref","-d",h.ref,h.sha]).catch(()=>{}),f instanceof Error&&f.message==="git-lifecycle-runtime-revision-conflict"){d="origin-binding-start-raced";continue}return f instanceof he?r(f.message,a):r("origin-binding-start-failed",a)}}return r(d)}function le(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 T(e){const t=P(await C(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!qe(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await u(e,["hash-object","--no-filters","--",r])}`}));return A([await C(e,["diff","--cached","--binary","--full-index"]),await C(e,["diff","--binary","--full-index"]),await C(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function Vr(e){const t=L(e),o=await u(t,["rev-parse","HEAD"]),r=await u(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await T(t);if(await u(t,["rev-parse","HEAD"])!==o||await u(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 oe(e){const t=[];let o;for(const r of(await C(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}const ft=new Set(Object.values(ce));function V(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Se(e.message)||e instanceof Error&&ft.has(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function s(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function Te(e,t){try{return await te("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function u(e,t){return String((await te("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function C(e,t){return String((await te("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function _(e,t){try{return await te("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Nr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Wt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,at as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,Ar as acceptDirectYoloSetupCheckpoint,Br as beginDirectYoloStoryCommit,Vr as captureDirectYoloCheckoutEvidence,Mr as captureDirectYoloStoryGovernance,Wr as captureEpicOriginBindingAtYoloopStart,$r as directYoloCommitIdempotencyKey,Pr as directYoloWaveQaCoverage,Vt as directYoloWaveReceiptRef,fr as fetchOriginForYoloopStart,Cr as finalizeDirectYoloStoryCheckpoint,tr as isDirectYoloWriteSetExtensionScope,_r as issueDirectYoloSetupLeaseHandoff,zr as persistDirectYoloWaveStoryCheckpoint,jr as prepareDirectYoloSetup,Tr as pushDirectYoloWaveHead,Gr as readYoloopStartEpic,Hr as recoverLegacyDirectYoloStoryCheckpoint,Or as resolveDirectYoloIntegrationAuthority,qr as runDirectYoloWaveP205,Lr as validateDirectYoloWriteSet,dr as yoloopStartGitNetworkExecOptions};
1
+ import{execFile as St}from"node:child_process";import{createHash as It,randomBytes as Ee,timingSafeEqual as xt}from"node:crypto";import{existsSync as fe}from"node:fs";import{readFile as M,realpath as je}from"node:fs/promises";import{join as U,resolve as $}from"node:path";import{promisify as bt}from"node:util";import{readRootMemoryEffectForCheckpoint as kt}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as Dt,verifyRootMemoryPhysicalWriteSet as Ae}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as Et,resolveEpicStoryIds as jt}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as _e,storyWriteSetCovers as et,validateStoryWriteScope as At}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as K,applyGitLifecycleRuntimeOverlay as Be,computeImmutableStoryQaEvidenceDigest as _t,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as ue,computeP205StoryQaEvidenceDigest as Bt,computeLegacyDirectYoloRecoveryReceiptRef as Ct,ensureRuntimeEpic as P,ensureRuntimeStory as Ce,ensureGitLifecyclePrivateChildDirectory as He,executeP205TransientAuthorities as Ht,executeP205TransientAuthority as Ot,isP226GateReasonCode as Oe,projectP205TransientExecutionEvidence as tt,publicStoryReviewArtifactFromBytes as $t,publicStoryReviewArtifactFromGit as pe,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Lt,mutateGitLifecycleRuntime as L,P205_COMPLETE_COMMAND as rt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as $e,STORY_WRITE_SET_MAX_ENTRIES as ot,storyWriteSetExtensionPaths as Nt,assertGitLifecyclePrivateFile as Z,releaseGitLifecyclePhysicalIntegrationLock as V,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as qt,verifyGitLifecyclePhysicalIntegrationLock as le,verifyAcceptedGitLifecycleStoryCheckpoint as Le}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Ne,anchoredRemoveFile as it}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as nt,GOVERNANCE_DIGEST_TRAILER as at,GOVERNANCE_REASON_CODES as he,captureStoryGovernanceSync as Pt,detectGovernanceModeSync as Tt,governanceReceiptRefs as zt,isGovernanceRepositoryPath as Gt,readGovernanceStateSourceSync as Wt,storyReviewGovernancePath as Mt,verifyStoryGovernanceBinding as Kt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ct,trailerReasonKey as ye,trailerValue as ie}from"./neocortex-trailers.js";import{StoryWorktreeManager as Vt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ft,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as st,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as T}from"./git-lifecycle-step-ids.js";const ne=bt(St),ae=3600*1e3;async function qr(e){let t,o=!1;try{const r=await me(e.projectRoot,e.storyId);if(await Pe(r.projectRoot)){if(e.expiredSetupRecovery)return a("direct-yolo-expired-setup-recovery-invalid");const S=await dt(r);return{ok:!0,value:ft(r,S,!1)}}const i=N(e.nowIso),n=Date.parse(i),f=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),p=await O(r.projectRoot,{required:!0}),s=g(p.epics[r.epicId]),d=g(s?.branch_lease),u=e.expiredSetupRecovery;if(u&&!pr(u,p.revision,d,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const w=d&&Number.isFinite(Date.parse(String(d.expiresAt)))&&Date.parse(String(d.expiresAt))>n;if(w&&d?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let h=Y(s?.origin_binding,r.executionBranch,r.originBranch),y;if(f===r.executionBranch){if(!h){if(s?.origin_binding!==void 0&&s?.origin_binding!==null||w)return a("direct-yolo-origin-binding-invalid");const S=await gr(r,c,i);if(!S.ok)return S;h=S.value.binding,y={originRef:S.value.originRef,originHeadSha:S.value.binding.originHeadSha}}}else{if(f!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(h&&h.originHeadSha!==c){if(!u||!await C(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,c]))return a("direct-yolo-origin-binding-conflict");const m=`refs/heads/${r.executionBranch}`;if(!await C(r.projectRoot,["show-ref","--verify","--quiet",m]))return a("direct-yolo-execution-branch-missing");const j=await l(r.projectRoot,["rev-parse",m]);if(!await C(r.projectRoot,["merge-base","--is-ancestor",j,c]))return a("direct-yolo-execution-branch-diverged")}if(h??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await se(r.projectRoot)).some(m=>m.branch===r.executionBranch&&$(m.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const b=await G(r.projectRoot),A=`refs/heads/${r.executionBranch}`;if(await C(r.projectRoot,["show-ref","--verify","--quiet",A])){const m=await l(r.projectRoot,["rev-parse",A]);if(m!==c){if(!await C(r.projectRoot,["merge-base","--is-ancestor",m,c]))return a("direct-yolo-execution-branch-diverged");u||await l(r.projectRoot,["update-ref",A,c,m])}u?t={checkoutBefore:b,executionRef:A,executionBranch:r.executionBranch,executionHead:m,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(u)return a("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await G(r.projectRoot)!==b)return a("direct-yolo-checkout-payload-raced")}const R=t?.originHead??await l(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return a("direct-yolo-current-branch-mismatch");if(w&&d?.ownerStoryId===e.storyId)return d.setupHeadSha!==R?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:De(r,h,String(d.expiresAt),!0)};const _=i,v=new Date(n+3600*1e3).toISOString(),D=`setup-${Ee(32).toString("hex")}`,x=u?p:await O(r.projectRoot,{required:!0});return await L(r.projectRoot,S=>{const b=P(S,r.epicId),A=g(b.branch_lease);if(u&&JSON.stringify(A)!==JSON.stringify(u.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(A&&Date.parse(String(A.expiresAt))>n&&A.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const m=Y(b.origin_binding,r.executionBranch,r.originBranch);if(b.origin_binding&&!m)throw new Error("direct-yolo-origin-binding-conflict");if(m&&JSON.stringify(m)!==JSON.stringify(h))throw new Error("direct-yolo-origin-binding-conflict");b.branch_mode="epic",b.execution_branch=r.executionBranch,b.origin_branch=r.originBranch,b.graph_revision=r.graphRevision,b.origin_binding=h,b.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:_,expiresAt:v,setupHeadSha:R}},{expectedRevision:u?.expectedRuntimeRevision??x.revision,preCommit:async()=>{if(t){if((await se(r.projectRoot)).some(b=>b.branch===r.executionBranch&&$(b.path)!==r.projectRoot)||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await G(r.projectRoot)!==t.checkoutBefore||!await C(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await l(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 l(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await l(r.projectRoot,["switch",r.executionBranch]),await G(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==R)throw new Error("direct-yolo-setup-physical-state-raced");if(y&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${y.originRef}^{commit}`]).catch(()=>"")!==y.originHeadSha||await Ze(r.projectRoot,["merge-base","--is-ancestor",y.originHeadSha,R])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:De(r,h,v,!1)}}catch(r){return o&&t&&await lr($(e.projectRoot),t).catch(()=>{}),a(W(r,"direct-yolo-setup-failed"))}}async function Pr(e){let t;try{const o=await me(e.projectRoot,e.storyId);if(await Pe(o.projectRoot))return await Jt(o,N(e.nowIso));const r=await F(e.projectRoot,e.storyId),i=N(e.nowIso),n=U(r.projectRoot,".neocortex/state.json"),f=await M(n,"utf8"),c=await G(r.projectRoot),p=await l(r.projectRoot,["rev-parse","HEAD"]),s=`refs/heads/${r.executionBranch}`,d=await O(r.projectRoot,{required:!0}),u=g(d.epics[r.epicId]),w=Y(u?.origin_binding,r.executionBranch,r.originBranch),h=g(u?.branch_lease);if(!w)return a("direct-yolo-origin-binding-invalid");if(!h||!Ve(h,e.storyId,i)||h?.sessionId!==h?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const y=await K(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(h.sessionId),idempotencyKey:String(h.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!y.ok)return a(y.reasonCode);if(t=y,p!==h.setupHeadSha||!await C(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,p])||await l(r.projectRoot,["rev-parse",s])!==p)return a("direct-yolo-setup-head-mismatch");if((await se(r.projectRoot)).some(b=>b.branch===r.executionBranch&&$(b.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const _=g(JSON.parse(f)),v=g(g(_?.stories)?.[e.storyId]),D=g(d.stories[e.storyId]);if(!v||!["backlog","ready_to_start"].includes(String(v.status))||v.steps_completed!==void 0&&(!Array.isArray(v.steps_completed)||v.steps_completed.length>0)||v.branch_name||v.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const x=D?.status==="branch-ready"&&D.last_step===T&&Array.isArray(D.steps_completed)&&D.steps_completed.length===1&&D.steps_completed[0]===T&&ee(D).sort().join(",")==="last_step,status,steps_completed";if(D&&ee(D).length>0&&!x)return a("direct-yolo-setup-story-progress-conflict");const S=async()=>{if(Date.parse(String(h.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await le(t.path,t.owner)||await M(n,"utf8")!==f||await G(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==p||!await C(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,p])||await l(r.projectRoot,["rev-parse",s])!==p)throw new Error("direct-yolo-setup-physical-state-raced")};return x?await S():await L(r.projectRoot,b=>{const A=g(b.epics[r.epicId]),m=Ce(b,e.storyId);if(JSON.stringify(A?.branch_lease)!==JSON.stringify(h)||JSON.stringify(A?.origin_binding)!==JSON.stringify(w)||A?.graph_revision!==r.graphRevision||ee(m).length>0)throw new Error("direct-yolo-setup-runtime-raced");m.status="branch-ready",m.last_step=T,m.steps_completed=[T]},{expectedRevision:d.revision,preCommit:S}),{ok:!0,value:Object.freeze({...De(r,w,String(h.expiresAt),x),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:p})}}catch(o){return a(W(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await V(t.path,t.owner).catch(()=>{})}}async function Tr(e){try{const t=await F(e.projectRoot,e.storyId),o=z(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),r=X(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return a(r.reasonCode);t.rootMemoryEffect&&Ae(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet});const i=t.governanceMode==="runtime-store"?ze(t):void 0;if((i?i.review:pe(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(z(await H(t.projectRoot,["diff","--name-only","-z"])).some(k=>o.includes(k)))return a("direct-yolo-user-overlap");const c=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return a("direct-yolo-staged-diff-empty");const p=B(c),s=B([...t.authorizedWriteSet].sort().join("\0")),d=N(e.nowIso),u=await O(t.projectRoot,{required:!0});let w=g(u.epics[t.epicId]?.branch_lease),h;if(!Ve(w,e.storyId,d)){const I=w!==void 0&&Date.parse(String(w.expiresAt))>Date.parse(d)?void 0:await ht(t.projectRoot,u,t.epicId,e.storyId,d);if(!I||!await C(t.projectRoot,["merge-base","--is-ancestor",I.setupHeadSha,"HEAD"]))return a("direct-yolo-setup-handoff-owner-invalid");h=I,w={schemaVersion:1,ownerStoryId:e.storyId,sessionId:I.sessionId,idempotencyKey:I.idempotencyKey,acquiredAt:d,expiresAt:new Date(Math.min(Date.parse(I.expiresAt),Date.parse(d)+tr)).toISOString(),setupHeadSha:I.setupHeadSha}}const y=String(w.sessionId),R=String(w.expiresAt),_=new Date(Math.min(Date.parse(R),Date.parse(d)+300*1e3)).toISOString(),v=await Q(t.projectRoot,e.storyId),D=v?.state==="issued"&&v.fromSessionId===y&&v.bundleDigest===p&&v.claimRevision===s&&Date.parse(v.expiresAt)>Date.parse(d),x=D?v.expiresAt:_,S=D?v.token:Ee(32).toString("base64url"),b=B(S),A=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:y,tokenDigest:b,bundleDigest:p,claimRevision:s,expiresAt:x}),m=B(JSON.stringify(A)),j=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:x,persistent:!1,createdAt:d});if(!j.ok)return a(j.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ye(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:y,token:S,tokenDigest:b,bundleDigest:p,claimRevision:s,grantDigest:m,expiresAt:x}),await L(t.projectRoot,k=>{const I=P(k,t.epicId);if(h){const q=g(I.branch_lease);if(q&&Date.parse(String(q.expiresAt))>Date.parse(d))throw new Error("direct-yolo-setup-handoff-owner-raced");I.branch_lease={...w}}const E=g(I.branch_lease);if(!Ve(E,e.storyId,d)||E?.sessionId!==y||E.idempotencyKey!==y)throw new Error("direct-yolo-setup-handoff-owner-raced");E.handoffGrant=A},{expectedRevision:u.revision,preCommit:async()=>{if(!await le(j.path,j.owner))throw new Error("direct-yolo-integration-lock-raced");const k=await Q(t.projectRoot,e.storyId);if(!k||k.state!=="issued"||k.grantDigest!==m||k.tokenDigest!==b)throw new Error("direct-yolo-setup-handoff-token-raced");if(h&&(await lt(t.projectRoot,e.storyId))?.sessionId!==h.sessionId)throw new Error("direct-yolo-setup-handoff-owner-raced")}}),h&&await or(t.projectRoot,e.storyId)}finally{await V(j.path,j.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:y,bundleDigest:p,claimRevision:s,grantDigest:m,expiresAt:x,reused:D,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return a(t instanceof Error&&(/^direct-yolo-/.test(t.message)||Rt.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function zr(e){try{const t=await F(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=z(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),i=X(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&Ae(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?ze(t):void 0,f=n?n.review:pe(t.projectRoot,e.storyId,":");if(f?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(z(await H(t.projectRoot,["diff","--name-only","-z"])).some(k=>r.includes(k)))return a("direct-yolo-user-overlap");const p=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!p)return a("direct-yolo-staged-diff-empty");const s=B(p),d=B([...t.authorizedWriteSet].sort().join("\0")),u=await ut(t.projectRoot,e.storyId),w=u.state==="valid"&&u.plan.epicId===t.epicId&&u.plan.executionBranch===t.executionBranch&&u.plan.preparedBase===o&&u.plan.bundleDigest===s&&u.plan.claimRevision===d?u.plan:void 0,h=w?.graphRevision??t.graphRevision,y=Me({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,graphRevision:h,claimRevision:d}),R=N(e.nowIso),_={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:h,preparedBase:o,bundleDigest:s,claimRevision:d,idempotencyKey:y,issuedAt:w?.issuedAt??R};let v=e.setupLeaseHandoff??await ir(t.projectRoot,e.storyId,s,d,R);const D=await O(t.projectRoot,{required:!0}),x=g(D.epics[t.epicId]?.branch_lease),S=x?.ownerStoryId===e.storyId&&x.sessionId===y&&x.idempotencyKey===y&&typeof x.expiresAt=="string"&&Date.parse(x.expiresAt)>Date.parse(R)?x:void 0;if(S&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const b=g(S?.handoffConsumption);if(b){const k=await Q(t.projectRoot,e.storyId);if(!k||!["consuming","consumed"].includes(k.state)||k.fromSessionId!==b.fromSessionId||k.tokenDigest!==b.tokenDigest||k.bundleDigest!==s||k.claimRevision!==d||b.bundleDigest!==s||b.claimRevision!==d||k.consumedBySessionId!==y||b.consumedBySessionId!==y)return a("direct-yolo-setup-handoff-consume-invalid");if(k.state==="consuming"){if(!k.token||B(k.token)!==k.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");v={sessionId:k.fromSessionId,token:k.token}}}const A=S?String(S.expiresAt):new Date(Date.parse(R)+ae).toISOString(),m=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:y,idempotencyKey:y,expiresAt:A,persistent:!0,createdAt:S&&typeof S.acquiredAt=="string"?S.acquiredAt:R});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{v&&e.setupLeaseHandoff===void 0&&(await nr(t.projectRoot,e.storyId,v.sessionId,v.token,y,R),await e.setupHandoffFault?.("after-consuming-persisted")),await L(t.projectRoot,k=>{const I=P(k,t.epicId),E=g(I.branch_lease),q=E&&Date.parse(String(E.expiresAt))>Date.parse(R),oe=E?.ownerStoryId===e.storyId&&E.sessionId===y&&E.idempotencyKey===y,de=E?.ownerStoryId===e.storyId&&E.sessionId===E.idempotencyKey&&typeof E.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(E.idempotencyKey),J=q&&de&&cr({current:E,handoff:v,storyId:e.storyId,bundleDigest:s,claimRevision:d,nowIso:R});if(v&&q&&!oe&&!J)throw new Error("direct-yolo-setup-handoff-invalid");if(q&&!oe&&!J)throw new Error("direct-yolo-writer-active");const Qe=J?g(E?.handoffGrant):void 0,Xe=Qe?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(E?.sessionId),tokenDigest:String(Qe.tokenDigest),bundleDigest:s,claimRevision:d,consumedBySessionId:y,consumedAt:R}:void 0;I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.graph_revision=t.graphRevision,I.branch_lease=q&&oe?E:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:y,idempotencyKey:y,acquiredAt:R,expiresAt:A,...Xe?{handoffConsumption:Xe}:{}}},{expectedRevision:D.revision,preCommit:async()=>{if(!await le(m.path,m.owner))throw new Error("direct-yolo-integration-lock-raced");await Xt(t.projectRoot,_)}})}catch(k){throw await V(m.path,m.owner).catch(()=>{}),k}v&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await ar(t.projectRoot,t.epicId,e.storyId,v.sessionId,v.token,s,d,y,R));const j=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${s}`,`Neocortex-Review-Artifact-Digest: ${f.digest}`,`Neocortex-Graph-Revision: ${h}`,`Neocortex-Claim-Revision: ${d}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Dt(t.rootMemoryEffect)}`]:[],...n?[`${at}: ${n.receipt.governanceDigest}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,reviewArtifactDigest:f.digest,graphRevision:h,claimRevision:d,idempotencyKey:y,changedPaths:Object.freeze(r),trailers:j,...n?{governance:n.receipt}:{}})}}catch(t){return a(W(t,"direct-yolo-begin-failed"))}}async function Gr(e){let t,o,r;try{const i=await F(e.projectRoot,e.storyId);t=i;const n=e.preFastForwardAuthorizedWriteSet;if(n!==void 0&&!qe(n))return a("direct-yolo-write-set-invalid");const f=n??i.authorizedWriteSet,c=await l(i.projectRoot,["rev-parse","HEAD"]);let p=await O(i.projectRoot,{required:!0});const s=g(p.stories[e.storyId]?.checkpoint);if(s){const j=typeof s.headSha=="string"?s.headSha:"",k=typeof s.graphRevision=="string"?s.graphRevision:"",I=/^[a-f0-9]{40,64}$/.test(j)?z(await H(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",j])):[],E=X(I,f,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(j)&&await C(i.projectRoot,["merge-base","--is-ancestor",j,c]))||!/^[a-f0-9]{64}$/.test(k)||!E.ok)return a("direct-yolo-replay-invalid");const oe=await Ie(e,i.projectRoot,c,k);if(!await Le(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,oe.transientAuthority,f))return a("direct-yolo-replay-invalid");if(!await xe(i.projectRoot,i.executionBranch,c,I))return a("direct-yolo-replay-head-raced");if(e.push&&!await We(i.projectRoot,e.remote??"origin",i.executionBranch,j))return a("direct-yolo-remote-head-mismatch");const de=Array.isArray(s.receiptRefs)?s.receiptRefs.find(J=>typeof J=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(J)):void 0;return de&&typeof s.idempotencyKey=="string"&&await qt(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:de.slice(20)}),await ce(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const d=c,u=await ge(i,e.storyId,d,n?{claimWriteSet:n}:{});if(!u.ok)return a(u.reasonCode);const{baseSha:w,changedPaths:h,bundleDigest:y,graphRevision:R,claimRevision:_,idempotencyKey:v,governance:D}=u.value,x=g(p.epics[i.epicId]?.branch_lease),S=N(e.nowIso),b=x?.ownerStoryId===e.storyId&&x.idempotencyKey===v&&x.sessionId===v&&Date.parse(String(x.expiresAt))>Date.now()?x:void 0;if(x&&Date.parse(String(x.expiresAt))>Date.now()&&!b)return a("direct-yolo-writer-active");const A=b??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:v,idempotencyKey:v,acquiredAt:S,expiresAt:new Date(Date.parse(S)+ae).toISOString()},m=await K(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:v,idempotencyKey:v,expiresAt:String(A.expiresAt),persistent:!0,createdAt:String(A.acquiredAt)});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,b||(p=(await L(i.projectRoot,k=>{const I=P(k,i.epicId),E=g(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(S))throw new Error("direct-yolo-writer-active");if(I.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");I.branch_lease=A},{expectedRevision:p.revision})).document),o=A;{const j=await Ie(e,i.projectRoot,d,R);if(!await xe(i.projectRoot,i.executionBranch,d,h))return a("direct-yolo-head-raced");if(e.push){const E=re(e.remote??"origin");if(await l(i.projectRoot,["push",E,i.executionBranch]),!await Je(i.projectRoot,E,i.executionBranch,d))return a("direct-yolo-remote-head-mismatch")}const k=await we({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:w,headSha:d,bundleDigest:y,graphRevision:R,claimRevision:_,idempotencyKey:v,qaExecution:j,physicalLockOwnerDigest:ue(m.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...D?{governance:D}:{}});return await e.beforeCheckpointPersist?.(),await ve({projectRoot:i.projectRoot,checkpoint:k,remote:e.push?e.remote??"origin":void 0,expectedRevision:p.revision,expectedLease:A,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:R,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:j.transientAuthority,authorizedWriteSet:f})?(await ce(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:k}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(W(i,"direct-yolo-finalize-failed"))}finally{r&&await V(r.path,r.owner).catch(()=>{}),t&&o?await Se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await dr(t,e.storyId).catch(()=>{})}}function qe(e){return Array.isArray(e)&&e.length>0&&e.length<=ot&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}async function Wr(e,t,o,r={}){try{return/^[a-f0-9]{40,64}$/.test(o)?await ge(e,t,o,{claimWriteSet:e.authorizedWriteSet,...r.expectedGraphRevision!==void 0?{expectedGraphRevision:r.expectedGraphRevision}:{}}):a("direct-yolo-recovery-commit-invalid")}catch(i){return a(W(i,"direct-yolo-commit-verification-failed"))}}async function ge(e,t,o,r={}){if(r.claimWriteSet!==void 0&&!qe(r.claimWriteSet))return a("direct-yolo-write-set-invalid");if(r.expectedGraphRevision!==void 0&&!/^[a-f0-9]{64}$/.test(r.expectedGraphRevision))return a("direct-yolo-graph-revision-invalid");const i=r.claimWriteSet??e.authorizedWriteSet,n=await l(e.projectRoot,["rev-parse",`${o}^`]),f=await H(e.projectRoot,["show","--no-patch","--format=%B",o]),c=z(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),p=X(c,i,t,e.rootMemoryEffect,e.governanceMode);if(!p.ok)return a(p.reasonCode);e.rootMemoryEffect&&Ae(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:n,headRef:o,childPaths:i});const s=B([...i].sort().join("\0")),d=await ut(e.projectRoot,t);if(d.state==="invalid")return a("direct-yolo-commit-plan-invalid");const u=d.state==="valid"?d.plan:void 0;if(u&&(u.epicId!==e.epicId||u.executionBranch!==e.executionBranch))return a("direct-yolo-commit-plan-invalid");if(u&&u.claimRevision!==s)return a("direct-yolo-commit-plan-claim-changed");if(u&&u.preparedBase!==n)return a("direct-yolo-commit-plan-base-mismatch");const w=ct(f,nt);if(!w.ok)return a(`direct-yolo-trailer-duplicate:${w.key}`);const h=w.values;if(r.expectedGraphRevision!==void 0&&u&&u.graphRevision!==r.expectedGraphRevision)return a(`direct-yolo-trailer-mismatch:${ye("Neocortex-Graph-Revision")}`);const y=r.expectedGraphRevision??u?.graphRevision??e.graphRevision,R=s,_=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",n],["Neocortex-Bundle-Digest",u?.bundleDigest??""],["Neocortex-Graph-Revision",y],["Neocortex-Claim-Revision",R]];for(const[j,k]of _){const I=ie(h,j);if(I===void 0)return a(`direct-yolo-trailer-missing:${ye(j)}`);if(j==="Neocortex-Bundle-Digest"&&!u){if(!/^[a-f0-9]{64}$/.test(I))return a(`direct-yolo-trailer-mismatch:${ye(j)}`);continue}if(I!==k)return a(`direct-yolo-trailer-mismatch:${ye(j)}`)}const v=ie(h,"Neocortex-Bundle-Digest"),D=ie(h,at);if(e.governanceMode!=="runtime-store"&&D!==void 0)return a(he.MISMATCH);const x=e.governanceMode==="runtime-store"?Ge({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},D):void 0,S=x?x.review:pe(e.projectRoot,t,o);if(S?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const b=ie(h,"Neocortex-Review-Artifact-Digest");if(b!==void 0&&b!==S.digest)return a("direct-yolo-review-artifact-digest-mismatch");const A=B(await H(e.projectRoot,["diff","--binary","--full-index",`${n}..${o}`]));if(v!==A)return a("direct-yolo-bundle-digest-mismatch");const m=Me({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:n,bundleDigest:v,graphRevision:y,claimRevision:R});return u&&u.idempotencyKey!==m?a("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:n,changedPaths:c,bundleDigest:v,graphRevision:y,claimRevision:R,idempotencyKey:m,...x?{governance:x.receipt}:{}}}}async function Mr(e){try{const t=await F(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return a("direct-yolo-recovery-commit-invalid");const o=await l(t.projectRoot,["rev-parse",e.commitSha]);if(Lt[e.storyId]!==o)return await Yt(e,t,o);if(await l(t.projectRoot,["rev-parse","HEAD"])!==o)return a("direct-yolo-recovery-head-mismatch");await l(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await l(t.projectRoot,["rev-parse",`${o}^`]),i=await H(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=z(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!X(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const c=B(i),p=B([...n].sort().join("\0")),s=B(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),d=N(e.nowIso),u=new Date(Date.parse(d)+ae).toISOString(),w=await O(t.projectRoot,{required:!0}),h=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:u,persistent:!0,createdAt:d});if(!h.ok)return a(h.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const y={schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:d,expiresAt:u};let R=!1;try{const _=await L(t.projectRoot,A=>{const m=P(A,t.epicId),j=g(m.branch_lease);if(j&&Date.parse(String(j.expiresAt))>Date.parse(d)&&!Re(j,y))throw new Error("direct-yolo-recovery-writer-active");if(m.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");m.branch_mode="epic",m.execution_branch=t.executionBranch,m.origin_branch=t.originBranch,m.branch_lease=y},{expectedRevision:w.revision});R=!0;const v=await Ie(e,t.projectRoot,o,t.graphRevision);if(!await xe(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const A=re(e.remote??"origin"),m=(await l(t.projectRoot,["ls-remote","--heads",A,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!m||!await C(t.projectRoot,["merge-base","--is-ancestor",o,m]))return a("direct-yolo-recovery-remote-proof-missing")}const D=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:p,idempotencyKey:s,qaExecution:v,physicalLockOwnerDigest:ue(h.owner),nowIso:d,legacyReceiptRef:void 0}),x=await Ct(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!x)return a("direct-yolo-recovery-evidence-invalid");const S=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,x])});return await ve({projectRoot:t.projectRoot,checkpoint:S,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:_.document.revision,expectedLease:y,expectedGraphRevision:t.graphRevision,physicalLockPath:h.path,physicalLockOwner:h.owner,transientAuthority:v.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:S}:a("direct-yolo-recovery-persist-failed")}finally{await V(h.path,h.owner).catch(()=>{}),R&&await Se(t.projectRoot,t.epicId,y).catch(()=>{})}}catch(t){return a(W(t,"direct-yolo-recovery-failed"))}}async function Yt(e,t,o){const r=await H(t.projectRoot,["show","--no-patch","--format=%B",o]),i=ct(r,nt);if(!i.ok||ie(i.values,"Neocortex-Story")!==e.storyId)return a("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o||!await C(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]))return a("direct-yolo-recovery-head-mismatch");const n=await ge(t,e.storyId,o);if(!n.ok)return a(n.reasonCode);const{baseSha:f,changedPaths:c,bundleDigest:p,graphRevision:s,claimRevision:d,idempotencyKey:u,governance:w}=n.value,h=re(e.remote??"origin");let y=!1;try{y=await We(t.projectRoot,h,t.executionBranch,o)}catch{y=!1}if(!y)return a("direct-yolo-recovery-remote-proof-missing");const R=N(e.nowIso),_=new Date(Date.parse(R)+ae).toISOString(),v=await O(t.projectRoot,{required:!0});if(g(v.stories[e.storyId]?.checkpoint))return a("direct-yolo-checkpoint-conflict");const D=await K(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:_,persistent:!0,createdAt:R});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const x={schemaVersion:1,ownerStoryId:e.storyId,sessionId:u,idempotencyKey:u,acquiredAt:R,expiresAt:_};let S=!1;try{const b=await L(t.projectRoot,k=>{const I=P(k,t.epicId),E=g(I.branch_lease);if(E&&Date.parse(String(E.expiresAt))>Date.parse(R)&&!Re(E,x))throw new Error("direct-yolo-recovery-writer-active");if(I.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");I.branch_mode="epic",I.execution_branch=t.executionBranch,I.origin_branch=t.originBranch,I.branch_lease=x},{expectedRevision:v.revision});S=!0;const A=await Ie(e,t.projectRoot,o,s);if(!await xe(t.projectRoot,t.executionBranch,o,c))return a("direct-yolo-recovery-head-raced");const m=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:f,headSha:o,bundleDigest:p,graphRevision:s,claimRevision:d,idempotencyKey:u,qaExecution:A,physicalLockOwnerDigest:ue(D.owner),nowIso:R,legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,...w?{governance:w}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:m,remote:h,remotePolicy:"ancestor-recovery",expectedRevision:b.document.revision,expectedLease:x,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:s,physicalLockPath:D.path,physicalLockOwner:D.owner,transientAuthority:A.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:m}):a("direct-yolo-recovery-persist-failed")}finally{await V(D.path,D.owner).catch(()=>{}),S&&await Se(t.projectRoot,t.epicId,x).catch(()=>{})}}async function Pe(e){const t=await je(await l(e,["rev-parse","--absolute-git-dir"])),o=await je(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function dt(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(u=>u.storyId===e.storyId&&u.epicId===e.epicId&&u.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 je(await l(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const f=await new Vt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!f.ok||f.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=Y(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const p=r.syncedSha??r.baseSha,s=await l(e.projectRoot,["rev-parse","HEAD"]),d=`refs/heads/${e.executionBranch}`;if(s!==p||!await C(e.projectRoot,["merge-base","--is-ancestor",p,d])||!await C(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,p]))throw new Error("direct-yolo-worktree-base-divergent");if(f.value.clean!==!0||(await H(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:p,headSha:s,expiresAt:r.expiresAt,binding:c}}function ft(e,t,o){return Object.freeze({...De(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Jt(e,t){const o=await dt(e),r=Te(e.projectRoot),i=g(JSON.parse(r)),n=g(g(i?.stories)?.[e.storyId]),f=await O(e.projectRoot,{required:!0}),c=g(f.stories[e.storyId]);if(!n||!["backlog","ready_to_start"].includes(String(n.status))||n.steps_completed!==void 0&&(!Array.isArray(n.steps_completed)||n.steps_completed.length>0)||n.branch_name||n.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const p=c?.status==="branch-ready"&&c.last_step===T&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===T&&ee(c).sort().join(",")==="last_step,status,steps_completed";if(c&&ee(c).length>0&&!p)return a("direct-yolo-setup-story-progress-conflict");p||await L(e.projectRoot,u=>{const w=Ce(u,e.storyId);if(ee(w).length>0)throw new Error("direct-yolo-setup-runtime-raced");w.status="branch-ready",w.last_step=T,w.steps_completed=[T]},{expectedRevision:f.revision,preCommit:async()=>{if(Te(e.projectRoot)!==r||await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.temporaryBranch||await l(e.projectRoot,["rev-parse","HEAD"])!==o.headSha||(await H(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}});const s=await O(e.projectRoot,{required:!0}),d=await ht(e.projectRoot,s,e.epicId,e.storyId,t);if(d?.leaseId!==o.leaseId||d.setupHeadSha!==o.headSha){const u=`setup-${Ee(32).toString("hex")}`;await rr(e.projectRoot,{schemaVersion:1,kind:pt,epicId:e.epicId,ownerStoryId:e.storyId,sessionId:u,idempotencyKey:u,leaseId:o.leaseId,acquiredAt:t,expiresAt:o.expiresAt,setupHeadSha:o.headSha})}return{ok:!0,value:Object.freeze({...ft(e,o,p),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:o.headSha})}}async function Kr(e,t){const o=await F(e,t),r=await O(o.projectRoot,{required:!0}),i=Y(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Vr(e,t,o,r,i="tracked"){return X(e,t,o,r,i)}function Fr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Yr=ae,Ut="p205-wave:";function Jr(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=B(["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 Zt(e){return`${Ut}${e.waveHeadSha}:${e.waveDigest}`}async function Ur(e){let t;try{t=await Ht(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:Oe(r)?r:"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/^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:Oe(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Zr(e,t,o,r){const i=re(t);return await l(e,["push",i,o]),Je(e,i,o,r)}async function Qr(e){try{const t=await F(e.projectRoot,e.storyId);if(e.authorizedWriteSet!==void 0&&!qe(e.authorizedWriteSet))return a("direct-yolo-write-set-invalid");const o=e.authorizedWriteSet??t.authorizedWriteSet,r=e.coverage.waveHeadSha,i=e.coverage.waveStoryIds.indexOf(e.storyId);if(i<0||e.coverage.waveCommitShas[i]!==e.headSha)return a("direct-yolo-wave-coverage-invalid");if(await l(t.projectRoot,["rev-parse","HEAD"])!==r||await l(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==r||!await C(t.projectRoot,["merge-base","--is-ancestor",e.headSha,r]))return a("direct-yolo-wave-head-raced");const n=await O(t.projectRoot,{required:!0}),f=g(n.stories[e.storyId]?.checkpoint);if(f){if(f.headSha!==e.headSha)return a("direct-yolo-checkpoint-conflict");const x=e.authorities.get(String(f.graphRevision));return await Le(t.projectRoot,f,e.storyId,t.epicId,t.executionBranch,x??null,o)?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:f}):a("direct-yolo-replay-invalid")}const c=await ge(t,e.storyId,e.headSha,{...e.authorizedWriteSet!==void 0?{claimWriteSet:e.authorizedWriteSet}:{},...e.expectedGraphRevision!==void 0?{expectedGraphRevision:e.expectedGraphRevision}:{}});if(!c.ok)return a(c.reasonCode);const{baseSha:p,bundleDigest:s,graphRevision:d,claimRevision:u,idempotencyKey:w,governance:h}=c.value,y=i===0?void 0:e.coverage.waveCommitShas[i-1];if(y!==void 0&&p!==y)return a("direct-yolo-wave-chain-invalid");const R=e.authorities.get(d),_=tt(R);if(!R||!_||_.executionHeadSha!==r||_.graphRevision!==d)return a("direct-yolo-wave-qa-unbound");const v=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:p,headSha:e.headSha,bundleDigest:s,graphRevision:d,claimRevision:u,idempotencyKey:w,qaExecution:{contract:"P205-CI-02",command:rt,manifestDigest:_.manifestDigest,gateIds:_.gateIds,resultDigest:_.resultDigest,transientAuthority:R},physicalLockOwnerDigest:ue(e.physicalLock.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Zt(e.coverage)],...h?{governance:h}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:v,remote:e.remote,expectedRevision:n.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:d,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:R,authorizedWriteSet:o,expectedHeadSha:r,keepLease:!0})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:v}):a("direct-yolo-checkpoint-persist-failed")}catch(t){return a(W(t,"direct-yolo-wave-persist-failed"))}}async function me(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=$(e),r=g(JSON.parse(Te(o))),i=await O(o,{required:!0}),n=Be(r,i),f=Tt({projectRoot:o,storyId:t});if(!f.ok)throw new Error(f.reasonCode);const c=f.mode,p=g(n.stories),s=g(n.epics),d=g(p?.[t]),u=String(d?.epic_id??t.split(".")[0]),w=g(s?.[u]),h=String(w?.execution_branch??""),y=String(w?.origin_branch??""),R=String(w?.graph_revision??""),_=Array.isArray(d?.files_to_modify)?d.files_to_modify:[],v=Nt(d).filter(ur),D=[..._,...v],x=D.length>0?_e(t,D):void 0,S=x?.ok?x.scopes:[];if(!d)throw new Error("direct-yolo-story-state-missing");if(v.length>0&&S.length>ot)throw new Error("direct-yolo-write-set-too-large");if(w?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!te(h)||!await C(o,["check-ref-format","--branch",h]))throw new Error("direct-yolo-execution-branch-invalid");if(!te(y)||!await C(o,["check-ref-format","--branch",y]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(R))throw new Error("direct-yolo-graph-revision-invalid");const b=await kt({projectRoot:o,storyId:t,graphRevision:R,executionBranch:h,childPaths:S});return{projectRoot:o,storyId:t,story:d,epicId:u,executionBranch:h,originBranch:y,graphRevision:R,authorizedWriteSet:S,rootMemoryEffect:b,governanceMode:c}}async function Xr(e){try{const t=await me(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?a("governance-capture-not-applicable"):await Pe(t.projectRoot)?a("governance-capture-root-required"):{ok:!0,value:ze(t).receipt}}catch(t){return a(W(t,"governance-capture-failed"))}}function Te(e){const t=Wt(e);if(!t.ok)throw new Error(t.reasonCode);if(!t.value)throw new Error("direct-yolo-story-state-missing");return t.value.toString("utf8")}function ze(e){const t=Pt(e);if(!t.ok)throw new Error(t.reasonCode);return Ge(e,t.value.governanceDigest)}function Ge(e,t){const o=Kt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Mt(e.storyId));if(!r)throw new Error(he.MISMATCH);return{receipt:o.value.receipt,review:$t(e.storyId,r)}}async function F(e,t){const o=await me(e,t);if(await l(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function we(e){const t=e.nowIso,o=await H(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=z(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=_t({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Bt({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),f=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:f}),p=e.governance?Ge(e,e.governance.governanceDigest).review:pe(e.projectRoot,e.storyId,e.headSha);if(p?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const s=B(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,f,B(o),[...r].sort().join(","),p.digest].join("\0")),d=`story-review:${s}`,u=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:s,reviewArtifactDigest:p.digest,qaReceiptRef:f,verdict:"approved",reviewedAt:t,receiptRef:d}),w=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,f,d,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[],...e.governance?zt(e.governance):[]];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(w),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:u,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ve(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await L(t,n=>{const f=P(n,o.epicId);if(e.expectedLease){const d=g(f.branch_lease);if(!Re(d,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(d?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(f.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=Ce(n,o.storyId),p=g(c.checkpoint);if(p&&p.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=st;const s=Array.isArray(c.steps_completed)?c.steps_completed.filter(d=>typeof d=="string"):[];c.steps_completed=[...new Set([...s,Ft,st])],e.keepLease||(f.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await l(t,["rev-parse","HEAD"])!==n||await l(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await C(t,["merge-base","--is-ancestor",o.headSha,n]))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 le(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await We(t,r,o.branch,o.headSha):await Je(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function We(e,t,o,r){const i=re(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await C(e,["merge-base","--is-ancestor",r,n]))}function Me(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Qt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Ke(e,t){const o=await $e(e),r=await He(o,"commit-plans"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:U(r,i)}}async function Xt(e,t){const o=await Ke(e,t.storyId);await Ne(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
+ `),await Z(o.path,o.parent)}async function ut(e,t){let o;try{o=await Ke(e,t)}catch{return{state:"invalid"}}try{if(!fe(o.path))return{state:"absent"};await Z(o.path,o.parent);const r=await M(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=g(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...Qt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!te(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(f=>typeof f=="string"&&/^[a-f0-9]{64}$/.test(f))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const n=i;return n.idempotencyKey!==Me({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ce(e,t){const o=await Ke(e,t);fe(o.path)&&await it(o.parent,o.name)}function Ve(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))}const pt="direct-yolo-worktree-setup-reservation",er=["schemaVersion","kind","epicId","ownerStoryId","sessionId","idempotencyKey","leaseId","acquiredAt","expiresAt","setupHeadSha"],tr=3600*1e3;async function Fe(e,t){const o=await $e(e),r=await He(o,"setup-reservations"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:U(r,i)}}async function rr(e,t){const o=await Fe(e,t.ownerStoryId);await Ne(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
+ `),await Z(o.path,o.parent)}async function lt(e,t){try{const o=await Fe(e,t);if(!fe(o.path))return;await Z(o.path,o.parent);const r=JSON.parse(await M(o.path,"utf8"));return Object.keys(r).sort().join("\0")!==[...er].sort().join("\0")||r.schemaVersion!==1||r.kind!==pt||r.ownerStoryId!==t||!be(r.epicId)||!be(r.leaseId)||typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId||typeof r.setupHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.setupHeadSha)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!(Date.parse(String(r.expiresAt))>Date.parse(String(r.acquiredAt)))?void 0:r}catch{return}}async function or(e,t){const o=await Fe(e,t);fe(o.path)&&await it(o.parent,o.name)}async function ht(e,t,o,r,i){const n=await lt(e,r),f=Date.parse(i);if(!n||n.epicId!==o||!(Date.parse(n.expiresAt)>f))return;const c=Object.values(t.storyWorktrees?.entries??{}).find(s=>s.leaseId===n.leaseId);if(!c||c.state!=="active"||c.storyId!==r||c.epicId!==o||!(Date.parse(c.expiresAt)>f))return;const p=g(t.stories[r]);if(!(p?.checkpoint||p?.last_step!==T))return n}async function yt(e,t){const o=await $e(e),r=await He(o,"handoffs"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:U(r,i)}}async function Ye(e,t){const o=await yt(e,t.storyId);await Ne(o.parent,o.name,`${JSON.stringify(t,null,2)}
4
+ `),await Z(o.path,o.parent)}async function Q(e,t){try{const o=await yt(e,t);await Z(o.path,o.parent);const r=JSON.parse(await M(o.path,"utf8")),i=r.state==="issued"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt"]:r.state==="consuming"?["schemaVersion","kind","state","storyId","fromSessionId","token","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumeStartedAt"]:["schemaVersion","kind","state","storyId","fromSessionId","tokenDigest","bundleDigest","claimRevision","grantDigest","expiresAt","consumedBySessionId","consumedAt"];return Object.keys(r).sort().join("\0")!==[...i].sort().join("\0")||r.schemaVersion!==1||r.kind!=="direct-yolo-setup-handoff-token"||r.state!=="issued"&&r.state!=="consuming"&&r.state!=="consumed"||r.storyId!==t||typeof r.fromSessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.fromSessionId)||![r.tokenDigest,r.bundleDigest,r.claimRevision,r.grantDigest].every(n=>typeof n=="string"&&/^[a-f0-9]{64}$/.test(n))||typeof r.expiresAt!="string"||!Number.isFinite(Date.parse(r.expiresAt))||(r.state==="issued"||r.state==="consuming")&&(typeof r.token!="string"||!/^[A-Za-z0-9_-]{32,256}$/.test(r.token))||r.state==="consuming"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumeStartedAt!="string"||!Number.isFinite(Date.parse(r.consumeStartedAt)))||r.state==="consumed"&&(typeof r.consumedBySessionId!="string"||!/^[a-f0-9]{64}$/.test(r.consumedBySessionId)||typeof r.consumedAt!="string"||!Number.isFinite(Date.parse(r.consumedAt)))?void 0:r}catch{return}}async function ir(e,t,o,r,i){const n=await Q(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||B(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function nr(e,t,o,r,i,n){const f=await Q(e,t);if(!f||f.state==="consumed"||f.fromSessionId!==o||f.token!==r||f.tokenDigest!==B(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(f.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await Ye(e,{...f,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function ar(e,t,o,r,i,n,f,c,p){const s=await Q(e,o);if(s?.state==="consumed"&&s.fromSessionId===r&&s.consumedBySessionId===c)return;const d=await O(e,{required:!0}),u=g(d.epics[t]?.branch_lease),w=g(u?.handoffConsumption);if(!s||s.state!=="consuming"||s.fromSessionId!==r||s.token!==i||s.tokenDigest!==B(i)||s.bundleDigest!==n||s.claimRevision!==f||s.consumedBySessionId!==c||u?.ownerStoryId!==o||u.sessionId!==c||w?.kind!=="direct-yolo-setup-handoff-consumption"||w.state!=="consumed"||w.fromSessionId!==r||w.tokenDigest!==s.tokenDigest||w.bundleDigest!==n||w.claimRevision!==f||w.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ye(e,{schemaVersion:1,kind:s.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:s.tokenDigest,bundleDigest:s.bundleDigest,claimRevision:s.claimRevision,grantDigest:s.grantDigest,expiresAt:s.expiresAt,consumedBySessionId:c,consumedAt:p})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function cr(e){const t=g(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?B(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)&&sr(t.tokenDigest,r))}function sr(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&xt(o,r)}function Re(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Se(e,t,o){await L(e,r=>{const i=P(r,t),n=g(i.branch_lease);Re(n,o)&&(i.branch_lease=null)})}async function dr(e,t){const o=await O(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!be(r.sessionId)||!be(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await K(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 V(i.path,i.owner)&&await Se(e.projectRoot,e.epicId,r)}async function Ie(e,t,o,r){const i=await Ot(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=tt(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:rt,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function xe(e,t,o,r){return await l(e,["rev-parse","HEAD"])!==o||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await C(e,["diff","--cached","--quiet"])?!1:C(e,["diff","--quiet","HEAD","--",...r])}async function Je(e,t,o,r){const i=re(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function X(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!Ue(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return fr(e,t,o,r);const n=t.length>0?_e(o,t):void 0;return n?.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(c=>e.includes(c))?r&&(r.storyId!==o||r.childClaimRevision!==B([...n.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(c=>!et(n.scopes,c)&&!r?.files.some(p=>p.path===c))?{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 fr(e,t,o,r){if(e.some(Gt))return{ok:!1,reasonCode:he.WRITE_SET_FORBIDDEN};const i=t.length>0?_e(o,t):void 0;if(!i?.ok)return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const n=`docs/stories/${o}.story.md`;return!e.includes(n)||!e.some(f=>f!==n)?{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:r&&(r.storyId!==o||r.childClaimRevision!==B([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(f=>!et(i.scopes,f)&&!r?.files.some(c=>c.path===f))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function ee(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function ur(e){return typeof e!="string"||e.length>512||!Ue(e)||!At(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Ue(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function be(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function te(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function re(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function B(e){return It("sha256").update(e).digest("hex")}function z(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function pr(e,t,o,r,i){const n=g(e.expectedLease),f=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof f=="string"&&/^setup-[a-f0-9]{64}$/.test(f)&&n.idempotencyKey===f&&Number.isFinite(c)&&c<=i}async function lr(e,t){let o=await l(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await l(e,["rev-parse","HEAD"])!==t.originHead||await G(e)!==t.checkoutBefore)return;await l(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await l(e,["rev-parse","HEAD"])!==t.originHead||await G(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await C(e,["show-ref","--verify","--quiet",t.executionRef]))return;await l(e,["rev-parse",t.executionRef])===t.originHead&&await l(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const hr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],yr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function Y(e,t,o){const r=g(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!==hr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==yr.join("\0")?void 0:r}async function gr(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await C(e.projectRoot,["show-ref","--verify","--quiet",r]))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await l(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return a("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await se(e.projectRoot)).some(p=>p.branch===e.executionBranch&&$(p.path)!==e.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const f=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",f]).catch(()=>"")!==t)return a("direct-yolo-setup-physical-state-raced");const c=await Ze(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?a("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?a("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}}}}const gt=3e4,mr=3,wr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class ke extends Error{}function vr(e,t=gt){return{timeout:t,killSignal:"SIGKILL",env:{...e,GIT_TERMINAL_PROMPT:"0",GCM_INTERACTIVE:"never",GIT_HTTP_LOW_SPEED_LIMIT:"1000",GIT_HTTP_LOW_SPEED_TIME:"30",...e.GIT_SSH_COMMAND?{}:{GIT_SSH_COMMAND:wr}}}}async function Rr(e){if(!te(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ne("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:$(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...vr(process.env,e.fetchTimeoutMs??gt)}),{ok:!0}}catch(t){const o=String(t.stderr??"");return{ok:!1,reasonCode:/non-fast-forward|\[rejected\]/.test(o)?"origin-binding-start-fetch-non-fast-forward":"origin-binding-start-fetch-unavailable"}}}const Sr=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function eo(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=$(e),i=g(JSON.parse(await M(U(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),f=Be(i,n),c=g(g(f.epics)?.[t]);if(!c)return o;const p=wt(f,t,c),s=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,d=await mt(r,c,i),u=g(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:p,terminal:Sr.has(String(c.status??"").toLowerCase()),bound:!!Y(u,s,d),executionBranch:s,originBranch:d})}catch{return o}}async function mt(e,t,o){if(typeof t.origin_branch=="string"&&t.origin_branch.length>0)return t.origin_branch;const r=g(o.config)?.default_branch;if(r!=null&&String(r).length>0)return String(r);const i=await l(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]).catch(()=>"");if(i.startsWith("origin/")&&i.length>7)return i.slice(7);const n=[];for(const f of["main","master"])await C(e,["rev-parse","--verify","--quiet",`refs/heads/${f}^{commit}`])&&await C(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${f}^{commit}`])&&n.push(f);return n.length===1?n[0]:""}function wt(e,t,o){if(o.branch_mode==="epic")return"recorded-epic";if(o.branch_mode!==void 0&&o.branch_mode!==null)return"not-epic";const r=g(e.stories)??{},n=jt(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const p=g(r[c]);return p?[{...p,id:c}]:[]}),f=Et({...o,id:t},n);return f.mode==="epic"&&(f.source==="new-epic-default"||f.source==="epic-boundary")?"resolved-epic":"not-epic"}function vt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function to(e){const t=N(e.nowIso),o=Date.parse(t),r=(c,p={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...p,outcome:"refused",reasonCode:c,executionRefCreated:!1,capturedAt:t});if(!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e.epicId))return r("origin-binding-start-target-ambiguous");const i=$(e.projectRoot);let n=e.originFetch,f="origin-binding-start-raced";for(let c=0;c<mr;c+=1){let p,s={};try{const d=g(JSON.parse(await M(U(i,".neocortex/state.json"),"utf8")));if(!d)return r("origin-binding-start-state-invalid");const u=await O(i),w=Be(d,u),h=g(g(w.epics)?.[e.epicId]);if(!h)return r("origin-binding-start-target-ambiguous");if(wt(w,e.epicId,h)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const y=typeof h.execution_branch=="string"&&h.execution_branch.length>0?h.execution_branch:`epic/${e.epicId}`,R=await mt(i,h,d);if(s={executionBranch:y,originBranch:R},!te(y)||!te(R)||y===R||!await C(i,["check-ref-format","--branch",y])||!await C(i,["check-ref-format","--branch",R]))return r("origin-binding-start-branch-invalid",s);const _=g(u.epics[e.epicId]),v=_?.origin_binding??h.origin_binding;if(v!=null){const I=Y(v,y,R);return I?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:I.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",s)}if(vt(g(_?.branch_lease??h.branch_lease),o))return r("origin-binding-start-lease-inconsistent",s);if(n??=await Rr({projectRoot:i,originBranch:R,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,s);const D=`refs/remotes/origin/${R}`,x=`refs/heads/${R}`,S=await l(i,["rev-parse","--verify","--quiet",`${x}^{commit}`]).catch(()=>""),b=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(S)||S!==b)return r("origin-binding-start-origin-stale",s);if((await se(i)).some(I=>I.branch===y&&$(I.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",s);const m=`refs/heads/${y}`,j=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(j){const I=await Ze(i,["merge-base","--is-ancestor",S,j]);if(I===1)return r("direct-yolo-origin-not-ancestor",s);if(I!==0)return r("direct-yolo-origin-ancestry-unverifiable",s)}const k={schemaVersion:2,originBranch:R,originHeadSha:S,executionBranch:y,capturedFrom:"branch-ref",capturedAt:t};return await L(i,I=>{const E=P(I,e.epicId);if(E.origin_binding!==void 0&&E.origin_binding!==null)throw new ke("origin-binding-start-raced");if(vt(g(E.branch_lease),o))throw new ke("origin-binding-start-lease-inconsistent");E.origin_binding=k},{expectedRevision:u.revision,preCommit:async()=>{const I=await l(i,["rev-parse","--verify","--quiet",`${x}^{commit}`]).catch(()=>""),E=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>""),q=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(I!==S||E!==S||q!==j)throw new ke("origin-binding-start-raced");j||(await l(i,["update-ref",m,S,""]),p={ref:m,sha:S})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:S,outcome:"captured",executionRefCreated:p!==void 0,capturedAt:t})}catch(d){if(p&&await l(i,["update-ref","-d",p.ref,p.sha]).catch(()=>{}),d instanceof Error&&d.message==="git-lifecycle-runtime-revision-conflict"){f="origin-binding-start-raced";continue}return d instanceof ke?r(d.message,s):r("origin-binding-start-failed",s)}}return r(f)}function De(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 G(e){const t=z(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ue(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return B([await H(e,["diff","--cached","--binary","--full-index"]),await H(e,["diff","--binary","--full-index"]),await H(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function ro(e){const t=$(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await G(t);if(await l(t,["rev-parse","HEAD"])!==o||await l(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 se(e){const t=[];let o;for(const r of(await H(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}const Rt=new Set(Object.values(he));function W(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Oe(e.message)||e instanceof Error&&Rt.has(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function a(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function Ze(e,t){try{return await ne("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function l(e,t){return String((await ne("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function H(e,t){return String((await ne("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function C(e,t){try{return await ne("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Yr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Ut as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,gt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,Pr as acceptDirectYoloSetupCheckpoint,zr as beginDirectYoloStoryCommit,ro as captureDirectYoloCheckoutEvidence,Xr as captureDirectYoloStoryGovernance,to as captureEpicOriginBindingAtYoloopStart,Fr as directYoloCommitIdempotencyKey,Jr as directYoloWaveQaCoverage,Zt as directYoloWaveReceiptRef,Rr as fetchOriginForYoloopStart,Gr as finalizeDirectYoloStoryCheckpoint,ur as isDirectYoloWriteSetExtensionScope,Tr as issueDirectYoloSetupLeaseHandoff,Qr as persistDirectYoloWaveStoryCheckpoint,qr as prepareDirectYoloSetup,Zr as pushDirectYoloWaveHead,eo as readYoloopStartEpic,Mr as recoverLegacyDirectYoloStoryCheckpoint,Kr as resolveDirectYoloIntegrationAuthority,Ur as runDirectYoloWaveP205,Vr as validateDirectYoloWriteSet,Wr as verifyDirectYoloIntegrationCommit,vr as yoloopStartGitNetworkExecOptions};
@@ -0,0 +1,184 @@
1
+ import type { EpicAggregateQaReceipt, EpicHeadReconciliationReceiptV1 } from '../../../shared/dist/yoloop/epic-terminal-git.js';
2
+ import type { EpicTerminalEffectResult } from '../runner/headless/epic-terminal-git-runner.js';
3
+ import { type EpicTerminalReleaseAuthority, type P205TransientExecutionAuthority } from './git-lifecycle-store.js';
4
+ export interface EpicLifecycleEvidenceInput {
5
+ readonly projectRoot: string;
6
+ readonly epicId: string;
7
+ readonly nowIso: string;
8
+ readonly git: (...args: readonly string[]) => Promise<string>;
9
+ /** Headless: true (historical behavior). Invoke: false; off the execution branch fails typed, without effect. */
10
+ readonly allowExecutionBranchSwitch: boolean;
11
+ /** P205 authority already executed in this process; reused only when HEAD and epic graph are exact. */
12
+ readonly p205Authority?: P205TransientExecutionAuthority;
13
+ /** Invoke: never run the complete gate here; without an exact `p205Authority`, fail typed without effect. */
14
+ readonly requireProvidedP205Authority?: boolean;
15
+ /** Test observer after canonical P205; cannot replace the command or result. */
16
+ readonly aggregateQaRunner?: (input: {
17
+ readonly projectRoot: string;
18
+ readonly gateIds: readonly string[];
19
+ }) => Promise<unknown>;
20
+ }
21
+ export type EpicLifecycleEvidenceResult = EpicTerminalEffectResult<{
22
+ readonly originBindingCaptured: boolean;
23
+ readonly aggregateQaRecorded: boolean;
24
+ readonly headReconciliationRecorded?: boolean;
25
+ readonly terminalAuthority?: EpicTerminalReleaseAuthority;
26
+ /** Backward-compatible alias for same-process fresh aggregate producers. */
27
+ readonly p205Authority?: P205TransientExecutionAuthority;
28
+ }>;
29
+ /** Produce (or renew) the epic lifecycle evidence under one compare-bound runtime write. */
30
+ export declare function produceEpicLifecycleEvidence(input: EpicLifecycleEvidenceInput): Promise<EpicLifecycleEvidenceResult>;
31
+ export interface JsonState {
32
+ readonly epics?: Record<string, Record<string, unknown>>;
33
+ readonly stories?: Record<string, Record<string, unknown>>;
34
+ [key: string]: unknown;
35
+ }
36
+ export declare function readEffectiveState(projectRoot: string, statePath: string, requiredRuntime?: boolean): Promise<JsonState>;
37
+ /** P226.15 ADR-3: only bounded, known lifecycle codes may become `causeCode`. */
38
+ export declare const LIFECYCLE_EVIDENCE_CAUSE_PATTERN: RegExp;
39
+ export declare function publicLifecycleEvidenceCause(error: unknown): string | undefined;
40
+ export type LifecycleEvidenceFailure = Extract<EpicTerminalEffectResult, {
41
+ readonly ok: false;
42
+ }> & {
43
+ readonly causeCode?: string;
44
+ };
45
+ export declare function lifecycleEvidenceFailure(error: unknown): LifecycleEvidenceFailure;
46
+ export interface OriginSyncEvidence {
47
+ readonly originSyncHeadSha: string;
48
+ readonly originSyncCommitShas: readonly string[];
49
+ readonly originSyncPaths: readonly string[];
50
+ readonly originSyncResolvedPaths: readonly string[];
51
+ }
52
+ export interface HeadReconciliationRange {
53
+ readonly reconciliationCommitShas: readonly string[];
54
+ readonly changedPaths: readonly string[];
55
+ readonly originSync?: OriginSyncEvidence;
56
+ }
57
+ export interface HeadReconciliationPlan {
58
+ readonly originBranch: string;
59
+ readonly originHeadSha: string;
60
+ readonly executionHeadSha: string;
61
+ readonly acceptedCheckpointIds: readonly string[];
62
+ readonly acceptedCheckpointHeads: readonly string[];
63
+ readonly lastAcceptedCheckpointHeadSha: string;
64
+ readonly allowedWriteSet: readonly string[];
65
+ readonly range: HeadReconciliationRange;
66
+ }
67
+ export declare function prepareHeadReconciliationPlan(input: {
68
+ readonly git: (...args: readonly string[]) => Promise<string>;
69
+ readonly state: JsonState;
70
+ readonly epic: Record<string, unknown>;
71
+ readonly originBranch: string;
72
+ readonly originHeadSha: string;
73
+ readonly executionHeadSha: string;
74
+ }): Promise<HeadReconciliationPlan>;
75
+ /**
76
+ * P226.15 R1–R6: classify the first-parent range after the last accepted
77
+ * checkpoint. A two-parent merge whose second parent descends from the origin
78
+ * binding and is reachable from the (unambiguous) origin tip is an origin-sync
79
+ * merge; any other merge fails closed. Changed paths outside the write-set are
80
+ * exempt only when identical to the synced origin, or when a sync merge
81
+ * resolved them (bounded); a non-merge commit touching them stays invalid.
82
+ */
83
+ export declare function classifyHeadReconciliationRange(input: {
84
+ readonly git: (...args: readonly string[]) => Promise<string>;
85
+ readonly lastAcceptedCheckpointHeadSha: string;
86
+ readonly executionHeadSha: string;
87
+ readonly originBranch: string;
88
+ readonly originBindingHeadSha: string;
89
+ readonly allowedWriteSet: readonly string[];
90
+ readonly acceptedCheckpointIds: readonly string[];
91
+ }): Promise<HeadReconciliationRange>;
92
+ /**
93
+ * The sync origin tip.
94
+ *
95
+ * P227.12 (ADR-1): with an `origin` remote configured, the tip is the freshly
96
+ * queried remote head, confirmed by an exact fetch; the remote-tracking ref is
97
+ * never the authority. A tracking ref that is not an ancestor of the fresh head
98
+ * (diverged/force-pushed) or a raced fetch fails `origin-ref-stale`; any
99
+ * transport failure fails `origin-fetch-unavailable` and never falls back to
100
+ * local refs. The remote URL is probed for presence only and never retained.
101
+ *
102
+ * Without a configured remote (P226.15 DEC-13): when `refs/remotes/origin/<origin>`
103
+ * exists it is the authority, unpushed local commits never count as origin, and
104
+ * a local branch that diverged from it is ambiguous. Without a remote-tracking
105
+ * ref, the local origin branch is the tip; with neither, fail closed.
106
+ */
107
+ export declare function resolveUnambiguousOriginTip(git: (...args: readonly string[]) => Promise<string>, originBranch: string): Promise<string>;
108
+ /**
109
+ * Presence of a configured `origin` remote; the URL itself is discarded. Only
110
+ * Git's documented "No such remote" exit (status 2) proves absence; any other
111
+ * failure (or an empty URL) is ambiguous and fails closed (C11 review).
112
+ */
113
+ export declare function hasOriginRemote(git: (...args: readonly string[]) => Promise<string>): Promise<boolean>;
114
+ /**
115
+ * P227.12 R1/R3/R4/R5: fresh origin head via `ls-remote`, confirmed by an exact
116
+ * fetch so the object exists locally for ancestry proofs. Raw Git errors
117
+ * (including network timeouts/kills) are never propagated; only bounded reason
118
+ * codes leave this function.
119
+ *
120
+ * The fetch keeps Git's default opportunistic update of
121
+ * `refs/remotes/origin/<origin>`, so a stale tracking ref self-heals on the next
122
+ * call (ADR-1, A-002). `fetchRemoteHeadExact` is not reused because its raw
123
+ * `remote-head-raced` failure is outside the public cause pattern.
124
+ */
125
+ export declare function resolveFreshOriginTip(git: (...args: readonly string[]) => Promise<string>, originBranch: string): Promise<string>;
126
+ /** Exactly one merge base; criss-cross histories fail closed. */
127
+ export declare function uniqueMergeBase(git: (...args: readonly string[]) => Promise<string>, left: string, right: string): Promise<string>;
128
+ /** `mode sha` per present path; absent paths are omitted (absence equals absence). */
129
+ export declare function treeEntries(git: (...args: readonly string[]) => Promise<string>, revision: string, paths: readonly string[]): Promise<Map<string, string>>;
130
+ export declare function splitNul(value: string): string[];
131
+ export declare function sameOriginSync(expected: OriginSyncEvidence | undefined, receipt: EpicHeadReconciliationReceiptV1): boolean;
132
+ export declare function buildHeadReconciliationReceipt(input: {
133
+ readonly plan: HeadReconciliationPlan;
134
+ readonly epicId: string;
135
+ readonly executionBranch: string;
136
+ readonly originBranch: string;
137
+ readonly originHeadSha: string;
138
+ readonly executionHeadSha: string;
139
+ readonly graphRevision: string;
140
+ readonly aggregateQaReceipt: EpicAggregateQaReceipt;
141
+ readonly nowIso: string;
142
+ }): EpicHeadReconciliationReceiptV1;
143
+ /** Exported for P227.12 revalidation tests; production callers stay internal. */
144
+ export declare function physicallyValidHeadReconciliation(input: {
145
+ readonly projectRoot: string;
146
+ readonly git: (...args: readonly string[]) => Promise<string>;
147
+ readonly state: JsonState;
148
+ readonly epic: Record<string, unknown>;
149
+ readonly epicId: string;
150
+ readonly executionBranch: string;
151
+ readonly originBranch: string;
152
+ readonly executionHeadSha: string;
153
+ readonly graphRevision: string;
154
+ readonly aggregateQaReceipt: EpicAggregateQaReceipt;
155
+ readonly nowIso: string;
156
+ }): Promise<boolean>;
157
+ export declare function validFreshAggregate(value: EpicAggregateQaReceipt | null | undefined, executionHeadSha: string, graphRevision: string, nowIso: string): value is EpicAggregateQaReceipt;
158
+ export declare function sameOrdered(left: readonly string[], right: readonly string[]): boolean;
159
+ export declare function resolveRemoteHeadFreshOptional(git: (...args: readonly string[]) => Promise<string>, branch: string): Promise<string | undefined>;
160
+ export declare function fetchRemoteHeadExact(git: (...args: readonly string[]) => Promise<string>, branch: string, expectedSha: string): Promise<void>;
161
+ export declare function resolveOptionalRef(git: (...args: readonly string[]) => Promise<string>, ref: string): Promise<string | undefined>;
162
+ export declare function isAncestor(git: (...args: readonly string[]) => Promise<string>, ancestor: string, branch: string): Promise<boolean>;
163
+ export declare function isCommit(git: (...args: readonly string[]) => Promise<string>, sha: string): Promise<boolean>;
164
+ export declare function failure(reasonCode: string, retryEligible: boolean, externalPolicy: boolean): Extract<EpicTerminalEffectResult, {
165
+ readonly ok: false;
166
+ }>;
167
+ export declare function stringValue(value: unknown): string;
168
+ export declare function safeBranch(value: string): boolean;
169
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
170
+ export declare function isNodeError(error: unknown, code: string): error is NodeJS.ErrnoException;
171
+ /**
172
+ * P230.07 (C11 minor #2): the epic's checkpointed stories in physical
173
+ * first-parent order of `executionHeadSha` -- the same order
174
+ * `canonicalizeEpicCheckpointOrder` makes canonical for the P205 claim -- so
175
+ * the head reconciliation anchors to the physically last integrated
176
+ * checkpoint. A listed order that already matches is returned unchanged
177
+ * (byte-identical receipts); any head missing from the first-parent chain
178
+ * keeps the listed order so the existing ancestry checks fail closed.
179
+ */
180
+ export declare function physicalCheckpointOrder(git: (...args: readonly string[]) => Promise<string>, state: JsonState, epic: Record<string, unknown>, executionHeadSha: string): Promise<string[]>;
181
+ export declare function storyIds(epic: Record<string, unknown>): string[];
182
+ export declare function acceptedPhysicalCheckpointIds(projectRoot: string, state: JsonState, epic: Record<string, unknown>, epicId: string, executionBranch: string): Promise<string[]>;
183
+ export declare function hasP205ExecutionAuthority(value: unknown): boolean;
184
+ export declare function hasUncommittedSourceChanges(git: (...args: readonly string[]) => Promise<string>): Promise<boolean>;