@ornexus/neocortex 4.66.12 → 4.66.14
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.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +3 -2
- package/packages/client/dist/cli.js +0 -0
- package/packages/client/dist/commands/invoke.js +1 -1
- package/packages/client/dist/continuity/migrations/007-native-launch-retry.d.ts +19 -0
- package/packages/client/dist/continuity/migrations/007-native-launch-retry.js +16 -0
- package/packages/client/dist/continuity/sqlite-store.d.ts +1 -1
- package/packages/client/dist/continuity/sqlite-store.js +68 -67
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/runner-cli.js +0 -0
- package/packages/client/dist/yoloop/invoke-hooks.d.ts +3 -3
- package/packages/client/dist/yoloop/invoke-hooks.js +11 -11
- package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +2 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +2 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/shared/dist/yoloop/native-launch-retry.js +16 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile as xt}from"node:child_process";import{createHash as bt,randomBytes as Ee,timingSafeEqual as kt}from"node:crypto";import{existsSync as ue}from"node:fs";import{readFile as V,realpath as je}from"node:fs/promises";import{join as X,resolve as N}from"node:path";import{promisify as Dt}from"node:util";import{registeredNestedWorktreeDirectories as Et}from"./worktree-checkout-boundary.js";import{rootProjectMemoryPaths as jt}from"../private-execution/shared-root-memory-types.js";import{readRootMemoryEffectForCheckpoint as Ae}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as ot,verifyRootMemoryPhysicalWriteSet as _e}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as At,resolveEpicStoryIds as _t}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as Be,storyWriteSetCovers as Ce,validateStoryWriteScope as Bt}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as He,computeImmutableStoryQaEvidenceDigest as Ct,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as Ht,computeLegacyDirectYoloRecoveryReceiptRef as Ot,ensureRuntimeEpic as z,ensureRuntimeStory as Oe,ensureGitLifecyclePrivateChildDirectory as $e,executeP205TransientAuthorities as $t,executeP205TransientAuthority as Lt,isP226GateReasonCode as Le,projectP205TransientExecutionEvidence as it,publicStoryReviewArtifactFromBytes as Nt,publicStoryReviewArtifactFromGit as le,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Pt,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as nt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as Ne,STORY_WRITE_SET_MAX_ENTRIES as at,storyWriteSetExtensionPaths as qt,assertGitLifecyclePrivateFile as ee,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as Tt,verifyGitLifecyclePhysicalIntegrationLock as he,verifyAcceptedGitLifecycleStoryCheckpoint as Pe}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as qe,anchoredRemoveFile as ct}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as st,GOVERNANCE_DIGEST_TRAILER as dt,GOVERNANCE_REASON_CODES as ye,captureStoryGovernanceSync as zt,detectGovernanceModeSync as Wt,governanceReceiptRefs as Gt,isGovernanceRepositoryPath as Mt,readGovernanceStateSourceSync as Kt,storyReviewGovernancePath as Vt,verifyStoryGovernanceBinding as Ft}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ft,trailerReasonKey as ae,trailerValue as J}from"./neocortex-trailers.js";import{StoryWorktreeManager as Yt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Jt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ut,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as W}from"./git-lifecycle-step-ids.js";const ce=Dt(xt),se=3600*1e3;async function Wr(e){let t,o=!1;try{const r=await me(e.projectRoot,e.storyId);if(await ze(r.projectRoot)){if(e.expiredSetupRecovery)return a("direct-yolo-expired-setup-recovery-invalid");const S=await pt(r);return{ok:!0,value:lt(r,S,!1)}}const i=q(e.nowIso),n=Date.parse(i),d=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),u=await O(r.projectRoot,{required:!0}),s=g(u.epics[r.epicId]),f=g(s?.branch_lease),p=e.expiredSetupRecovery;if(p&&!hr(p,u.revision,f,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const v=f&&Number.isFinite(Date.parse(String(f.expiresAt)))&&Date.parse(String(f.expiresAt))>n;if(v&&f?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let y=Z(s?.origin_binding,r.executionBranch,r.originBranch),h;if(d===r.executionBranch){if(!y){if(s?.origin_binding!==void 0&&s?.origin_binding!==null||v)return a("direct-yolo-origin-binding-invalid");const S=await wr(r,c,i);if(!S.ok)return S;y=S.value.binding,h={originRef:S.value.originRef,originHeadSha:S.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(y&&y.originHeadSha!==c){if(!p||!await C(r.projectRoot,["merge-base","--is-ancestor",y.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 D=await l(r.projectRoot,["rev-parse",m]);if(!await C(r.projectRoot,["merge-base","--is-ancestor",D,c]))return a("direct-yolo-execution-branch-diverged")}if(y??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await fe(r.projectRoot)).some(m=>m.branch===r.executionBranch&&N(m.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const R=await G(r.projectRoot),j=`refs/heads/${r.executionBranch}`;if(await C(r.projectRoot,["show-ref","--verify","--quiet",j])){const m=await l(r.projectRoot,["rev-parse",j]);if(m!==c){if(!await C(r.projectRoot,["merge-base","--is-ancestor",m,c]))return a("direct-yolo-execution-branch-diverged");p||await l(r.projectRoot,["update-ref",j,c,m])}p?t={checkoutBefore:R,executionRef:j,executionBranch:r.executionBranch,executionHead:m,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(p)return a("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await G(r.projectRoot)!==R)return a("direct-yolo-checkout-payload-raced")}const I=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(v&&f?.ownerStoryId===e.storyId)return f.setupHeadSha!==I?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:De(r,y,String(f.expiresAt),!0)};const _=i,w=new Date(n+3600*1e3).toISOString(),E=`setup-${Ee(32).toString("hex")}`,k=p?u:await O(r.projectRoot,{required:!0});return await P(r.projectRoot,S=>{const R=z(S,r.epicId),j=g(R.branch_lease);if(p&&JSON.stringify(j)!==JSON.stringify(p.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(j&&Date.parse(String(j.expiresAt))>n&&j.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const m=Z(R.origin_binding,r.executionBranch,r.originBranch);if(R.origin_binding&&!m)throw new Error("direct-yolo-origin-binding-conflict");if(m&&JSON.stringify(m)!==JSON.stringify(y))throw new Error("direct-yolo-origin-binding-conflict");R.branch_mode="epic",R.execution_branch=r.executionBranch,R.origin_branch=r.originBranch,R.graph_revision=r.graphRevision,R.origin_binding=y,R.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:E,idempotencyKey:E,acquiredAt:_,expiresAt:w,setupHeadSha:I}},{expectedRevision:p?.expectedRuntimeRevision??k.revision,preCommit:async()=>{if(t){if((await fe(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.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"])!==I)throw new Error("direct-yolo-setup-physical-state-raced");if(h&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${h.originRef}^{commit}`]).catch(()=>"")!==h.originHeadSha||await et(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,I])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:De(r,y,w,!1)}}catch(r){return o&&t&&await yr(N(e.projectRoot),t).catch(()=>{}),a(K(r,"direct-yolo-setup-failed"))}}async function Gr(e){let t;try{const o=await me(e.projectRoot,e.storyId);if(await ze(o.projectRoot))return await Zt(o,q(e.nowIso));const r=await U(e.projectRoot,e.storyId),i=q(e.nowIso),n=X(r.projectRoot,".neocortex/state.json"),d=await V(n,"utf8"),c=await G(r.projectRoot),u=await l(r.projectRoot,["rev-parse","HEAD"]),s=`refs/heads/${r.executionBranch}`,f=await O(r.projectRoot,{required:!0}),p=g(f.epics[r.epicId]),v=Z(p?.origin_binding,r.executionBranch,r.originBranch),y=g(p?.branch_lease);if(!v)return a("direct-yolo-origin-binding-invalid");if(!y||!Je(y,e.storyId,i)||y?.sessionId!==y?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const h=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(y.sessionId),idempotencyKey:String(y.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!h.ok)return a(h.reasonCode);if(t=h,u!==y.setupHeadSha||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)return a("direct-yolo-setup-head-mismatch");if((await fe(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const _=g(JSON.parse(d)),w=g(g(_?.stories)?.[e.storyId]),E=g(f.stories[e.storyId]);if(!w||!["backlog","ready_to_start"].includes(String(w.status))||w.steps_completed!==void 0&&(!Array.isArray(w.steps_completed)||w.steps_completed.length>0)||w.branch_name||w.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const k=E?.status==="branch-ready"&&E.last_step===W&&Array.isArray(E.steps_completed)&&E.steps_completed.length===1&&E.steps_completed[0]===W&&oe(E).sort().join(",")==="last_step,status,steps_completed";if(E&&oe(E).length>0&&!k)return a("direct-yolo-setup-story-progress-conflict");const S=async()=>{if(Date.parse(String(y.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await he(t.path,t.owner)||await V(n,"utf8")!==d||await G(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==u||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)throw new Error("direct-yolo-setup-physical-state-raced")};return k?await S():await P(r.projectRoot,R=>{const j=g(R.epics[r.epicId]),m=Oe(R,e.storyId);if(JSON.stringify(j?.branch_lease)!==JSON.stringify(y)||JSON.stringify(j?.origin_binding)!==JSON.stringify(v)||j?.graph_revision!==r.graphRevision||oe(m).length>0)throw new Error("direct-yolo-setup-runtime-raced");m.status="branch-ready",m.last_step=W,m.steps_completed=[W]},{expectedRevision:f.revision,preCommit:S}),{ok:!0,value:Object.freeze({...De(r,v,String(y.expiresAt),k),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:u})}}catch(o){return a(K(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function Mr(e){try{const t=await U(e.projectRoot,e.storyId),o=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),r=re(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return a(r.reasonCode);t.rootMemoryEffect&&_e(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"?Ge(t):void 0;if((i?i.review:le(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>o.includes(b)))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 u=B(c),s=B([...t.authorizedWriteSet].sort().join("\0")),f=q(e.nowIso),p=await O(t.projectRoot,{required:!0});let v=g(p.epics[t.epicId]?.branch_lease),y;if(!Je(v,e.storyId,f)){const x=v!==void 0&&Date.parse(String(v.expiresAt))>Date.parse(f)?void 0:await gt(t.projectRoot,p,t.epicId,e.storyId,f);if(!x||!await C(t.projectRoot,["merge-base","--is-ancestor",x.setupHeadSha,"HEAD"]))return a("direct-yolo-setup-handoff-owner-invalid");y=x,v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:x.sessionId,idempotencyKey:x.idempotencyKey,acquiredAt:f,expiresAt:new Date(Math.min(Date.parse(x.expiresAt),Date.parse(f)+or)).toISOString(),setupHeadSha:x.setupHeadSha}}const h=String(v.sessionId),I=String(v.expiresAt),_=new Date(Math.min(Date.parse(I),Date.parse(f)+300*1e3)).toISOString(),w=await te(t.projectRoot,e.storyId),E=w?.state==="issued"&&w.fromSessionId===h&&w.bundleDigest===u&&w.claimRevision===s&&Date.parse(w.expiresAt)>Date.parse(f),k=E?w.expiresAt:_,S=E?w.token:Ee(32).toString("base64url"),R=B(S),j=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:h,tokenDigest:R,bundleDigest:u,claimRevision:s,expiresAt:k}),m=B(JSON.stringify(j)),D=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!1,createdAt:f});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ze(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:h,token:S,tokenDigest:R,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k}),await P(t.projectRoot,b=>{const x=z(b,t.epicId);if(y){const $=g(x.branch_lease);if($&&Date.parse(String($.expiresAt))>Date.parse(f))throw new Error("direct-yolo-setup-handoff-owner-raced");x.branch_lease={...v}}const A=g(x.branch_lease);if(!Je(A,e.storyId,f)||A?.sessionId!==h||A.idempotencyKey!==h)throw new Error("direct-yolo-setup-handoff-owner-raced");A.handoffGrant=j},{expectedRevision:p.revision,preCommit:async()=>{if(!await he(D.path,D.owner))throw new Error("direct-yolo-integration-lock-raced");const b=await te(t.projectRoot,e.storyId);if(!b||b.state!=="issued"||b.grantDigest!==m||b.tokenDigest!==R)throw new Error("direct-yolo-setup-handoff-token-raced");if(y&&(await yt(t.projectRoot,e.storyId))?.sessionId!==y.sessionId)throw new Error("direct-yolo-setup-handoff-owner-raced")}}),y&&await nr(t.projectRoot,e.storyId)}finally{await Y(D.path,D.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:h,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k,reused:E,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return a(t instanceof Error&&(/^direct-yolo-/.test(t.message)||It.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function Kr(e){try{const t=await U(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),i=re(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&_e(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?Ge(t):void 0,d=n?n.review:le(t.projectRoot,e.storyId,":");if(d?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>r.includes(b)))return a("direct-yolo-user-overlap");const u=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!u)return a("direct-yolo-staged-diff-empty");const s=B(u),f=B([...t.authorizedWriteSet].sort().join("\0")),p=await Ye(t.projectRoot,e.storyId),v=p.state==="valid"&&p.plan.epicId===t.epicId&&p.plan.executionBranch===t.executionBranch&&p.plan.preparedBase===o&&p.plan.bundleDigest===s&&p.plan.claimRevision===f?p.plan:void 0,y=v?.graphRevision??t.graphRevision,h=Ve({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,graphRevision:y,claimRevision:f}),I=q(e.nowIso),_={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:y,preparedBase:o,bundleDigest:s,claimRevision:f,idempotencyKey:h,issuedAt:v?.issuedAt??I};let w=e.setupLeaseHandoff??await ar(t.projectRoot,e.storyId,s,f,I);const E=await O(t.projectRoot,{required:!0}),k=g(E.epics[t.epicId]?.branch_lease),S=k?.ownerStoryId===e.storyId&&k.sessionId===h&&k.idempotencyKey===h&&typeof k.expiresAt=="string"&&Date.parse(k.expiresAt)>Date.parse(I)?k:void 0;if(S&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const R=g(S?.handoffConsumption);if(R){const b=await te(t.projectRoot,e.storyId);if(!b||!["consuming","consumed"].includes(b.state)||b.fromSessionId!==R.fromSessionId||b.tokenDigest!==R.tokenDigest||b.bundleDigest!==s||b.claimRevision!==f||R.bundleDigest!==s||R.claimRevision!==f||b.consumedBySessionId!==h||R.consumedBySessionId!==h)return a("direct-yolo-setup-handoff-consume-invalid");if(b.state==="consuming"){if(!b.token||B(b.token)!==b.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");w={sessionId:b.fromSessionId,token:b.token}}}const j=S?String(S.expiresAt):new Date(Date.parse(I)+se).toISOString(),m=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:j,persistent:!0,createdAt:S&&typeof S.acquiredAt=="string"?S.acquiredAt:I});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{w&&e.setupLeaseHandoff===void 0&&(await cr(t.projectRoot,e.storyId,w.sessionId,w.token,h,I),await e.setupHandoffFault?.("after-consuming-persisted")),await P(t.projectRoot,b=>{const x=z(b,t.epicId),A=g(x.branch_lease),$=A&&Date.parse(String(A.expiresAt))>Date.parse(I),L=A?.ownerStoryId===e.storyId&&A.sessionId===h&&A.idempotencyKey===h,M=A?.ownerStoryId===e.storyId&&A.sessionId===A.idempotencyKey&&typeof A.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(A.idempotencyKey),Q=$&&M&&dr({current:A,handoff:w,storyId:e.storyId,bundleDigest:s,claimRevision:f,nowIso:I});if(w&&$&&!L&&!Q)throw new Error("direct-yolo-setup-handoff-invalid");if($&&!L&&!Q)throw new Error("direct-yolo-writer-active");const tt=Q?g(A?.handoffGrant):void 0,rt=tt?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(A?.sessionId),tokenDigest:String(tt.tokenDigest),bundleDigest:s,claimRevision:f,consumedBySessionId:h,consumedAt:I}:void 0;x.branch_mode="epic",x.execution_branch=t.executionBranch,x.origin_branch=t.originBranch,x.graph_revision=t.graphRevision,x.branch_lease=$&&L?A:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:I,expiresAt:j,...rt?{handoffConsumption:rt}:{}}},{expectedRevision:E.revision,preCommit:async()=>{if(!await he(m.path,m.owner))throw new Error("direct-yolo-integration-lock-raced");await tr(t.projectRoot,_)}})}catch(b){throw await Y(m.path,m.owner).catch(()=>{}),b}w&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await sr(t.projectRoot,t.epicId,e.storyId,w.sessionId,w.token,s,f,h,I));const D=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: ${d.digest}`,`Neocortex-Graph-Revision: ${y}`,`Neocortex-Claim-Revision: ${f}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ot(t.rootMemoryEffect)}`]:[],...n?[`${dt}: ${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:d.digest,graphRevision:y,claimRevision:f,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:D,...n?{governance:n.receipt}:{}})}}catch(t){return a(K(t,"direct-yolo-begin-failed"))}}async function Vr(e){let t,o,r;try{const i=await U(e.projectRoot,e.storyId);t=i;const n=e.preFastForwardAuthorizedWriteSet;if(n!==void 0&&!Te(n))return a("direct-yolo-write-set-invalid");const d=n??i.authorizedWriteSet,c=await l(i.projectRoot,["rev-parse","HEAD"]);let u=await O(i.projectRoot,{required:!0});const s=g(u.stories[e.storyId]?.checkpoint);if(s){const D=typeof s.headSha=="string"?s.headSha:"",b=typeof s.graphRevision=="string"?s.graphRevision:"",x=/^[a-f0-9]{40,64}$/.test(D)?T(await H(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",D])):[],A=re(x,d,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(D)&&await C(i.projectRoot,["merge-base","--is-ancestor",D,c]))||!/^[a-f0-9]{64}$/.test(b)||!A.ok)return a("direct-yolo-replay-invalid");const L=await Ie(e,i.projectRoot,c,b);if(!await Pe(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,L.transientAuthority,d))return a("direct-yolo-replay-invalid");if(!await xe(i.projectRoot,i.executionBranch,c,x))return a("direct-yolo-replay-head-raced");if(e.push&&!await Ke(i.projectRoot,e.remote??"origin",i.executionBranch,D))return a("direct-yolo-remote-head-mismatch");const M=Array.isArray(s.receiptRefs)?s.receiptRefs.find(Q=>typeof Q=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(Q)):void 0;return M&&typeof s.idempotencyKey=="string"&&await Tt(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:M.slice(20)}),await de(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const f=c,p=await ge(i,e.storyId,f,n?{claimWriteSet:n}:{});if(!p.ok)return a(p.reasonCode);const{baseSha:v,changedPaths:y,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,governance:E}=p.value,k=g(u.epics[i.epicId]?.branch_lease),S=q(e.nowIso),R=k?.ownerStoryId===e.storyId&&k.idempotencyKey===w&&k.sessionId===w&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!R)return a("direct-yolo-writer-active");const j=R??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:w,idempotencyKey:w,acquiredAt:S,expiresAt:new Date(Date.parse(S)+se).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,R||(u=(await P(i.projectRoot,b=>{const x=z(b,i.epicId),A=g(x.branch_lease);if(A&&Date.parse(String(A.expiresAt))>Date.parse(S))throw new Error("direct-yolo-writer-active");if(x.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");x.branch_lease=j},{expectedRevision:u.revision})).document),o=j;{const D=await Ie(e,i.projectRoot,f,I);if(!await xe(i.projectRoot,i.executionBranch,f,y))return a("direct-yolo-head-raced");if(e.push){const A=ne(e.remote??"origin");if(await l(i.projectRoot,["push",A,i.executionBranch]),!await Qe(i.projectRoot,A,i.executionBranch,f))return a("direct-yolo-remote-head-mismatch")}const b=await we({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:v,headSha:f,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,qaExecution:D,physicalLockOwnerDigest:pe(m.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...E?{governance:E}:{}});return await e.beforeCheckpointPersist?.(),await ve({projectRoot:i.projectRoot,checkpoint:b,remote:e.push?e.remote??"origin":void 0,expectedRevision:u.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:I,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:d})?(await de(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:b}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(K(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await Se(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await ur(t,e.storyId).catch(()=>{})}}function Te(e){return Array.isArray(e)&&e.length>0&&e.length<=at&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}async function Fr(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(K(i,"direct-yolo-commit-verification-failed"))}}async function ge(e,t,o,r={}){if(r.claimWriteSet!==void 0&&!Te(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}^`]),d=await H(e.projectRoot,["show","--no-patch","--format=%B",o]),c=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),u=re(c,i,t,e.rootMemoryEffect,e.governanceMode);if(!u.ok)return a(u.reasonCode);e.rootMemoryEffect&&_e(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:n,headRef:o,childPaths:i});const s=B([...i].sort().join("\0")),f=await Ye(e.projectRoot,t);if(f.state==="invalid")return a("direct-yolo-commit-plan-invalid");const p=f.state==="valid"?f.plan:void 0;if(p&&(p.epicId!==e.epicId||p.executionBranch!==e.executionBranch))return a("direct-yolo-commit-plan-invalid");if(p&&p.claimRevision!==s)return a("direct-yolo-commit-plan-claim-changed");if(p&&p.preparedBase!==n)return a("direct-yolo-commit-plan-base-mismatch");const v=ft(d,st);if(!v.ok)return a(`direct-yolo-trailer-duplicate:${v.key}`);const y=v.values;if(r.expectedGraphRevision!==void 0&&p&&p.graphRevision!==r.expectedGraphRevision)return a(`direct-yolo-trailer-mismatch:${ae("Neocortex-Graph-Revision")}`);const h=r.expectedGraphRevision??p?.graphRevision??e.graphRevision,I=s,_=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",n],["Neocortex-Bundle-Digest",p?.bundleDigest??""],["Neocortex-Graph-Revision",h],["Neocortex-Claim-Revision",I]];for(const[D,b]of _){const x=J(y,D);if(x===void 0)return a(`direct-yolo-trailer-missing:${ae(D)}`);if(D==="Neocortex-Bundle-Digest"&&!p){if(!/^[a-f0-9]{64}$/.test(x))return a(`direct-yolo-trailer-mismatch:${ae(D)}`);continue}if(x!==b)return a(`direct-yolo-trailer-mismatch:${ae(D)}`)}const w=J(y,"Neocortex-Bundle-Digest"),E=J(y,dt);if(e.governanceMode!=="runtime-store"&&E!==void 0)return a(ye.MISMATCH);const k=e.governanceMode==="runtime-store"?Me({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},E):void 0,S=k?k.review:le(e.projectRoot,t,o);if(S?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const R=J(y,"Neocortex-Review-Artifact-Digest");if(R!==void 0&&R!==S.digest)return a("direct-yolo-review-artifact-digest-mismatch");const j=B(await H(e.projectRoot,["diff","--binary","--full-index",`${n}..${o}`]));if(w!==j)return a("direct-yolo-bundle-digest-mismatch");const m=Ve({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:n,bundleDigest:w,graphRevision:h,claimRevision:I});return p&&p.idempotencyKey!==m?a("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:n,changedPaths:c,bundleDigest:w,graphRevision:h,claimRevision:I,idempotencyKey:m,...k?{governance:k.receipt}:{}}}}async function Yr(e){try{const t=await U(e.projectRoot,e.storyId,!1);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(Pt[e.storyId]!==o)return await Ut(e,t,o);if(await Ae({...t,childPaths:t.authorizedWriteSet}),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=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!re(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const c=B(i),u=B([...n].sort().join("\0")),s=B(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),f=q(e.nowIso),p=new Date(Date.parse(f)+se).toISOString(),v=await O(t.projectRoot,{required:!0}),y=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:p,persistent:!0,createdAt:f});if(!y.ok)return a(y.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const h={schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:f,expiresAt:p};let I=!1;try{const _=await P(t.projectRoot,j=>{const m=z(j,t.epicId),D=g(m.branch_lease);if(D&&Date.parse(String(D.expiresAt))>Date.parse(f)&&!Re(D,h))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=h},{expectedRevision:v.revision});I=!0;const w=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 j=ne(e.remote??"origin"),m=(await l(t.projectRoot,["ls-remote","--heads",j,`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 E=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:u,idempotencyKey:s,qaExecution:w,physicalLockOwnerDigest:pe(y.owner),nowIso:f,legacyReceiptRef:void 0}),k=await Ot(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!k)return a("direct-yolo-recovery-evidence-invalid");const S=Object.freeze({...E,receiptRefs:Object.freeze([...E.receiptRefs,k])});return await ve({projectRoot:t.projectRoot,checkpoint:S,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:_.document.revision,expectedLease:h,expectedGraphRevision:t.graphRevision,physicalLockPath:y.path,physicalLockOwner:y.owner,transientAuthority:w.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:S}:a("direct-yolo-recovery-persist-failed")}finally{await Y(y.path,y.owner).catch(()=>{}),I&&await Se(t.projectRoot,t.epicId,h).catch(()=>{})}}catch(t){return a(K(t,"direct-yolo-recovery-failed"))}}async function Ut(e,t,o){const r=await H(t.projectRoot,["show","--no-patch","--format=%B",o]),i=ft(r,st);if(!i.ok||J(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=J(i.values,"Neocortex-Root-Memory-Effect");let d=t.graphRevision;if(n!==void 0){if(!/^[a-f0-9]{64}$/.test(n))return a("direct-yolo-recovery-root-governance-unverified");const D=await Ye(t.projectRoot,e.storyId);if(D.state==="invalid")return a("direct-yolo-commit-plan-invalid");if(D.state==="valid"&&(d=D.plan.graphRevision),J(i.values,"Neocortex-Graph-Revision")!==d)return a(`direct-yolo-trailer-mismatch:${ae("Neocortex-Graph-Revision")}`)}let c;try{c=await Ae({...t,graphRevision:d,childPaths:t.authorizedWriteSet})}catch{return a("direct-yolo-recovery-root-governance-unverified")}if((c?ot(c):void 0)!==n)return a("direct-yolo-recovery-root-governance-unverified");const u=await ge({...t,rootMemoryEffect:c},e.storyId,o);if(!u.ok){if(u.reasonCode==="direct-yolo-write-set-unauthorized"){const D=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","--no-renames","-r","-z",o])),b=new Set([...jt(),`docs/epics/epic-${t.epicId}.md`]);if(D.some(x=>b.has(x)&&!Ce(t.authorizedWriteSet,x)&&!c?.files.some(A=>A.path===x)))return a("direct-yolo-recovery-root-governance-unverified")}return a(u.reasonCode)}const{baseSha:s,changedPaths:f,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,governance:I}=u.value,_=ne(e.remote??"origin");let w=!1;try{w=await Ke(t.projectRoot,_,t.executionBranch,o)}catch{w=!1}if(!w)return a("direct-yolo-recovery-remote-proof-missing");const E=q(e.nowIso),k=new Date(Date.parse(E)+se).toISOString(),S=await O(t.projectRoot,{required:!0});if(g(S.stories[e.storyId]?.checkpoint))return a("direct-yolo-checkpoint-conflict");const R=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!0,createdAt:E});if(!R.ok)return a(R.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const j={schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:E,expiresAt:k};let m=!1;try{const D=await P(t.projectRoot,$=>{const L=z($,t.epicId),M=g(L.branch_lease);if(M&&Date.parse(String(M.expiresAt))>Date.parse(E)&&!Re(M,j))throw new Error("direct-yolo-recovery-writer-active");if(L.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");L.branch_mode="epic",L.execution_branch=t.executionBranch,L.origin_branch=t.originBranch,L.branch_lease=j},{expectedRevision:S.revision});m=!0;const b=await Ie(e,t.projectRoot,o,v);if(!await xe(t.projectRoot,t.executionBranch,o,f))return a("direct-yolo-recovery-head-raced");const x=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:o,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,qaExecution:b,physicalLockOwnerDigest:pe(R.owner),nowIso:E,legacyReceiptRef:void 0,rootMemoryEffect:c,...I?{governance:I}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:x,remote:_,remotePolicy:"ancestor-recovery",expectedRevision:D.document.revision,expectedLease:j,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:v,physicalLockPath:R.path,physicalLockOwner:R.owner,transientAuthority:b.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):a("direct-yolo-recovery-persist-failed")}finally{await Y(R.path,R.owner).catch(()=>{}),m&&await Se(t.projectRoot,t.epicId,j).catch(()=>{})}}async function ze(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 pt(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===e.storyId&&p.epicId===e.epicId&&p.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 d=await new Yt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=Z(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const u=r.syncedSha??r.baseSha,s=await l(e.projectRoot,["rev-parse","HEAD"]),f=`refs/heads/${e.executionBranch}`;if(s!==u||!await C(e.projectRoot,["merge-base","--is-ancestor",u,f])||!await C(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,u]))throw new Error("direct-yolo-worktree-base-divergent");if(d.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:u,headSha:s,expiresAt:r.expiresAt,binding:c}}function lt(e,t,o){return Object.freeze({...De(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Zt(e,t){const o=await pt(e),r=We(e.projectRoot),i=g(JSON.parse(r)),n=g(g(i?.stories)?.[e.storyId]),d=await O(e.projectRoot,{required:!0}),c=g(d.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 u=c?.status==="branch-ready"&&c.last_step===W&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===W&&oe(c).sort().join(",")==="last_step,status,steps_completed";if(c&&oe(c).length>0&&!u)return a("direct-yolo-setup-story-progress-conflict");u||await P(e.projectRoot,p=>{const v=Oe(p,e.storyId);if(oe(v).length>0)throw new Error("direct-yolo-setup-runtime-raced");v.status="branch-ready",v.last_step=W,v.steps_completed=[W]},{expectedRevision:d.revision,preCommit:async()=>{if(We(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}),f=await gt(e.projectRoot,s,e.epicId,e.storyId,t);if(f?.leaseId!==o.leaseId||f.setupHeadSha!==o.headSha){const p=`setup-${Ee(32).toString("hex")}`;await ir(e.projectRoot,{schemaVersion:1,kind:ht,epicId:e.epicId,ownerStoryId:e.storyId,sessionId:p,idempotencyKey:p,leaseId:o.leaseId,acquiredAt:t,expiresAt:o.expiresAt,setupHeadSha:o.headSha})}return{ok:!0,value:Object.freeze({...lt(e,o,u),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:o.headSha})}}async function Jr(e,t){const o=await U(e,t),r=await O(o.projectRoot,{required:!0}),i=Z(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Ur(e,t,o,r,i="tracked"){return re(e,t,o,r,i)}function Zr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Qr=se,Qt="p205-wave:";function Xr(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 Xt(e){return`${Qt}${e.waveHeadSha}:${e.waveDigest}`}async function eo(e){let t;try{t=await $t(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:Le(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:Le(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function to(e,t,o,r){const i=ne(t);return await l(e,["push",i,o]),Qe(e,i,o,r)}async function ro(e){try{const t=await U(e.projectRoot,e.storyId);if(e.authorizedWriteSet!==void 0&&!Te(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}),d=g(n.stories[e.storyId]?.checkpoint);if(d){if(d.headSha!==e.headSha)return a("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(d.graphRevision));return await Pe(t.projectRoot,d,e.storyId,t.epicId,t.executionBranch,k??null,o)?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:d}):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:u,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,governance:y}=c.value,h=i===0?void 0:e.coverage.waveCommitShas[i-1];if(h!==void 0&&u!==h)return a("direct-yolo-wave-chain-invalid");const I=e.authorities.get(f),_=it(I);if(!I||!_||_.executionHeadSha!==r||_.graphRevision!==f)return a("direct-yolo-wave-qa-unbound");const w=await we({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:u,headSha:e.headSha,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,qaExecution:{contract:"P205-CI-02",command:nt,manifestDigest:_.manifestDigest,gateIds:_.gateIds,resultDigest:_.resultDigest,transientAuthority:I},physicalLockOwnerDigest:pe(e.physicalLock.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Xt(e.coverage)],...y?{governance:y}:{}});return await ve({projectRoot:t.projectRoot,checkpoint:w,remote:e.remote,expectedRevision:n.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:I,authorizedWriteSet:o,expectedHeadSha:r,keepLease:!0})?(await de(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:w}):a("direct-yolo-checkpoint-persist-failed")}catch(t){return a(K(t,"direct-yolo-wave-persist-failed"))}}async function me(e,t,o=!0){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const r=N(e),i=g(JSON.parse(We(r))),n=await O(r,{required:!0}),d=He(i,n),c=Wt({projectRoot:r,storyId:t});if(!c.ok)throw new Error(c.reasonCode);const u=c.mode,s=g(d.stories),f=g(d.epics),p=g(s?.[t]),v=String(p?.epic_id??t.split(".")[0]),y=g(f?.[v]),h=String(y?.execution_branch??""),I=String(y?.origin_branch??""),_=String(y?.graph_revision??""),w=Array.isArray(p?.files_to_modify)?p.files_to_modify:[],E=qt(p).filter(lr),k=[...w,...E],S=k.length>0?Be(t,k):void 0,R=S?.ok?S.scopes:[];if(!p)throw new Error("direct-yolo-story-state-missing");if(E.length>0&&R.length>at)throw new Error("direct-yolo-write-set-too-large");if(y?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!ie(h)||!await C(r,["check-ref-format","--branch",h]))throw new Error("direct-yolo-execution-branch-invalid");if(!ie(I)||!await C(r,["check-ref-format","--branch",I]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(_))throw new Error("direct-yolo-graph-revision-invalid");const j=o?await Ae({projectRoot:r,storyId:t,graphRevision:_,executionBranch:h,childPaths:R}):void 0;return{projectRoot:r,storyId:t,story:p,epicId:v,executionBranch:h,originBranch:I,graphRevision:_,authorizedWriteSet:R,rootMemoryEffect:j,governanceMode:u}}async function oo(e){try{const t=await me(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?a("governance-capture-not-applicable"):await ze(t.projectRoot)?a("governance-capture-root-required"):{ok:!0,value:Ge(t).receipt}}catch(t){return a(K(t,"governance-capture-failed"))}}function We(e){const t=Kt(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 Ge(e){const t=zt(e);if(!t.ok)throw new Error(t.reasonCode);return Me(e,t.value.governanceDigest)}function Me(e,t){const o=Ft({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Vt(e.storyId));if(!r)throw new Error(ye.MISMATCH);return{receipt:o.value.receipt,review:Nt(e.storyId,r)}}async function U(e,t,o=!0){const r=await me(e,t,o);if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return r}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=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=Ct({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ht({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}),u=e.governance?Me(e,e.governance.governanceDigest).review:le(e.projectRoot,e.storyId,e.headSha);if(u?.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,d,B(o),[...r].sort().join(","),u.digest].join("\0")),f=`story-review:${s}`,p=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:u.digest,qaReceiptRef:d,verdict:"approved",reviewedAt:t,receiptRef:f}),v=[`.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?Gt(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(v),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:p,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function ve(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await P(t,n=>{const d=z(n,o.epicId);if(e.expectedLease){const f=g(d.branch_lease);if(!Re(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=Oe(n,o.storyId),u=g(c.checkpoint);if(u&&u.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=ut;const s=Array.isArray(c.steps_completed)?c.steps_completed.filter(f=>typeof f=="string"):[];c.steps_completed=[...new Set([...s,Jt,ut])],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 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 Pe(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 he(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Ke(t,r,o.branch,o.headSha):await Qe(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Ke(e,t,o,r){const i=ne(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 Ve(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const er=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Fe(e,t){const o=await Ne(e),r=await $e(o,"commit-plans"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function tr(e,t){const o=await Fe(e,t.storyId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
2
|
-
`),await ee(o.path,o.parent)}async function Ye(e,t){let o;try{o=await Fe(e,t)}catch{return{state:"invalid"}}try{if(!
|
|
3
|
-
`),await ee(o.path,o.parent)}async function
|
|
4
|
-
`),await ee(o.path,o.parent)}async function te(e,t){try{const o=await mt(e,t);await ee(o.path,o.parent);const r=JSON.parse(await V(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 ar(e,t,o,r,i){const n=await te(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 cr(e,t,o,r,i,n){const d=await te(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==B(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 Ze(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function sr(e,t,o,r,i,n,d,c,u){const s=await te(e,o);if(s?.state==="consumed"&&s.fromSessionId===r&&s.consumedBySessionId===c)return;const f=await O(e,{required:!0}),p=g(f.epics[t]?.branch_lease),v=g(p?.handoffConsumption);if(!s||s.state!=="consuming"||s.fromSessionId!==r||s.token!==i||s.tokenDigest!==B(i)||s.bundleDigest!==n||s.claimRevision!==d||s.consumedBySessionId!==c||p?.ownerStoryId!==o||p.sessionId!==c||v?.kind!=="direct-yolo-setup-handoff-consumption"||v.state!=="consumed"||v.fromSessionId!==r||v.tokenDigest!==s.tokenDigest||v.bundleDigest!==n||v.claimRevision!==d||v.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ze(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:u})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function dr(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)&&fr(t.tokenDigest,r))}function fr(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&kt(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 P(e,r=>{const i=z(r,t),n=g(i.branch_lease);Re(n,o)&&(i.branch_lease=null)})}async function ur(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 F(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 Y(i.path,i.owner)&&await Se(e.projectRoot,e.epicId,r)}async function Ie(e,t,o,r){const i=await Lt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=it(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:nt,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 Qe(e,t,o,r){const i=ne(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function re(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!Xe(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return pr(e,t,o,r);const n=t.length>0?Be(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=>!Ce(n.scopes,c)&&!r?.files.some(u=>u.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 pr(e,t,o,r){if(e.some(Mt))return{ok:!1,reasonCode:ye.WRITE_SET_FORBIDDEN};const i=t.length>0?Be(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!==B([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!Ce(i.scopes,d)&&!r?.files.some(c=>c.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function oe(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function lr(e){return typeof e!="string"||e.length>512||!Xe(e)||!Bt(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Xe(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 ie(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ne(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function B(e){return bt("sha256").update(e).digest("hex")}function T(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 g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function hr(e,t,o,r,i){const n=g(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 yr(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 gr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],mr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function Z(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!==gr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==mr.join("\0")?void 0:r}async function wr(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 fe(e.projectRoot)).some(u=>u.branch===e.executionBranch&&N(u.path)!==e.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return a("direct-yolo-setup-physical-state-raced");const c=await et(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 wt=3e4,vr=3,Rr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class ke extends Error{}function Sr(e,t=wt){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:Rr}}}}async function Ir(e){if(!ie(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ce("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:N(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Sr(process.env,e.fetchTimeoutMs??wt)}),{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 xr=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function io(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=N(e),i=g(JSON.parse(await V(X(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),d=He(i,n),c=g(g(d.epics)?.[t]);if(!c)return o;const u=Rt(d,t,c),s=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,f=await vt(r,c,i),p=g(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:u,terminal:xr.has(String(c.status??"").toLowerCase()),bound:!!Z(p,s,f),executionBranch:s,originBranch:f})}catch{return o}}async function vt(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 d of["main","master"])await C(e,["rev-parse","--verify","--quiet",`refs/heads/${d}^{commit}`])&&await C(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${d}^{commit}`])&&n.push(d);return n.length===1?n[0]:""}function Rt(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=_t(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const u=g(r[c]);return u?[{...u,id:c}]:[]}),d=At({...o,id:t},n);return d.mode==="epic"&&(d.source==="new-epic-default"||d.source==="epic-boundary")?"resolved-epic":"not-epic"}function St(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function no(e){const t=q(e.nowIso),o=Date.parse(t),r=(c,u={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...u,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=N(e.projectRoot);let n=e.originFetch,d="origin-binding-start-raced";for(let c=0;c<vr;c+=1){let u,s={};try{const f=g(JSON.parse(await V(X(i,".neocortex/state.json"),"utf8")));if(!f)return r("origin-binding-start-state-invalid");const p=await O(i),v=He(f,p),y=g(g(v.epics)?.[e.epicId]);if(!y)return r("origin-binding-start-target-ambiguous");if(Rt(v,e.epicId,y)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const h=typeof y.execution_branch=="string"&&y.execution_branch.length>0?y.execution_branch:`epic/${e.epicId}`,I=await vt(i,y,f);if(s={executionBranch:h,originBranch:I},!ie(h)||!ie(I)||h===I||!await C(i,["check-ref-format","--branch",h])||!await C(i,["check-ref-format","--branch",I]))return r("origin-binding-start-branch-invalid",s);const _=g(p.epics[e.epicId]),w=_?.origin_binding??y.origin_binding;if(w!=null){const x=Z(w,h,I);return x?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:x.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",s)}if(St(g(_?.branch_lease??y.branch_lease),o))return r("origin-binding-start-lease-inconsistent",s);if(n??=await Ir({projectRoot:i,originBranch:I,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,s);const E=`refs/remotes/origin/${I}`,k=`refs/heads/${I}`,S=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),R=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(S)||S!==R)return r("origin-binding-start-origin-stale",s);if((await fe(i)).some(x=>x.branch===h&&N(x.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",s);const m=`refs/heads/${h}`,D=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(D){const x=await et(i,["merge-base","--is-ancestor",S,D]);if(x===1)return r("direct-yolo-origin-not-ancestor",s);if(x!==0)return r("direct-yolo-origin-ancestry-unverifiable",s)}const b={schemaVersion:2,originBranch:I,originHeadSha:S,executionBranch:h,capturedFrom:"branch-ref",capturedAt:t};return await P(i,x=>{const A=z(x,e.epicId);if(A.origin_binding!==void 0&&A.origin_binding!==null)throw new ke("origin-binding-start-raced");if(St(g(A.branch_lease),o))throw new ke("origin-binding-start-lease-inconsistent");A.origin_binding=b},{expectedRevision:p.revision,preCommit:async()=>{const x=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),A=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>""),$=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(x!==S||A!==S||$!==D)throw new ke("origin-binding-start-raced");D||(await l(i,["update-ref",m,S,""]),u={ref:m,sha:S})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:S,outcome:"captured",executionRefCreated:u!==void 0,capturedAt:t})}catch(f){if(u&&await l(i,["update-ref","-d",u.ref,u.sha]).catch(()=>{}),f instanceof Error&&f.message==="git-lifecycle-runtime-revision-conflict"){d="origin-binding-start-raced";continue}return f instanceof ke?r(f.message,s):r("origin-binding-start-failed",s)}}return r(d)}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=T(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=t.some(i=>i.endsWith("/"))?Et(e,await H(e,["worktree","list","--porcelain","-z"])):new Set,r=await Promise.all(t.map(async i=>{if(o.has(i))return`${i}\0registered-worktree`;if(!Xe(i))throw new Error("direct-yolo-checkout-payload-invalid");try{return`${i}\0${await l(e,["hash-object","--no-filters","--",i])}`}catch{throw new Error("direct-yolo-checkout-untracked-read-failed")}}));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"]),...r].join("\0"))}async function ao(e){const t=N(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 fe(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 It=new Set(Object.values(ye));function K(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Le(e.message)||e instanceof Error&&It.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 et(e,t){try{return await ce("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 ce("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function H(e,t){return String((await ce("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function C(e,t){try{return await ce("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Qr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Qt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,wt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,Gr as acceptDirectYoloSetupCheckpoint,Kr as beginDirectYoloStoryCommit,ao as captureDirectYoloCheckoutEvidence,oo as captureDirectYoloStoryGovernance,no as captureEpicOriginBindingAtYoloopStart,Zr as directYoloCommitIdempotencyKey,Xr as directYoloWaveQaCoverage,Xt as directYoloWaveReceiptRef,Ir as fetchOriginForYoloopStart,Vr as finalizeDirectYoloStoryCheckpoint,lr as isDirectYoloWriteSetExtensionScope,Mr as issueDirectYoloSetupLeaseHandoff,ro as persistDirectYoloWaveStoryCheckpoint,Wr as prepareDirectYoloSetup,to as pushDirectYoloWaveHead,io as readYoloopStartEpic,Yr as recoverLegacyDirectYoloStoryCheckpoint,Jr as resolveDirectYoloIntegrationAuthority,eo as runDirectYoloWaveP205,Ur as validateDirectYoloWriteSet,Fr as verifyDirectYoloIntegrationCommit,Sr as yoloopStartGitNetworkExecOptions};
|
|
1
|
+
import{execFile as bt}from"node:child_process";import{createHash as kt,randomBytes as Ae,timingSafeEqual as Dt}from"node:crypto";import{existsSync as pe}from"node:fs";import{readFile as V,realpath as ce}from"node:fs/promises";import{join as X,resolve as N}from"node:path";import{promisify as Et}from"node:util";import{registeredNestedWorktreeDirectories as jt}from"./worktree-checkout-boundary.js";import{rootProjectMemoryPaths as At}from"../private-execution/shared-root-memory-types.js";import{readRootMemoryEffectForCheckpoint as _e}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as ot,verifyRootMemoryPhysicalWriteSet as Be}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as _t,resolveEpicStoryIds as Bt}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as Ce,storyWriteSetCovers as He,validateStoryWriteScope as Ct}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as Oe,computeImmutableStoryQaEvidenceDigest as Ht,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as le,computeP205StoryQaEvidenceDigest as Ot,computeLegacyDirectYoloRecoveryReceiptRef as $t,ensureRuntimeEpic as z,ensureRuntimeStory as $e,ensureGitLifecyclePrivateChildDirectory as Le,executeP205TransientAuthorities as Lt,executeP205TransientAuthority as Nt,isP226GateReasonCode as Ne,projectP205TransientExecutionEvidence as it,publicStoryReviewArtifactFromBytes as Pt,publicStoryReviewArtifactFromGit as he,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as qt,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as nt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as Pe,STORY_WRITE_SET_MAX_ENTRIES as at,storyWriteSetExtensionPaths as Tt,assertGitLifecyclePrivateFile as ee,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as zt,verifyGitLifecyclePhysicalIntegrationLock as ye,verifyAcceptedGitLifecycleStoryCheckpoint as qe}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as Te,anchoredRemoveFile as ct}from"./secure-filesystem-boundary.js";import{GOVERNANCE_CHECKPOINT_TRAILER_KEYS as st,GOVERNANCE_DIGEST_TRAILER as dt,GOVERNANCE_REASON_CODES as ge,captureStoryGovernanceSync as Wt,detectGovernanceModeSync as Gt,governanceReceiptRefs as Mt,isGovernanceRepositoryPath as Kt,readGovernanceStateSourceSync as Vt,storyReviewGovernancePath as Ft,verifyStoryGovernanceBinding as Yt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ft,trailerReasonKey as se,trailerValue as J}from"./neocortex-trailers.js";import{StoryWorktreeManager as Jt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ut,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ut,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as W}from"./git-lifecycle-step-ids.js";const de=Et(bt),fe=3600*1e3;async function Gr(e){let t,o=!1;try{const r=await ve(e.projectRoot,e.storyId);if(await we(r)){if(e.expiredSetupRecovery)return a("direct-yolo-expired-setup-recovery-invalid");const S=await lt(r);return{ok:!0,value:ht(r,S,!1)}}const i=q(e.nowIso),n=Date.parse(i),d=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),u=await O(r.projectRoot,{required:!0}),s=g(u.epics[r.epicId]),f=g(s?.branch_lease),p=e.expiredSetupRecovery;if(p&&!yr(p,u.revision,f,e.storyId,n))return a("direct-yolo-expired-setup-recovery-invalid");const v=f&&Number.isFinite(Date.parse(String(f.expiresAt)))&&Date.parse(String(f.expiresAt))>n;if(v&&f?.ownerStoryId!==e.storyId)return a("direct-yolo-writer-active");let y=Z(s?.origin_binding,r.executionBranch,r.originBranch),h;if(d===r.executionBranch){if(!y){if(s?.origin_binding!==void 0&&s?.origin_binding!==null||v)return a("direct-yolo-origin-binding-invalid");const S=await vr(r,c,i);if(!S.ok)return S;y=S.value.binding,h={originRef:S.value.originRef,originHeadSha:S.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return a("direct-yolo-current-branch-mismatch");if(y&&y.originHeadSha!==c){if(!p||!await C(r.projectRoot,["merge-base","--is-ancestor",y.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 D=await l(r.projectRoot,["rev-parse",m]);if(!await C(r.projectRoot,["merge-base","--is-ancestor",D,c]))return a("direct-yolo-execution-branch-diverged")}if(y??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await ae(r.projectRoot)).some(m=>m.branch===r.executionBranch&&N(m.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const R=await G(r.projectRoot),j=`refs/heads/${r.executionBranch}`;if(await C(r.projectRoot,["show-ref","--verify","--quiet",j])){const m=await l(r.projectRoot,["rev-parse",j]);if(m!==c){if(!await C(r.projectRoot,["merge-base","--is-ancestor",m,c]))return a("direct-yolo-execution-branch-diverged");p||await l(r.projectRoot,["update-ref",j,c,m])}p?t={checkoutBefore:R,executionRef:j,executionBranch:r.executionBranch,executionHead:m,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(p)return a("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await G(r.projectRoot)!==R)return a("direct-yolo-checkout-payload-raced")}const I=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(v&&f?.ownerStoryId===e.storyId)return f.setupHeadSha!==I?a("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:je(r,y,String(f.expiresAt),!0)};const _=i,w=new Date(n+3600*1e3).toISOString(),E=`setup-${Ae(32).toString("hex")}`,k=p?u:await O(r.projectRoot,{required:!0});return await P(r.projectRoot,S=>{const R=z(S,r.epicId),j=g(R.branch_lease);if(p&&JSON.stringify(j)!==JSON.stringify(p.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(j&&Date.parse(String(j.expiresAt))>n&&j.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const m=Z(R.origin_binding,r.executionBranch,r.originBranch);if(R.origin_binding&&!m)throw new Error("direct-yolo-origin-binding-conflict");if(m&&JSON.stringify(m)!==JSON.stringify(y))throw new Error("direct-yolo-origin-binding-conflict");R.branch_mode="epic",R.execution_branch=r.executionBranch,R.origin_branch=r.originBranch,R.graph_revision=r.graphRevision,R.origin_binding=y,R.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:E,idempotencyKey:E,acquiredAt:_,expiresAt:w,setupHeadSha:I}},{expectedRevision:p?.expectedRuntimeRevision??k.revision,preCommit:async()=>{if(t){if((await ae(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.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"])!==I||await we(r))throw new Error("direct-yolo-setup-physical-state-raced");if(h&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${h.originRef}^{commit}`]).catch(()=>"")!==h.originHeadSha||await et(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,I])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:je(r,y,w,!1)}}catch(r){return o&&t&&await gr(N(e.projectRoot),t).catch(()=>{}),a(K(r,"direct-yolo-setup-failed"))}}async function Mr(e){let t;try{const o=await ve(e.projectRoot,e.storyId);if(await we(o))return await Qt(o,q(e.nowIso));const r=await U(e.projectRoot,e.storyId),i=q(e.nowIso),n=X(r.projectRoot,".neocortex/state.json"),d=await V(n,"utf8"),c=await G(r.projectRoot),u=await l(r.projectRoot,["rev-parse","HEAD"]),s=`refs/heads/${r.executionBranch}`,f=await O(r.projectRoot,{required:!0}),p=g(f.epics[r.epicId]),v=Z(p?.origin_binding,r.executionBranch,r.originBranch),y=g(p?.branch_lease);if(!v)return a("direct-yolo-origin-binding-invalid");if(!y||!Je(y,e.storyId,i)||y?.sessionId!==y?.idempotencyKey)return a("direct-yolo-setup-lease-invalid");const h=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(y.sessionId),idempotencyKey:String(y.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!h.ok)return a(h.reasonCode);if(t=h,u!==y.setupHeadSha||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)return a("direct-yolo-setup-head-mismatch");if((await ae(r.projectRoot)).some(R=>R.branch===r.executionBranch&&N(R.path)!==r.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const _=g(JSON.parse(d)),w=g(g(_?.stories)?.[e.storyId]),E=g(f.stories[e.storyId]);if(!w||!["backlog","ready_to_start"].includes(String(w.status))||w.steps_completed!==void 0&&(!Array.isArray(w.steps_completed)||w.steps_completed.length>0)||w.branch_name||w.checkpoint)return a("direct-yolo-setup-story-progress-conflict");const k=E?.status==="branch-ready"&&E.last_step===W&&Array.isArray(E.steps_completed)&&E.steps_completed.length===1&&E.steps_completed[0]===W&&oe(E).sort().join(",")==="last_step,status,steps_completed";if(E&&oe(E).length>0&&!k)return a("direct-yolo-setup-story-progress-conflict");const S=async()=>{if(Date.parse(String(y.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await ye(t.path,t.owner)||await V(n,"utf8")!==d||await G(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==u||await we(r)||!await C(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,u])||await l(r.projectRoot,["rev-parse",s])!==u)throw new Error("direct-yolo-setup-physical-state-raced")};return k?await S():await P(r.projectRoot,R=>{const j=g(R.epics[r.epicId]),m=$e(R,e.storyId);if(JSON.stringify(j?.branch_lease)!==JSON.stringify(y)||JSON.stringify(j?.origin_binding)!==JSON.stringify(v)||j?.graph_revision!==r.graphRevision||oe(m).length>0)throw new Error("direct-yolo-setup-runtime-raced");m.status="branch-ready",m.last_step=W,m.steps_completed=[W]},{expectedRevision:f.revision,preCommit:S}),{ok:!0,value:Object.freeze({...je(r,v,String(y.expiresAt),k),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:u})}}catch(o){return a(K(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function Kr(e){try{const t=await U(e.projectRoot,e.storyId),o=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),r=re(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!r.ok)return a(r.reasonCode);t.rootMemoryEffect&&Be(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"?Ge(t):void 0;if((i?i.review:he(t.projectRoot,e.storyId,":"))?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>o.includes(b)))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 u=B(c),s=B([...t.authorizedWriteSet].sort().join("\0")),f=q(e.nowIso),p=await O(t.projectRoot,{required:!0});let v=g(p.epics[t.epicId]?.branch_lease),y;if(!Je(v,e.storyId,f)){const x=v!==void 0&&Date.parse(String(v.expiresAt))>Date.parse(f)?void 0:await mt(t.projectRoot,p,t.epicId,e.storyId,f);if(!x||!await C(t.projectRoot,["merge-base","--is-ancestor",x.setupHeadSha,"HEAD"]))return a("direct-yolo-setup-handoff-owner-invalid");y=x,v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:x.sessionId,idempotencyKey:x.idempotencyKey,acquiredAt:f,expiresAt:new Date(Math.min(Date.parse(x.expiresAt),Date.parse(f)+ir)).toISOString(),setupHeadSha:x.setupHeadSha}}const h=String(v.sessionId),I=String(v.expiresAt),_=new Date(Math.min(Date.parse(I),Date.parse(f)+300*1e3)).toISOString(),w=await te(t.projectRoot,e.storyId),E=w?.state==="issued"&&w.fromSessionId===h&&w.bundleDigest===u&&w.claimRevision===s&&Date.parse(w.expiresAt)>Date.parse(f),k=E?w.expiresAt:_,S=E?w.token:Ae(32).toString("base64url"),R=B(S),j=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:h,tokenDigest:R,bundleDigest:u,claimRevision:s,expiresAt:k}),m=B(JSON.stringify(j)),D=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!1,createdAt:f});if(!D.ok)return a(D.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await Ze(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:h,token:S,tokenDigest:R,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k}),await P(t.projectRoot,b=>{const x=z(b,t.epicId);if(y){const $=g(x.branch_lease);if($&&Date.parse(String($.expiresAt))>Date.parse(f))throw new Error("direct-yolo-setup-handoff-owner-raced");x.branch_lease={...v}}const A=g(x.branch_lease);if(!Je(A,e.storyId,f)||A?.sessionId!==h||A.idempotencyKey!==h)throw new Error("direct-yolo-setup-handoff-owner-raced");A.handoffGrant=j},{expectedRevision:p.revision,preCommit:async()=>{if(!await ye(D.path,D.owner))throw new Error("direct-yolo-integration-lock-raced");const b=await te(t.projectRoot,e.storyId);if(!b||b.state!=="issued"||b.grantDigest!==m||b.tokenDigest!==R)throw new Error("direct-yolo-setup-handoff-token-raced");if(y&&(await gt(t.projectRoot,e.storyId))?.sessionId!==y.sessionId)throw new Error("direct-yolo-setup-handoff-owner-raced")}}),y&&await ar(t.projectRoot,e.storyId)}finally{await Y(D.path,D.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:h,bundleDigest:u,claimRevision:s,grantDigest:m,expiresAt:k,reused:E,publicSafe:!0,...i?{governance:i.receipt}:{}})}}catch(t){return a(t instanceof Error&&(/^direct-yolo-/.test(t.message)||xt.has(t.message))?t.message:"direct-yolo-setup-handoff-failed")}}async function Vr(e){try{const t=await U(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=T(await H(t.projectRoot,["diff","--cached","--name-only","-z"])),i=re(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect,t.governanceMode);if(!i.ok)return a(i.reasonCode);t.rootMemoryEffect&&Be(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=t.governanceMode==="runtime-store"?Ge(t):void 0,d=n?n.review:he(t.projectRoot,e.storyId,":");if(d?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");if(T(await H(t.projectRoot,["diff","--name-only","-z"])).some(b=>r.includes(b)))return a("direct-yolo-user-overlap");const u=await H(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!u)return a("direct-yolo-staged-diff-empty");const s=B(u),f=B([...t.authorizedWriteSet].sort().join("\0")),p=await Ye(t.projectRoot,e.storyId),v=p.state==="valid"&&p.plan.epicId===t.epicId&&p.plan.executionBranch===t.executionBranch&&p.plan.preparedBase===o&&p.plan.bundleDigest===s&&p.plan.claimRevision===f?p.plan:void 0,y=v?.graphRevision??t.graphRevision,h=Ve({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:s,graphRevision:y,claimRevision:f}),I=q(e.nowIso),_={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:y,preparedBase:o,bundleDigest:s,claimRevision:f,idempotencyKey:h,issuedAt:v?.issuedAt??I};let w=e.setupLeaseHandoff??await cr(t.projectRoot,e.storyId,s,f,I);const E=await O(t.projectRoot,{required:!0}),k=g(E.epics[t.epicId]?.branch_lease),S=k?.ownerStoryId===e.storyId&&k.sessionId===h&&k.idempotencyKey===h&&typeof k.expiresAt=="string"&&Date.parse(k.expiresAt)>Date.parse(I)?k:void 0;if(S&&e.setupLeaseHandoff)return a("direct-yolo-setup-handoff-replayed");const R=g(S?.handoffConsumption);if(R){const b=await te(t.projectRoot,e.storyId);if(!b||!["consuming","consumed"].includes(b.state)||b.fromSessionId!==R.fromSessionId||b.tokenDigest!==R.tokenDigest||b.bundleDigest!==s||b.claimRevision!==f||R.bundleDigest!==s||R.claimRevision!==f||b.consumedBySessionId!==h||R.consumedBySessionId!==h)return a("direct-yolo-setup-handoff-consume-invalid");if(b.state==="consuming"){if(!b.token||B(b.token)!==b.tokenDigest)return a("direct-yolo-setup-handoff-consume-invalid");w={sessionId:b.fromSessionId,token:b.token}}}const j=S?String(S.expiresAt):new Date(Date.parse(I)+fe).toISOString(),m=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:j,persistent:!0,createdAt:S&&typeof S.acquiredAt=="string"?S.acquiredAt:I});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{w&&e.setupLeaseHandoff===void 0&&(await sr(t.projectRoot,e.storyId,w.sessionId,w.token,h,I),await e.setupHandoffFault?.("after-consuming-persisted")),await P(t.projectRoot,b=>{const x=z(b,t.epicId),A=g(x.branch_lease),$=A&&Date.parse(String(A.expiresAt))>Date.parse(I),L=A?.ownerStoryId===e.storyId&&A.sessionId===h&&A.idempotencyKey===h,M=A?.ownerStoryId===e.storyId&&A.sessionId===A.idempotencyKey&&typeof A.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(A.idempotencyKey),Q=$&&M&&fr({current:A,handoff:w,storyId:e.storyId,bundleDigest:s,claimRevision:f,nowIso:I});if(w&&$&&!L&&!Q)throw new Error("direct-yolo-setup-handoff-invalid");if($&&!L&&!Q)throw new Error("direct-yolo-writer-active");const tt=Q?g(A?.handoffGrant):void 0,rt=tt?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(A?.sessionId),tokenDigest:String(tt.tokenDigest),bundleDigest:s,claimRevision:f,consumedBySessionId:h,consumedAt:I}:void 0;x.branch_mode="epic",x.execution_branch=t.executionBranch,x.origin_branch=t.originBranch,x.graph_revision=t.graphRevision,x.branch_lease=$&&L?A:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:I,expiresAt:j,...rt?{handoffConsumption:rt}:{}}},{expectedRevision:E.revision,preCommit:async()=>{if(!await ye(m.path,m.owner))throw new Error("direct-yolo-integration-lock-raced");await rr(t.projectRoot,_)}})}catch(b){throw await Y(m.path,m.owner).catch(()=>{}),b}w&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await dr(t.projectRoot,t.epicId,e.storyId,w.sessionId,w.token,s,f,h,I));const D=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: ${d.digest}`,`Neocortex-Graph-Revision: ${y}`,`Neocortex-Claim-Revision: ${f}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ot(t.rootMemoryEffect)}`]:[],...n?[`${dt}: ${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:d.digest,graphRevision:y,claimRevision:f,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:D,...n?{governance:n.receipt}:{}})}}catch(t){return a(K(t,"direct-yolo-begin-failed"))}}async function Fr(e){let t,o,r;try{const i=await U(e.projectRoot,e.storyId);t=i;const n=e.preFastForwardAuthorizedWriteSet;if(n!==void 0&&!ze(n))return a("direct-yolo-write-set-invalid");const d=n??i.authorizedWriteSet,c=await l(i.projectRoot,["rev-parse","HEAD"]);let u=await O(i.projectRoot,{required:!0});const s=g(u.stories[e.storyId]?.checkpoint);if(s){const D=typeof s.headSha=="string"?s.headSha:"",b=typeof s.graphRevision=="string"?s.graphRevision:"",x=/^[a-f0-9]{40,64}$/.test(D)?T(await H(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",D])):[],A=re(x,d,e.storyId,i.rootMemoryEffect,i.governanceMode);if(!(/^[a-f0-9]{40,64}$/.test(D)&&await C(i.projectRoot,["merge-base","--is-ancestor",D,c]))||!/^[a-f0-9]{64}$/.test(b)||!A.ok)return a("direct-yolo-replay-invalid");const L=await be(e,i.projectRoot,c,b);if(!await qe(i.projectRoot,s,e.storyId,i.epicId,i.executionBranch,L.transientAuthority,d))return a("direct-yolo-replay-invalid");if(!await ke(i.projectRoot,i.executionBranch,c,x))return a("direct-yolo-replay-head-raced");if(e.push&&!await Ke(i.projectRoot,e.remote??"origin",i.executionBranch,D))return a("direct-yolo-remote-head-mismatch");const M=Array.isArray(s.receiptRefs)?s.receiptRefs.find(Q=>typeof Q=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(Q)):void 0;return M&&typeof s.idempotencyKey=="string"&&await zt(i.projectRoot,{storyId:e.storyId,idempotencyKey:s.idempotencyKey,ownerDigest:M.slice(20)}),await ue(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:s}}const f=c,p=await me(i,e.storyId,f,n?{claimWriteSet:n}:{});if(!p.ok)return a(p.reasonCode);const{baseSha:v,changedPaths:y,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,governance:E}=p.value,k=g(u.epics[i.epicId]?.branch_lease),S=q(e.nowIso),R=k?.ownerStoryId===e.storyId&&k.idempotencyKey===w&&k.sessionId===w&&Date.parse(String(k.expiresAt))>Date.now()?k:void 0;if(k&&Date.parse(String(k.expiresAt))>Date.now()&&!R)return a("direct-yolo-writer-active");const j=R??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:w,idempotencyKey:w,acquiredAt:S,expiresAt:new Date(Date.parse(S)+fe).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return a(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,R||(u=(await P(i.projectRoot,b=>{const x=z(b,i.epicId),A=g(x.branch_lease);if(A&&Date.parse(String(A.expiresAt))>Date.parse(S))throw new Error("direct-yolo-writer-active");if(x.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");x.branch_lease=j},{expectedRevision:u.revision})).document),o=j;{const D=await be(e,i.projectRoot,f,I);if(!await ke(i.projectRoot,i.executionBranch,f,y))return a("direct-yolo-head-raced");if(e.push){const A=ne(e.remote??"origin");if(await l(i.projectRoot,["push",A,i.executionBranch]),!await Qe(i.projectRoot,A,i.executionBranch,f))return a("direct-yolo-remote-head-mismatch")}const b=await Re({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:v,headSha:f,bundleDigest:h,graphRevision:I,claimRevision:_,idempotencyKey:w,qaExecution:D,physicalLockOwnerDigest:le(m.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect,...E?{governance:E}:{}});return await e.beforeCheckpointPersist?.(),await Se({projectRoot:i.projectRoot,checkpoint:b,remote:e.push?e.remote??"origin":void 0,expectedRevision:u.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:I,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:D.transientAuthority,authorizedWriteSet:d})?(await ue(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:b}):a("direct-yolo-checkpoint-persist-failed")}}catch(i){return a(K(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await xe(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await pr(t,e.storyId).catch(()=>{})}}function ze(e){return Array.isArray(e)&&e.length>0&&e.length<=at&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=512)}async function Yr(e,t,o,r={}){try{return/^[a-f0-9]{40,64}$/.test(o)?await me(e,t,o,{claimWriteSet:e.authorizedWriteSet,...r.expectedGraphRevision!==void 0?{expectedGraphRevision:r.expectedGraphRevision}:{}}):a("direct-yolo-recovery-commit-invalid")}catch(i){return a(K(i,"direct-yolo-commit-verification-failed"))}}async function me(e,t,o,r={}){if(r.claimWriteSet!==void 0&&!ze(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}^`]),d=await H(e.projectRoot,["show","--no-patch","--format=%B",o]),c=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),u=re(c,i,t,e.rootMemoryEffect,e.governanceMode);if(!u.ok)return a(u.reasonCode);e.rootMemoryEffect&&Be(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:n,headRef:o,childPaths:i});const s=B([...i].sort().join("\0")),f=await Ye(e.projectRoot,t);if(f.state==="invalid")return a("direct-yolo-commit-plan-invalid");const p=f.state==="valid"?f.plan:void 0;if(p&&(p.epicId!==e.epicId||p.executionBranch!==e.executionBranch))return a("direct-yolo-commit-plan-invalid");if(p&&p.claimRevision!==s)return a("direct-yolo-commit-plan-claim-changed");if(p&&p.preparedBase!==n)return a("direct-yolo-commit-plan-base-mismatch");const v=ft(d,st);if(!v.ok)return a(`direct-yolo-trailer-duplicate:${v.key}`);const y=v.values;if(r.expectedGraphRevision!==void 0&&p&&p.graphRevision!==r.expectedGraphRevision)return a(`direct-yolo-trailer-mismatch:${se("Neocortex-Graph-Revision")}`);const h=r.expectedGraphRevision??p?.graphRevision??e.graphRevision,I=s,_=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",n],["Neocortex-Bundle-Digest",p?.bundleDigest??""],["Neocortex-Graph-Revision",h],["Neocortex-Claim-Revision",I]];for(const[D,b]of _){const x=J(y,D);if(x===void 0)return a(`direct-yolo-trailer-missing:${se(D)}`);if(D==="Neocortex-Bundle-Digest"&&!p){if(!/^[a-f0-9]{64}$/.test(x))return a(`direct-yolo-trailer-mismatch:${se(D)}`);continue}if(x!==b)return a(`direct-yolo-trailer-mismatch:${se(D)}`)}const w=J(y,"Neocortex-Bundle-Digest"),E=J(y,dt);if(e.governanceMode!=="runtime-store"&&E!==void 0)return a(ge.MISMATCH);const k=e.governanceMode==="runtime-store"?Me({projectRoot:e.projectRoot,epicId:e.epicId,storyId:t},E):void 0,S=k?k.review:he(e.projectRoot,t,o);if(S?.verdict!=="approved")return a("direct-yolo-review-artifact-not-approved");const R=J(y,"Neocortex-Review-Artifact-Digest");if(R!==void 0&&R!==S.digest)return a("direct-yolo-review-artifact-digest-mismatch");const j=B(await H(e.projectRoot,["diff","--binary","--full-index",`${n}..${o}`]));if(w!==j)return a("direct-yolo-bundle-digest-mismatch");const m=Ve({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:n,bundleDigest:w,graphRevision:h,claimRevision:I});return p&&p.idempotencyKey!==m?a("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:n,changedPaths:c,bundleDigest:w,graphRevision:h,claimRevision:I,idempotencyKey:m,...k?{governance:k.receipt}:{}}}}async function Jr(e){try{const t=await U(e.projectRoot,e.storyId,!1);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(qt[e.storyId]!==o)return await Zt(e,t,o);if(await _e({...t,childPaths:t.authorizedWriteSet}),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=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!re(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return a("direct-yolo-recovery-write-set-invalid");const c=B(i),u=B([...n].sort().join("\0")),s=B(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),f=q(e.nowIso),p=new Date(Date.parse(f)+fe).toISOString(),v=await O(t.projectRoot,{required:!0}),y=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:s,idempotencyKey:s,expiresAt:p,persistent:!0,createdAt:f});if(!y.ok)return a(y.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const h={schemaVersion:1,ownerStoryId:e.storyId,sessionId:s,idempotencyKey:s,acquiredAt:f,expiresAt:p};let I=!1;try{const _=await P(t.projectRoot,j=>{const m=z(j,t.epicId),D=g(m.branch_lease);if(D&&Date.parse(String(D.expiresAt))>Date.parse(f)&&!Ie(D,h))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=h},{expectedRevision:v.revision});I=!0;const w=await be(e,t.projectRoot,o,t.graphRevision);if(!await ke(t.projectRoot,t.executionBranch,o,n))return a("direct-yolo-recovery-head-raced");if(e.push){const j=ne(e.remote??"origin"),m=(await l(t.projectRoot,["ls-remote","--heads",j,`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 E=await Re({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:u,idempotencyKey:s,qaExecution:w,physicalLockOwnerDigest:le(y.owner),nowIso:f,legacyReceiptRef:void 0}),k=await $t(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!k)return a("direct-yolo-recovery-evidence-invalid");const S=Object.freeze({...E,receiptRefs:Object.freeze([...E.receiptRefs,k])});return await Se({projectRoot:t.projectRoot,checkpoint:S,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:_.document.revision,expectedLease:h,expectedGraphRevision:t.graphRevision,physicalLockPath:y.path,physicalLockOwner:y.owner,transientAuthority:w.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:S}:a("direct-yolo-recovery-persist-failed")}finally{await Y(y.path,y.owner).catch(()=>{}),I&&await xe(t.projectRoot,t.epicId,h).catch(()=>{})}}catch(t){return a(K(t,"direct-yolo-recovery-failed"))}}async function Zt(e,t,o){const r=await H(t.projectRoot,["show","--no-patch","--format=%B",o]),i=ft(r,st);if(!i.ok||J(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=J(i.values,"Neocortex-Root-Memory-Effect");let d=t.graphRevision;if(n!==void 0){if(!/^[a-f0-9]{64}$/.test(n))return a("direct-yolo-recovery-root-governance-unverified");const D=await Ye(t.projectRoot,e.storyId);if(D.state==="invalid")return a("direct-yolo-commit-plan-invalid");if(D.state==="valid"&&(d=D.plan.graphRevision),J(i.values,"Neocortex-Graph-Revision")!==d)return a(`direct-yolo-trailer-mismatch:${se("Neocortex-Graph-Revision")}`)}let c;try{c=await _e({...t,graphRevision:d,childPaths:t.authorizedWriteSet})}catch{return a("direct-yolo-recovery-root-governance-unverified")}if((c?ot(c):void 0)!==n)return a("direct-yolo-recovery-root-governance-unverified");const u=await me({...t,rootMemoryEffect:c},e.storyId,o);if(!u.ok){if(u.reasonCode==="direct-yolo-write-set-unauthorized"){const D=T(await H(t.projectRoot,["diff-tree","--no-commit-id","--name-only","--no-renames","-r","-z",o])),b=new Set([...At(),`docs/epics/epic-${t.epicId}.md`]);if(D.some(x=>b.has(x)&&!He(t.authorizedWriteSet,x)&&!c?.files.some(A=>A.path===x)))return a("direct-yolo-recovery-root-governance-unverified")}return a(u.reasonCode)}const{baseSha:s,changedPaths:f,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,governance:I}=u.value,_=ne(e.remote??"origin");let w=!1;try{w=await Ke(t.projectRoot,_,t.executionBranch,o)}catch{w=!1}if(!w)return a("direct-yolo-recovery-remote-proof-missing");const E=q(e.nowIso),k=new Date(Date.parse(E)+fe).toISOString(),S=await O(t.projectRoot,{required:!0});if(g(S.stories[e.storyId]?.checkpoint))return a("direct-yolo-checkpoint-conflict");const R=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:k,persistent:!0,createdAt:E});if(!R.ok)return a(R.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const j={schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:E,expiresAt:k};let m=!1;try{const D=await P(t.projectRoot,$=>{const L=z($,t.epicId),M=g(L.branch_lease);if(M&&Date.parse(String(M.expiresAt))>Date.parse(E)&&!Ie(M,j))throw new Error("direct-yolo-recovery-writer-active");if(L.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");L.branch_mode="epic",L.execution_branch=t.executionBranch,L.origin_branch=t.originBranch,L.branch_lease=j},{expectedRevision:S.revision});m=!0;const b=await be(e,t.projectRoot,o,v);if(!await ke(t.projectRoot,t.executionBranch,o,f))return a("direct-yolo-recovery-head-raced");const x=await Re({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:s,headSha:o,bundleDigest:p,graphRevision:v,claimRevision:y,idempotencyKey:h,qaExecution:b,physicalLockOwnerDigest:le(R.owner),nowIso:E,legacyReceiptRef:void 0,rootMemoryEffect:c,...I?{governance:I}:{}});return await Se({projectRoot:t.projectRoot,checkpoint:x,remote:_,remotePolicy:"ancestor-recovery",expectedRevision:D.document.revision,expectedLease:j,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:v,physicalLockPath:R.path,physicalLockOwner:R.owner,transientAuthority:b.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?(await ue(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:x}):a("direct-yolo-recovery-persist-failed")}finally{await Y(R.path,R.owner).catch(()=>{}),m&&await xe(t.projectRoot,t.epicId,j).catch(()=>{})}}async function pt(e){const t=await ce(await l(e,["rev-parse","--absolute-git-dir"])),o=await ce(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function we(e){const{projectRoot:t,executionBranch:o}=e;if(!await pt(t))return!1;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==o)return!0;const i=await ce(t),n=await O(t,{required:!0});if(Object.values(n.storyWorktrees?.entries??{}).some(u=>N(u.worktreePath)===i||u.storyId===e.storyId&&Date.parse(u.expiresAt)>Date.now()))return!0;const c=(await ae(t)).filter(u=>u.branch===o);if(c.length!==1||await ce(c[0].path)!==i)throw new Error("direct-yolo-execution-branch-checked-out-elsewhere");return!1}async function lt(e){const t=await O(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(p=>p.storyId===e.storyId&&p.epicId===e.epicId&&p.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 ce(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 d=await new Jt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=Z(g(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const u=r.syncedSha??r.baseSha,s=await l(e.projectRoot,["rev-parse","HEAD"]),f=`refs/heads/${e.executionBranch}`;if(s!==u||!await C(e.projectRoot,["merge-base","--is-ancestor",u,f])||!await C(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,u]))throw new Error("direct-yolo-worktree-base-divergent");if(d.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:u,headSha:s,expiresAt:r.expiresAt,binding:c}}function ht(e,t,o){return Object.freeze({...je(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Qt(e,t){const o=await lt(e),r=We(e.projectRoot),i=g(JSON.parse(r)),n=g(g(i?.stories)?.[e.storyId]),d=await O(e.projectRoot,{required:!0}),c=g(d.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 u=c?.status==="branch-ready"&&c.last_step===W&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===W&&oe(c).sort().join(",")==="last_step,status,steps_completed";if(c&&oe(c).length>0&&!u)return a("direct-yolo-setup-story-progress-conflict");u||await P(e.projectRoot,p=>{const v=$e(p,e.storyId);if(oe(v).length>0)throw new Error("direct-yolo-setup-runtime-raced");v.status="branch-ready",v.last_step=W,v.steps_completed=[W]},{expectedRevision:d.revision,preCommit:async()=>{if(We(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}),f=await mt(e.projectRoot,s,e.epicId,e.storyId,t);if(f?.leaseId!==o.leaseId||f.setupHeadSha!==o.headSha){const p=`setup-${Ae(32).toString("hex")}`;await nr(e.projectRoot,{schemaVersion:1,kind:yt,epicId:e.epicId,ownerStoryId:e.storyId,sessionId:p,idempotencyKey:p,leaseId:o.leaseId,acquiredAt:t,expiresAt:o.expiresAt,setupHeadSha:o.headSha})}return{ok:!0,value:Object.freeze({...ht(e,o,u),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:o.headSha})}}async function Ur(e,t){const o=await U(e,t),r=await O(o.projectRoot,{required:!0}),i=Z(g(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function Zr(e,t,o,r,i="tracked"){return re(e,t,o,r,i)}function Qr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Xr=fe,Xt="p205-wave:";function eo(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 er(e){return`${Xt}${e.waveHeadSha}:${e.waveDigest}`}async function to(e){let t;try{t=await Lt(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:Ne(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:Ne(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function ro(e,t,o,r){const i=ne(t);return await l(e,["push",i,o]),Qe(e,i,o,r)}async function oo(e){try{const t=await U(e.projectRoot,e.storyId);if(e.authorizedWriteSet!==void 0&&!ze(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}),d=g(n.stories[e.storyId]?.checkpoint);if(d){if(d.headSha!==e.headSha)return a("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(d.graphRevision));return await qe(t.projectRoot,d,e.storyId,t.epicId,t.executionBranch,k??null,o)?(await ue(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:d}):a("direct-yolo-replay-invalid")}const c=await me(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:u,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,governance:y}=c.value,h=i===0?void 0:e.coverage.waveCommitShas[i-1];if(h!==void 0&&u!==h)return a("direct-yolo-wave-chain-invalid");const I=e.authorities.get(f),_=it(I);if(!I||!_||_.executionHeadSha!==r||_.graphRevision!==f)return a("direct-yolo-wave-qa-unbound");const w=await Re({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:u,headSha:e.headSha,bundleDigest:s,graphRevision:f,claimRevision:p,idempotencyKey:v,qaExecution:{contract:"P205-CI-02",command:nt,manifestDigest:_.manifestDigest,gateIds:_.gateIds,resultDigest:_.resultDigest,transientAuthority:I},physicalLockOwnerDigest:le(e.physicalLock.owner),nowIso:q(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[er(e.coverage)],...y?{governance:y}:{}});return await Se({projectRoot:t.projectRoot,checkpoint:w,remote:e.remote,expectedRevision:n.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:f,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:I,authorizedWriteSet:o,expectedHeadSha:r,keepLease:!0})?(await ue(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:w}):a("direct-yolo-checkpoint-persist-failed")}catch(t){return a(K(t,"direct-yolo-wave-persist-failed"))}}async function ve(e,t,o=!0){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const r=N(e),i=g(JSON.parse(We(r))),n=await O(r,{required:!0}),d=Oe(i,n),c=Gt({projectRoot:r,storyId:t});if(!c.ok)throw new Error(c.reasonCode);const u=c.mode,s=g(d.stories),f=g(d.epics),p=g(s?.[t]),v=String(p?.epic_id??t.split(".")[0]),y=g(f?.[v]),h=String(y?.execution_branch??""),I=String(y?.origin_branch??""),_=String(y?.graph_revision??""),w=Array.isArray(p?.files_to_modify)?p.files_to_modify:[],E=Tt(p).filter(hr),k=[...w,...E],S=k.length>0?Ce(t,k):void 0,R=S?.ok?S.scopes:[];if(!p)throw new Error("direct-yolo-story-state-missing");if(E.length>0&&R.length>at)throw new Error("direct-yolo-write-set-too-large");if(y?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!ie(h)||!await C(r,["check-ref-format","--branch",h]))throw new Error("direct-yolo-execution-branch-invalid");if(!ie(I)||!await C(r,["check-ref-format","--branch",I]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(_))throw new Error("direct-yolo-graph-revision-invalid");const j=o?await _e({projectRoot:r,storyId:t,graphRevision:_,executionBranch:h,childPaths:R}):void 0;return{projectRoot:r,storyId:t,story:p,epicId:v,executionBranch:h,originBranch:I,graphRevision:_,authorizedWriteSet:R,rootMemoryEffect:j,governanceMode:u}}async function io(e){try{const t=await ve(e.projectRoot,e.storyId);return t.governanceMode!=="runtime-store"?a("governance-capture-not-applicable"):await pt(t.projectRoot)?a("governance-capture-root-required"):{ok:!0,value:Ge(t).receipt}}catch(t){return a(K(t,"governance-capture-failed"))}}function We(e){const t=Vt(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 Ge(e){const t=Wt(e);if(!t.ok)throw new Error(t.reasonCode);return Me(e,t.value.governanceDigest)}function Me(e,t){const o=Yt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Ft(e.storyId));if(!r)throw new Error(ge.MISMATCH);return{receipt:o.value.receipt,review:Pt(e.storyId,r)}}async function U(e,t,o=!0){const r=await ve(e,t,o);if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return r}async function Re(e){const t=e.nowIso,o=await H(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=T(await H(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=Ht({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ot({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}),u=e.governance?Me(e,e.governance.governanceDigest).review:he(e.projectRoot,e.storyId,e.headSha);if(u?.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,d,B(o),[...r].sort().join(","),u.digest].join("\0")),f=`story-review:${s}`,p=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:u.digest,qaReceiptRef:d,verdict:"approved",reviewedAt:t,receiptRef:f}),v=[`.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?Mt(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(v),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:p,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function Se(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await P(t,n=>{const d=z(n,o.epicId);if(e.expectedLease){const f=g(d.branch_lease);if(!Ie(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=$e(n,o.storyId),u=g(c.checkpoint);if(u&&u.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=ut;const s=Array.isArray(c.steps_completed)?c.steps_completed.filter(f=>typeof f=="string"):[];c.steps_completed=[...new Set([...s,Ut,ut])],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 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 qe(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 ye(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Ke(t,r,o.branch,o.headSha):await Qe(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Ke(e,t,o,r){const i=ne(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 Ve(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const tr=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function Fe(e,t){const o=await Pe(e),r=await Le(o,"commit-plans"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function rr(e,t){const o=await Fe(e,t.storyId);await Te(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`),await ee(o.path,o.parent)}async function Ye(e,t){let o;try{o=await Fe(e,t)}catch{return{state:"invalid"}}try{if(!pe(o.path))return{state:"absent"};await ee(o.path,o.parent);const r=await V(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")!==[...tr].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!ie(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!==Ve({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ue(e,t){const o=await Fe(e,t);pe(o.path)&&await ct(o.parent,o.name)}function Je(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 yt="direct-yolo-worktree-setup-reservation",or=["schemaVersion","kind","epicId","ownerStoryId","sessionId","idempotencyKey","leaseId","acquiredAt","expiresAt","setupHeadSha"],ir=3600*1e3;async function Ue(e,t){const o=await Pe(e),r=await Le(o,"setup-reservations"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function nr(e,t){const o=await Ue(e,t.ownerStoryId);await Te(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),await ee(o.path,o.parent)}async function gt(e,t){try{const o=await Ue(e,t);if(!pe(o.path))return;await ee(o.path,o.parent);const r=JSON.parse(await V(o.path,"utf8"));return Object.keys(r).sort().join("\0")!==[...or].sort().join("\0")||r.schemaVersion!==1||r.kind!==yt||r.ownerStoryId!==t||!De(r.epicId)||!De(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 ar(e,t){const o=await Ue(e,t);pe(o.path)&&await ct(o.parent,o.name)}async function mt(e,t,o,r,i){const n=await gt(e,r),d=Date.parse(i);if(!n||n.epicId!==o||!(Date.parse(n.expiresAt)>d))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)>d))return;const u=g(t.stories[r]);if(!(u?.checkpoint||u?.last_step!==W))return n}async function wt(e,t){const o=await Pe(e),r=await Le(o,"handoffs"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function Ze(e,t){const o=await wt(e,t.storyId);await Te(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
4
|
+
`),await ee(o.path,o.parent)}async function te(e,t){try{const o=await wt(e,t);await ee(o.path,o.parent);const r=JSON.parse(await V(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 cr(e,t,o,r,i){const n=await te(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 sr(e,t,o,r,i,n){const d=await te(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==B(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 Ze(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function dr(e,t,o,r,i,n,d,c,u){const s=await te(e,o);if(s?.state==="consumed"&&s.fromSessionId===r&&s.consumedBySessionId===c)return;const f=await O(e,{required:!0}),p=g(f.epics[t]?.branch_lease),v=g(p?.handoffConsumption);if(!s||s.state!=="consuming"||s.fromSessionId!==r||s.token!==i||s.tokenDigest!==B(i)||s.bundleDigest!==n||s.claimRevision!==d||s.consumedBySessionId!==c||p?.ownerStoryId!==o||p.sessionId!==c||v?.kind!=="direct-yolo-setup-handoff-consumption"||v.state!=="consumed"||v.fromSessionId!==r||v.tokenDigest!==s.tokenDigest||v.bundleDigest!==n||v.claimRevision!==d||v.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await Ze(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:u})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function fr(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)&&ur(t.tokenDigest,r))}function ur(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&Dt(o,r)}function Ie(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function xe(e,t,o){await P(e,r=>{const i=z(r,t),n=g(i.branch_lease);Ie(n,o)&&(i.branch_lease=null)})}async function pr(e,t){const o=await O(e.projectRoot,{required:!0}),r=g(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!De(r.sessionId)||!De(r.idempotencyKey)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!Number.isFinite(Date.parse(String(r.expiresAt))))return;const i=await F(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 Y(i.path,i.owner)&&await xe(e.projectRoot,e.epicId,r)}async function be(e,t,o,r){const i=await Nt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=it(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:nt,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function ke(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 Qe(e,t,o,r){const i=ne(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function re(e,t,o,r,i="tracked"){if(e.length===0||e.some(c=>!Xe(c)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};if(i==="runtime-store")return lr(e,t,o,r);const n=t.length>0?Ce(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=>!He(n.scopes,c)&&!r?.files.some(u=>u.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 lr(e,t,o,r){if(e.some(Kt))return{ok:!1,reasonCode:ge.WRITE_SET_FORBIDDEN};const i=t.length>0?Ce(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!==B([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!He(i.scopes,d)&&!r?.files.some(c=>c.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}}function oe(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function hr(e){return typeof e!="string"||e.length>512||!Xe(e)||!Ct(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Xe(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function De(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function ie(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function ne(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function B(e){return kt("sha256").update(e).digest("hex")}function T(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 g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yr(e,t,o,r,i){const n=g(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 gr(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 mr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],wr=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function Z(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!==mr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==wr.join("\0")?void 0:r}async function vr(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 ae(e.projectRoot)).some(u=>u.branch===e.executionBranch&&N(u.path)!==e.projectRoot))return a("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return a("direct-yolo-setup-physical-state-raced");const c=await et(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 vt=3e4,Rr=3,Sr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class Ee extends Error{}function Ir(e,t=vt){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 xr(e){if(!ie(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await de("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:N(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Ir(process.env,e.fetchTimeoutMs??vt)}),{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 br=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function no(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=N(e),i=g(JSON.parse(await V(X(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await O(r),d=Oe(i,n),c=g(g(d.epics)?.[t]);if(!c)return o;const u=St(d,t,c),s=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,f=await Rt(r,c,i),p=g(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:u,terminal:br.has(String(c.status??"").toLowerCase()),bound:!!Z(p,s,f),executionBranch:s,originBranch:f})}catch{return o}}async function Rt(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 d of["main","master"])await C(e,["rev-parse","--verify","--quiet",`refs/heads/${d}^{commit}`])&&await C(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=g(e.stories)??{},n=Bt(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const u=g(r[c]);return u?[{...u,id:c}]:[]}),d=_t({...o,id:t},n);return d.mode==="epic"&&(d.source==="new-epic-default"||d.source==="epic-boundary")?"resolved-epic":"not-epic"}function It(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function ao(e){const t=q(e.nowIso),o=Date.parse(t),r=(c,u={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...u,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=N(e.projectRoot);let n=e.originFetch,d="origin-binding-start-raced";for(let c=0;c<Rr;c+=1){let u,s={};try{const f=g(JSON.parse(await V(X(i,".neocortex/state.json"),"utf8")));if(!f)return r("origin-binding-start-state-invalid");const p=await O(i),v=Oe(f,p),y=g(g(v.epics)?.[e.epicId]);if(!y)return r("origin-binding-start-target-ambiguous");if(St(v,e.epicId,y)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const h=typeof y.execution_branch=="string"&&y.execution_branch.length>0?y.execution_branch:`epic/${e.epicId}`,I=await Rt(i,y,f);if(s={executionBranch:h,originBranch:I},!ie(h)||!ie(I)||h===I||!await C(i,["check-ref-format","--branch",h])||!await C(i,["check-ref-format","--branch",I]))return r("origin-binding-start-branch-invalid",s);const _=g(p.epics[e.epicId]),w=_?.origin_binding??y.origin_binding;if(w!=null){const x=Z(w,h,I);return x?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:x.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",s)}if(It(g(_?.branch_lease??y.branch_lease),o))return r("origin-binding-start-lease-inconsistent",s);if(n??=await xr({projectRoot:i,originBranch:I,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,s);const E=`refs/remotes/origin/${I}`,k=`refs/heads/${I}`,S=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),R=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(S)||S!==R)return r("origin-binding-start-origin-stale",s);if((await ae(i)).some(x=>x.branch===h&&N(x.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",s);const m=`refs/heads/${h}`,D=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(D){const x=await et(i,["merge-base","--is-ancestor",S,D]);if(x===1)return r("direct-yolo-origin-not-ancestor",s);if(x!==0)return r("direct-yolo-origin-ancestry-unverifiable",s)}const b={schemaVersion:2,originBranch:I,originHeadSha:S,executionBranch:h,capturedFrom:"branch-ref",capturedAt:t};return await P(i,x=>{const A=z(x,e.epicId);if(A.origin_binding!==void 0&&A.origin_binding!==null)throw new Ee("origin-binding-start-raced");if(It(g(A.branch_lease),o))throw new Ee("origin-binding-start-lease-inconsistent");A.origin_binding=b},{expectedRevision:p.revision,preCommit:async()=>{const x=await l(i,["rev-parse","--verify","--quiet",`${k}^{commit}`]).catch(()=>""),A=await l(i,["rev-parse","--verify","--quiet",`${E}^{commit}`]).catch(()=>""),$=await l(i,["rev-parse","--verify","--quiet",`${m}^{commit}`]).catch(()=>"");if(x!==S||A!==S||$!==D)throw new Ee("origin-binding-start-raced");D||(await l(i,["update-ref",m,S,""]),u={ref:m,sha:S})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...s,originHeadSha:S,outcome:"captured",executionRefCreated:u!==void 0,capturedAt:t})}catch(f){if(u&&await l(i,["update-ref","-d",u.ref,u.sha]).catch(()=>{}),f instanceof Error&&f.message==="git-lifecycle-runtime-revision-conflict"){d="origin-binding-start-raced";continue}return f instanceof Ee?r(f.message,s):r("origin-binding-start-failed",s)}}return r(d)}function je(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=T(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=t.some(i=>i.endsWith("/"))?jt(e,await H(e,["worktree","list","--porcelain","-z"])):new Set,r=await Promise.all(t.map(async i=>{if(o.has(i))return`${i}\0registered-worktree`;if(!Xe(i))throw new Error("direct-yolo-checkout-payload-invalid");try{return`${i}\0${await l(e,["hash-object","--no-filters","--",i])}`}catch{throw new Error("direct-yolo-checkout-untracked-read-failed")}}));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"]),...r].join("\0"))}async function co(e){const t=N(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 ae(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 xt=new Set(Object.values(ge));function K(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&Ne(e.message)||e instanceof Error&&xt.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 et(e,t){try{return await de("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 de("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function H(e,t){return String((await de("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function C(e,t){try{return await de("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{Xr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Xt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,vt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,Mr as acceptDirectYoloSetupCheckpoint,Vr as beginDirectYoloStoryCommit,co as captureDirectYoloCheckoutEvidence,io as captureDirectYoloStoryGovernance,ao as captureEpicOriginBindingAtYoloopStart,Qr as directYoloCommitIdempotencyKey,eo as directYoloWaveQaCoverage,er as directYoloWaveReceiptRef,xr as fetchOriginForYoloopStart,Fr as finalizeDirectYoloStoryCheckpoint,hr as isDirectYoloWriteSetExtensionScope,Kr as issueDirectYoloSetupLeaseHandoff,oo as persistDirectYoloWaveStoryCheckpoint,Gr as prepareDirectYoloSetup,ro as pushDirectYoloWaveHead,no as readYoloopStartEpic,Jr as recoverLegacyDirectYoloStoryCheckpoint,Ur as resolveDirectYoloIntegrationAuthority,to as runDirectYoloWaveP205,Zr as validateDirectYoloWriteSet,Yr as verifyDirectYoloIntegrationCommit,Ir as yoloopStartGitNetworkExecOptions};
|
|
File without changes
|
|
@@ -104,9 +104,9 @@ export declare function maybeCaptureYoloopStartOriginBinding(args: string, proje
|
|
|
104
104
|
/**
|
|
105
105
|
* Post-response hook: apply server-provided operations to local state.
|
|
106
106
|
* Safe to call for any response — no-op if no yoloopStateUpdate present.
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
107
|
+
* Rollover, successor and lock ownership updates are authoritative: failure is
|
|
108
|
+
* returned to the caller so instructions cannot be released before durable
|
|
109
|
+
* state exists.
|
|
110
110
|
* Non-rollover legacy operations retain fail-soft compatibility.
|
|
111
111
|
*/
|
|
112
112
|
export declare function persistYoloopFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string, nowIso?: string): Promise<YoloopPersistenceResult>;
|
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{statSync as J}from"node:fs";import{join as X}from"node:path";import{YoloopClientStateStore as L}from"./yoloop-client-state-store.js";import{LEGACY_ADOPTION_RECEIPT_SCHEMA as Q,LEGACY_ADOPTION_TARGET_POLICY as ee,runLegacyYoloopAdoption as te}from"./legacy-yoloop-adoption.js";import{isYoloopInvocation as oe}from"./target-normalization.js";import{applyStateMigration as re,StateMigrationApplyError as ie}from"../migrations/state-json.js";function W(e){return oe(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class ne extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="YoloopStateReadError"}}function j(e,r){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??r}const G=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function ae(e){const r=j(e,"");if(G.has(r))return!0;const t=e?.code;return typeof t=="string"&&G.has(t)}const se=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function we(e){if(typeof e.args!="string"||e.args.length===0)return;const r=e.args.match(se);if(!r)return;const t=r[0];if(e.args.slice(t.length).trim()!=="")return;let
|
|
2
|
-
`),await new L(r).readAll(t)}catch(i){const
|
|
3
|
-
`),new ne(
|
|
4
|
-
`);const
|
|
5
|
-
`),
|
|
6
|
-
`);return}}async function Ce(e,r,t){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const
|
|
1
|
+
import{statSync as J}from"node:fs";import{join as X}from"node:path";import{YoloopClientStateStore as L}from"./yoloop-client-state-store.js";import{LEGACY_ADOPTION_RECEIPT_SCHEMA as Q,LEGACY_ADOPTION_TARGET_POLICY as ee,runLegacyYoloopAdoption as te}from"./legacy-yoloop-adoption.js";import{isYoloopInvocation as oe}from"./target-normalization.js";import{applyStateMigration as re,StateMigrationApplyError as ie}from"../migrations/state-json.js";function W(e){return oe(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class ne extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="YoloopStateReadError"}}function j(e,r){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??r}const G=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function ae(e){const r=j(e,"");if(G.has(r))return!0;const t=e?.code;return typeof t=="string"&&G.has(t)}const se=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function we(e){if(typeof e.args!="string"||e.args.length===0)return;const r=e.args.match(se);if(!r)return;const t=r[0];if(e.args.slice(t.length).trim()!=="")return;let a=!1;try{const o=X(e.projectRoot,"docs","epics");a=J(o).isDirectory()}catch(o){const s=o instanceof Error?o.message:String(o);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${s}. Proceeding with raw args.`);return}a&&(e.args=`${t} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function be(e,r,t){if(W(e))try{const i=await te(r,t?{nowIso:t}:{});return i.written&&process.stderr.write(`[yoloop] ${i.receipt.reasonCode}: continuation policy ${ee} (${Q}).
|
|
2
|
+
`),await new L(r).readAll(t)}catch(i){const a=j(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${a}. Local yoloop authority was not read; no request was sent.
|
|
3
|
+
`),new ne(a)}}async function Se(e,r,t={}){if(W(e))try{let i;try{i=(await new L(r).readAll(t.nowIso))?.state?.currentEpicId}catch{i=void 0}const{runYoloopStartAdaptations:a}=await import("./yoloop-start-origin-binding.js"),o=await a({args:e,projectRoot:r,persistedCurrentEpicId:i,...t.nowIso?{nowIso:t.nowIso}:{},...t.fetchTimeoutMs?{fetchTimeoutMs:t.fetchTimeoutMs}:{},...t.prProvider?{prProvider:t.prProvider}:{},...t.repository?{repository:t.repository}:{}}),s=o.branchModeConversion;!t.quiet&&s&&(s.outcome==="converted"||s.outcome==="refused"&&s.reasonCode!=="branch-mode-conversion-epic-missing")&&process.stderr.write(`[yoloop] branch-mode-conversion-start ${s.outcome}${s.reasonCode?` ${s.reasonCode}`:""}.
|
|
4
|
+
`);const n=o.originBinding,p=n.reasonCode==="origin-binding-start-target-ambiguous"||n.reasonCode==="origin-binding-start-target-terminal"||n.reasonCode==="origin-binding-start-branch-mode-not-epic"||n.reasonCode==="origin-binding-start-state-invalid"||n.reasonCode==="origin-binding-start-failed";return!t.quiet&&n.outcome!=="already-bound"&&!p&&process.stderr.write(`[yoloop] origin-binding-start ${n.outcome}${n.reasonCode?` ${n.reasonCode}`:""}.
|
|
5
|
+
`),n}catch{t.quiet||process.stderr.write(`[yoloop] origin-binding-start refused origin-binding-start-failed.
|
|
6
|
+
`);return}}async function Ce(e,r,t){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const a=i.operations.some(n=>n.type==="rollover_session"||n.type==="commit_successor_transition"||n.type==="acquire_lock"||n.type==="release_lock"&&n.expectedLeaseId!==void 0);let o;const s=a?3:1;for(let n=0;n<s;n+=1)try{return await new L(r).applyUpdate(i,t),{ok:!0,authoritative:a,reasonCodes:[]}}catch(p){if(o=p,!a||n+1>=s||!ae(p))break}{const p=j(o,a?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return a?(process.stderr.write(`[yoloop] ${p}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
|
|
7
7
|
`),{ok:!1,authoritative:!0,reasonCodes:[p]}):(process.stderr.write(`[yoloop] ${p}. Auxiliary state update was not persisted; retry the same command.
|
|
8
|
-
`),{ok:!0,authoritative:!1,reasonCodes:[p]})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,r){return Array.isArray(e)&&e.length<=r&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(t))}function
|
|
8
|
+
`),{ok:!0,authoritative:!1,reasonCodes:[p]})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,r){return Array.isArray(e)&&e.length<=r&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(t))}function q(e){return c(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ce(e){const r={...e};return delete r.scope,delete r.stateSummary,delete r.graphRetrieval,delete r.runnerBootstrap,delete r.projectEvidence,delete r.continuity,delete r.implementCheckpoint,r}function le(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function de(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function pe(e,r){const t=e.syntheticStory;if(!c(t))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=t.schemaVersion,a=t.epicId,o=t.storyId,s=t.storyPath,n=t.deterministicKey,p=t.storyContent,E=t.storyContentSha256,f=t.lifecycle;if(i!==2||typeof a!="string"||!/^P9\d{18}$/.test(a)||typeof o!="string"||o!==`${a}.01.000001`||typeof s!="string"||s!==`docs/stories/${o}.story.md`||typeof n!="string"||!/^[a-f0-9]{16}$/.test(n)||typeof E!="string"||!/^[a-f0-9]{64}$/.test(E)||typeof p!="string"||p.length===0||p.length>131072||!c(f)||f.branchMode!=="epic"||f.executionBranch!==`epic/${a}`||typeof f.originBranch!="string"||!de(f.originBranch)||typeof f.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(f.graphRevision)||f.isolatedSyntheticEpic!==!0||t.publicSafe!==!0||t.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const u=await import("node:fs/promises"),w=await import("node:path"),I=await import("node:crypto");if(I.createHash("sha256").update(p).digest("hex")!==E)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const k=w.join(r,".neocortex"),O=w.join(k,"state.json"),b=w.join(r,...s.split("/"));let R;try{R=await u.readFile(O,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=I.createHash("sha256").update(R).digest("hex");let y;try{y=JSON.parse(R)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!c(y)||!c(y.stories)||!c(y.epics)||q(y))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!c(y.config)||y.config.default_branch!==f.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const d=y.stories[o];if(d!==void 0&&(!c(d)||d.epic_id!==a||d.story_file!==s||!c(d.inlineYolo)||d.inlineYolo.deterministicKey!==n))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=y.epics[a];if(g!==void 0&&(!c(g)||g.id!==a||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==f.executionBranch||g.origin_branch!==f.originBranch||g.graph_revision!==f.graphRevision||!c(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==n||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const _=c(g)?g:{},S=Array.isArray(_.stories)?_.stories:[];if(S.some(l=>typeof l!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const l of S){const m=y.stories[l];if(!c(m)||m.id!==l||m.epic_id!==a)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const l=await u.readFile(b,"utf8"),m=l.includes(`id: ${o}`)&&l.includes(`synthetic_key: ${n}`);if(l!==p&&!m)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(l){if(l.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const C=S.includes(o)?[...S]:[...S,o],T={...y.stories,[o]:{...c(d)?d:{},id:o,epic_id:a,title:"Synthetic inline USER STORY for yolo",status:c(d)&&typeof d.status=="string"?d.status:"backlog",steps_completed:c(d)&&Array.isArray(d.steps_completed)?d.steps_completed:[],last_step:c(d)?d.last_step??null:null,branch_name:c(d)?d.branch_name??null:null,story_file:s,source:"inline-yolo-materialization",inlineYolo:{...c(d)&&c(d.inlineYolo)?d.inlineYolo:{},schemaVersion:2,deterministicKey:n,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=C.filter(l=>c(T[l])&&le(T[l].status)).length,Y=c(y.inlineYolo)?y.inlineYolo:{},K=c(Y.materializations)?Y.materializations:{},Z=ce({...y,stories:T,epics:{...y.epics,[a]:{..._,id:a,title:typeof _.title=="string"?_.title:"Isolated synthetic inline yolo lifecycle",status:v===C.length&&C.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:f.executionBranch,origin_branch:f.originBranch,graph_revision:f.graphRevision,stories:C,total_stories:C.length,completed_stories:v,...v===C.length&&C.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:n,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...K,[o]:{schemaVersion:2,epicId:a,storyId:o,storyPath:s,deterministicKey:n,storyContentSha256:E,sourceStateSha256:P,lifecycle:f,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${s}`,reasonCodes:Array.isArray(t.reasonCodes)?t.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${I.randomBytes(6).toString("hex")}`,x=w.join(k,`state.json.tmp.${B}`),z=`${b}.tmp.${B}`,F=w.join(k,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),D=w.join(k,"state.json.inline-yolo.lock");let H=!1,A;const V=async l=>{let m;try{m=await u.open(l,"r"),await m.sync()}catch(h){const $=h.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes($??""))throw h}finally{await m?.close().catch(()=>{})}},U=async(l,m)=>{const h=await u.open(l,"wx",384);try{await h.writeFile(m,"utf8"),await h.sync()}finally{await h.close()}};try{await u.mkdir(k,{recursive:!0}),await u.mkdir(w.dirname(b),{recursive:!0});try{A=await u.open(D,"wx",384),await A.writeFile(`${process.pid}
|
|
9
9
|
${P}
|
|
10
|
-
`,"utf8"),await A.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const l=await u.readFile(O,"utf8");if(I.createHash("sha256").update(l).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await u.access(b)}catch{await U(z,p),await u.rename(z,b),await V(w.dirname(b)),H=!0}await u.copyFile(O,F);const h=await u.open(F,"r");try{await h.sync()}finally{await h.close()}return await U(x,JSON.stringify(
|
|
10
|
+
`,"utf8"),await A.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const l=await u.readFile(O,"utf8");if(I.createHash("sha256").update(l).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await u.access(b)}catch{await U(z,p),await u.rename(z,b),await V(w.dirname(b)),H=!0}await u.copyFile(O,F);const h=await u.open(F,"r");try{await h.sync()}finally{await h.close()}return await U(x,JSON.stringify(Z,null,2)),await u.rename(x,O),await V(k),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${o}; backup=${w.basename(F)}.
|
|
11
11
|
`),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(l){await Promise.allSettled([u.unlink(x),u.unlink(z)]),H&&await u.readFile(b,"utf8").catch(()=>{})===p&&await u.unlink(b).catch(()=>{});const m=l.message??String(l);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${m}.
|
|
12
|
-
`),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await A?.close().catch(()=>{}),A&&await u.unlink(D).catch(()=>{})}}async function ke(e,r){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return pe(e,r);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,
|
|
13
|
-
`),{applied:o.outcome==="applied",blocking:!1,reasonCode:o.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(o){const
|
|
14
|
-
`),{applied:!1,blocking:!0,reasonCode:
|
|
12
|
+
`),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await A?.close().catch(()=>{}),A&&await u.unlink(D).catch(()=>{})}}async function ke(e,r){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return pe(e,r);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,a=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!c(i)||Object.keys(i).some(o=>!a.has(o))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(o=>!c(o)||Object.keys(o).some(s=>!["kind","source","target"].includes(s))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(o.kind))||typeof o.target!="string"||o.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.target)||o.source!==void 0&&(typeof o.source!="string"||o.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.source)))||!M(i.migratedEpicIds,4096)||!M(i.migratedStoryIds,4096)||!M(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const o=re(r,i),s=`.neocortex/state.json.migration-backup-${o.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${o.outcome}; operation=${o.operationId}; backup=${o.backupHash?s:"none"}.
|
|
13
|
+
`),{applied:o.outcome==="applied",blocking:!1,reasonCode:o.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(o){const s=o instanceof ie?o.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${s}.
|
|
14
|
+
`),{applied:!1,blocking:!0,reasonCode:s}}}const t=e.migratedState;return!t||typeof t!="object"||Array.isArray(t)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:q(t)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
|
|
15
15
|
`),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"}):(process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.
|
|
16
16
|
`),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function Ee(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${t}`}}}async function _e(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:t}}}export{N as YOLOOP_PERSISTENCE_REASON_CODES,ne as YoloopStateReadError,W as isYoloopTrigger,we as maybeAutoResolveYoloopArgs,Se as maybeCaptureYoloopStartOriginBinding,Ee as maybeRunDiscoveryHook,_e as maybeRunGraphRetrievalHook,ke as persistMigratedStateFromResponse,Ce as persistYoloopFromResponse,be as readYoloopForRequest};
|
|
@@ -27,7 +27,7 @@ export type YoloopSessionMode = 'directory' | 'epic-file' | 'epic-id';
|
|
|
27
27
|
export type YoloopLockOwnerKind = 'client' | 'server';
|
|
28
28
|
export type YoloopLockOwnerPidState = 'live' | 'stale' | 'unknown';
|
|
29
29
|
export type YoloopLockLeaseState = 'active' | 'expired' | 'unknown';
|
|
30
|
-
export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1' | 'continuation-replan-v1' | 'cross-epic-continuation-reconcile-v1';
|
|
30
|
+
export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1' | 'continuation-replan-v1' | 'native-launch-retry-v1' | 'cross-epic-continuation-reconcile-v1';
|
|
31
31
|
export interface YoloopCrossEpicReconciliationEvidenceV1 {
|
|
32
32
|
readonly schemaVersion: 'YoloopCrossEpicReconciliationEvidence/1.0';
|
|
33
33
|
readonly repositoryFingerprint: string;
|
|
@@ -299,6 +299,7 @@ export type YoloopStateOperation = {
|
|
|
299
299
|
readonly expectedRunId?: string;
|
|
300
300
|
readonly expectedSessionId?: string;
|
|
301
301
|
readonly expectedLeaseId?: string;
|
|
302
|
+
readonly expectedLeaseExpiresAt?: string;
|
|
302
303
|
} | {
|
|
303
304
|
readonly type: 'write_state';
|
|
304
305
|
readonly state: YoloopPersistedCounters;
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* setSecureFilePermissions helper from secure-config.ts.
|
|
24
24
|
*/
|
|
25
25
|
import type { YoloopPersistedCounters, YoloopPersistedState, YoloopRecoveryAttemptRef, YoloopRunControlV1, YoloopRunTransitionReceiptV1, YoloopStateOperation, YoloopStateUpdate } from './shared-yoloop-types.js';
|
|
26
|
-
export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1", "continuation-replan-v1"];
|
|
26
|
+
export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1", "continuation-replan-v1", "native-launch-retry-v1"];
|
|
27
27
|
type YoloopSessionRolloverOperation = Extract<YoloopStateOperation, {
|
|
28
28
|
readonly type: 'rollover_session';
|
|
29
29
|
}>;
|
|
@@ -101,6 +101,7 @@ export declare class YoloopClientStateStore {
|
|
|
101
101
|
* the legacy checkout-local adapter; a corrupt v2 never falls back.
|
|
102
102
|
*/
|
|
103
103
|
private readCommonAuthorityIfPresent;
|
|
104
|
+
private reconcileCommonLock;
|
|
104
105
|
/** Apply legacy operation semantics to the common authority under its Git CAS. */
|
|
105
106
|
private applyCommonOperation;
|
|
106
107
|
private reserveContinuationAuthority;
|