@ornexus/neocortex 4.66.11 → 4.66.12
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 +2 -2
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/worktree-checkout-boundary.d.ts +2 -0
- package/packages/client/dist/git/worktree-checkout-boundary.js +1 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- 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
package/install.ps1
CHANGED
package/install.sh
CHANGED
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as p,lstatSync as f}from"node:fs";import{homedir as O}from"node:os";import{dirname as E,isAbsolute as _,join as c,resolve as S}from"node:path";const C=/^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/;function h(e,l=v(e)){if(l.targetId!=="codex")return;const t=["CODEX_THREAD_ID","CODEX_SESSION_ID","CODEX_SANDBOX_NETWORK_DISABLED"].some(s=>e.env[s]!==void 0),d=t&&e.env.CODEX_REMOTE_PAYLOAD!==void 0,o=d?"codex-desktop":t?"codex-cli":"unknown",i=e.nativeHostVersion?.trim()??"",m=C.test(i)?i:null,n=!!e.targetFlag&&!t,u=e.env.CODEX_HOME&&_(e.env.CODEX_HOME)?e.env.CODEX_HOME:c(O(),".codex");let r=!1;if(t){const s=a=>{try{return f(a),!0}catch(I){return I.code!=="ENOENT"}},g="neocortex-sentinel.toml";r=!s(c(u,"agents",g));for(let a=S(e.cwd);r&&(s(c(a,".codex","agents",g))&&(r=!1),E(a)!==a);a=E(a));}return Object.freeze({schemaVersion:1,platformTarget:"codex",...r?{sentinelProfileMissing:!0}:{},hostKind:o,hostVersion:m,origin:n?"explicit-override":d?"host-observed":t?"environment":"unknown",confidence:n||o==="unknown"?"unknown":d?"observed":"inferred",publicSafe:!0})}const D=new Set(["claude-code","cursor","vscode","gemini","codex","opencode","github-copilot-cli","kimi","antigravity","openclaw","grok","deepseek","runner","unknown"]),k=Object.freeze({claude:"claude-code","claude-code":"claude-code",cursor:"cursor",vscode:"vscode","vscode-copilot":"vscode",gemini:"gemini","gemini-cli":"gemini",codex:"codex","codex-cli":"codex",opencode:"opencode","copilot-cli":"github-copilot-cli","github-copilot-cli":"github-copilot-cli",kimi:"kimi",antigravity:"antigravity",openclaw:"openclaw","open-claw":"openclaw",grok:"grok","grok-build":"grok",deepseek:"deepseek","deepseek-harness":"deepseek",deepseek_harness:"deepseek",dsh:"deepseek",runner:"runner",unknown:"unknown"});function b(e){return D.has(e)}function A(e){return k[e.trim().toLowerCase()]??null}const N=e=>p(e);function v(e,l=N){if(e.targetFlag){const n=A(e.targetFlag);return n?{targetId:n,confidence:1,reason:`Explicit --target=${n} flag`,reasonCode:"platform-target-explicit"}:{targetId:"unknown",confidence:0,reason:"Explicit platform target is not recognized",reasonCode:"platform-target-invalid-override"}}const t=n=>e.env[n]!==void 0,d=[],o=(n,u,r)=>{r.some(t)&&d.push({targetId:n,signal:u})};o("claude-code","Claude Code runtime",["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CLAUDE_CODE","CLAUDE_AGENT"]),o("codex","Codex runtime",["CODEX_THREAD_ID","CODEX_SESSION_ID","CODEX_SANDBOX_NETWORK_DISABLED"]),o("opencode","OpenCode runtime",["OPENCODE","OPENCODE_SESSION_ID"]),o("cursor","Cursor runtime",["CURSOR_SESSION_ID","CURSOR_TRACE_ID"]),o("gemini","Gemini CLI runtime",["GEMINI_CLI"]),o("github-copilot-cli","GitHub Copilot CLI runtime",["COPILOT_CLI"]),o("kimi","Kimi Code runtime",["KIMI_SESSION_ID","KIMI_CODE_SESSION_ID"]),o("antigravity","Antigravity runtime",["ANTIGRAVITY_SESSION_ID","ANTIGRAVITY_AGENT"]),o("openclaw","OpenClaw runtime",["OPENCLAW_SESSION_ID","OPENCLAW_GATEWAY"]),o("grok","Grok Build runtime",["GROK_SESSION_ID","GROK_AGENT","GROK_HOME"]),o("deepseek","DeepSeek Harness runtime",["DSH_SHELL","DSH_SESSION_ID"]);const i=[...new Map(d.map(n=>[n.targetId,n])).values()];if(i.length>1)return{targetId:"unknown",confidence:0,reason:`Conflicting runtime platform signals: ${i.map(({targetId:n})=>n).sort().join(", ")}`,reasonCode:"platform-target-ambiguous"};if(i.length===1){const n=i[0],r={"claude-code":"CLAUDE.md",codex:"AGENTS.md",cursor:".cursor",gemini:"GEMINI.md",vscode:".vscode",grok:"AGENTS.md"}[n.targetId],s=r?l(c(e.cwd,r)):!1;return{targetId:n.targetId,confidence:s?.98:.95,reason:`${n.signal} signal${s?` corroborated by ${r}`:""}`,reasonCode:"platform-target-runtime-signal"}}return t("VSCODE_PID")||e.env.TERM_PROGRAM==="vscode"?{targetId:"vscode",confidence:.75,reason:"VS Code runtime signal without a stronger agent runtime signal",reasonCode:"platform-target-runtime-signal"}:["AGENTS.md",".cursor",".cursorrules","CLAUDE.md",".vscode","GEMINI.md"].some(n=>l(c(e.cwd,n)))?{targetId:"unknown",confidence:0,reason:"Filesystem marker found without platform-owned runtime evidence",reasonCode:"platform-target-filesystem-only"}:{targetId:"unknown",confidence:0,reason:"No platform runtime signals detected",reasonCode:"platform-target-unknown"}}export{h as detectNativeHostAttestation,v as detectPlatform,b as isValidTargetId,A as normalizeTargetId};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFileSync as
|
|
2
|
-
`,{flag:"wx"}),
|
|
3
|
-
`),(await
|
|
4
|
-
`).filter(Boolean).sort();if(
|
|
1
|
+
import{execFileSync as R}from"node:child_process";import{createHash as $,randomBytes as P}from"node:crypto";import{existsSync as k,lstatSync as L,readFileSync as w,realpathSync as N,writeFileSync as O}from"node:fs";import{join as p,resolve as j}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLock as F,assertGitLifecyclePrivateFile as T,ensureGitLifecyclePrivateChildDirectory as G,gitLifecycleRuntimeDirectory as B,readGitLifecycleRuntime as C,releaseGitLifecyclePhysicalIntegrationLock as J}from"./git-lifecycle-store.js";import{registeredNestedWorktreeDirectories as I}from"./worktree-checkout-boundary.js";const _=["809db253d486b5d2620d318666219e8a2b4df05016174ba3c8a33fa17b65802a","50224b193dae7ba2a066e54f7091d2656302b849ea7a145a3a4c556d85f3fe3c","f757f6bf1182f23e5d7acbe47cbce9f0fa12f211d290b486892c6722bc42b4e8","9cd927d02ff5979b5077e75b09cb34be275eca0e1c955403235b9ba0fb7a55eb","a3f880e8d5bca9158a88c46f88754c0948237a3e8516c83a762ba1ee22c27d46"];function s(t,r){const o={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_NAMESPACE"])delete o[e];return R("git",[...r],{cwd:t,env:o,encoding:"utf8",stdio:["ignore","pipe","pipe"],timeout:3e4,maxBuffer:16*1024*1024}).trim()}function y(t){return $("sha256").update(t).digest("hex")}function d(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const z=new Set([".neocortex/pending-epic-claims.json",".neocortex/yoloop-session-rollover.json",".neocortex/yoloop-state.json",".neocortex/yoloop-successor-transition.json"]);function x(t){if(s(t,["status","--porcelain=v1","--untracked-files=no"]))return!0;const r=s(t,["ls-files","--others","--exclude-standard","-z"]).split("\0").filter(Boolean),o=I(t,s(t,["worktree","list","--porcelain","-z"]));return r.some(e=>{if(o.has(e))return!1;if(!z.has(e))return!0;const c=p(t,e);try{const n=L(c);return!n.isFile()||n.size>4*1024*1024||N(c)!==p(N(t),e)||!d(JSON.parse(w(c,"utf8")))}catch{return!0}})}async function H(t,r){const o=j(t);if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(r))throw new Error("direct-yolo-retry-story-invalid");const e=r.split(".")[0],c=s(o,["rev-parse","HEAD"]),n=s(o,["symbolic-ref","--quiet","--short","HEAD"]);if(x(o))throw new Error("direct-yolo-retry-checkout-dirty");const i=w(p(o,".neocortex/state.json"),"utf8"),m=d(JSON.parse(i)),a=d(d(m?.stories)?.[r]),l=d(d(m?.epics)?.[e]);if(!a||!l||a.epic_id!==e||l.branch_mode!=="epic"||l.execution_branch!==n||n!==`epic/${e}`)throw new Error("direct-yolo-retry-story-binding-invalid");const u=a.steps_completed;if(a.status!=="create-tasks"||typeof a.last_step!="string"||y(a.last_step)!==_.at(-1)||a.branch_name!==n||!Array.isArray(u)||u.length!==_.length||u.some((E,v)=>typeof E!="string"||y(E)!==_[v])||a.checkpoint||a.pr_number)throw new Error("direct-yolo-retry-progress-ineligible");const h=await C(o,{required:!0}),b=d(h.epics[e]),g=d(b?.branch_lease),f=d(b?.origin_binding);if(d(h.stories[r])&&Object.keys(d(h.stories[r])).length>0||!f||f.executionBranch!==n||typeof f.originHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(f.originHeadSha)||g&&(!Number.isFinite(Date.parse(String(g.expiresAt)))||Date.parse(String(g.expiresAt))>Date.now()))throw new Error("direct-yolo-retry-runtime-active");s(o,["merge-base","--is-ancestor",String(f.originHeadSha),c]);const S=await G(await B(o),"private-execution"),A=y(r);for(const E of[`session-${A}.json`,`baseline-${A}.json`]){const v=p(S,E);if(k(v))throw await T(v,S),new Error("direct-yolo-retry-private-evidence-present")}const D=`.neocortex/recovery/${r}-c01-${y(`${c}\0${y(i)}`).slice(0,16)}.json`;if(k(p(o,D)))throw new Error("direct-yolo-retry-already-recorded");if(s(o,["rev-parse","HEAD"])!==c||w(p(o,".neocortex/state.json"),"utf8")!==i)throw new Error("direct-yolo-retry-preflight-raced");return Object.freeze({schemaVersion:1,kind:"direct-yolo-c01-retry-plan",storyId:r,epicId:e,executionBranch:n,previousHeadSha:c,previousStateSha256:y(i),runtimeRevision:h.revision,previousStatus:"create-tasks",previousStepsCompleted:[...u],auditPath:D,publicSafe:!0})}async function Y(t,r,o){const e=j(t),c=`retry-${P(16).toString("hex")}`,n=await F(e,{kind:"direct",storyId:r,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+5*6e4).toISOString(),persistent:!1});if(!n.ok)throw new Error(n.reasonCode);try{const i=await H(e,r);if(i.previousHeadSha!==o)throw new Error("direct-yolo-retry-head-mismatch");const m=p(e,".neocortex/state.json"),a=JSON.parse(w(m,"utf8")),l=a.stories[r];l.status="backlog",l.steps_completed=[],l.last_step=null,l.branch_name=null;const u={...i,recordedAt:new Date().toISOString(),reason:"private-session-lost",newAttemptStatus:"backlog",oldProgressAcceptedForNewAttempt:!1};l.last_updated=u.recordedAt;const h=await H(e,r);if(JSON.stringify(h)!==JSON.stringify(i))throw new Error("direct-yolo-retry-apply-raced");if(s(e,["rev-parse","HEAD"])!==o||y(w(m,"utf8"))!==i.previousStateSha256||x(e))throw new Error("direct-yolo-retry-apply-raced");const{mkdirSync:b}=await import("node:fs");if(b(p(e,".neocortex/recovery"),{recursive:!0}),O(p(e,i.auditPath),`${JSON.stringify(u,null,2)}
|
|
2
|
+
`,{flag:"wx"}),O(m,`${JSON.stringify(a,null,2)}
|
|
3
|
+
`),(await C(e,{required:!0})).revision!==i.runtimeRevision)throw new Error("direct-yolo-retry-runtime-raced");s(e,["add","--",".neocortex/state.json",i.auditPath]),s(e,["commit","-m",`chore(${r}): begin audited C01 retry`,"-m",`Neocortex-C01-Retry-From: ${i.previousHeadSha}`,"-m",`Neocortex-C01-Retry-Audit: ${i.auditPath}`]);const f=s(e,["rev-parse","HEAD"]),S=s(e,["diff-tree","--no-commit-id","--name-only","-r",f]).split(`
|
|
4
|
+
`).filter(Boolean).sort();if(s(e,["rev-parse",`${f}^`])!==i.previousHeadSha||JSON.stringify(S)!==JSON.stringify([".neocortex/state.json",i.auditPath].sort())||x(e))throw new Error("direct-yolo-retry-postcommit-unverified");return{plan:i,newHeadSha:f}}finally{await J(n.path,n.owner).catch(()=>{})}}export{Y as applyDirectYoloC01Retry,H as inspectDirectYoloC01Retry};
|
|
@@ -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{rootProjectMemoryPaths as Et}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 jt,resolveEpicStoryIds as At}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as Be,storyWriteSetCovers as Ce,validateStoryWriteScope as _t}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as He,computeImmutableStoryQaEvidenceDigest as Bt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as Ct,computeLegacyDirectYoloRecoveryReceiptRef as Ht,ensureRuntimeEpic as z,ensureRuntimeStory as Oe,ensureGitLifecyclePrivateChildDirectory as $e,executeP205TransientAuthorities as Ot,executeP205TransientAuthority as $t,isP226GateReasonCode as Le,projectP205TransientExecutionEvidence as it,publicStoryReviewArtifactFromBytes as Lt,publicStoryReviewArtifactFromGit as le,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as Nt,mutateGitLifecycleRuntime as P,P205_COMPLETE_COMMAND as nt,readGitLifecycleRuntime as O,gitLifecycleRuntimeDirectory as Ne,STORY_WRITE_SET_MAX_ENTRIES as at,storyWriteSetExtensionPaths as Pt,assertGitLifecyclePrivateFile as ee,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as qt,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 Tt,detectGovernanceModeSync as zt,governanceReceiptRefs as Gt,isGovernanceRepositoryPath as Wt,readGovernanceStateSourceSync as Mt,storyReviewGovernancePath as Kt,verifyStoryGovernanceBinding as Vt}from"./governance-runtime-store.js";import{parseNeocortexTrailers as ft,trailerReasonKey as ae,trailerValue as J}from"./neocortex-trailers.js";import{StoryWorktreeManager as Ft}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Yt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as ut,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as G}from"./git-lifecycle-step-ids.js";const ce=Dt(xt),se=3600*1e3;async function Tr(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&&!lr(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 mr(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 W(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 W(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 W(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 W(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 hr(N(e.projectRoot),t).catch(()=>{}),a(K(r,"direct-yolo-setup-failed"))}}async function zr(e){let t;try{const o=await me(e.projectRoot,e.storyId);if(await ze(o.projectRoot))return await Ut(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 W(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===G&&Array.isArray(E.steps_completed)&&E.steps_completed.length===1&&E.steps_completed[0]===G&&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 W(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=G,m.steps_completed=[G]},{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 Gr(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"?We(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)+rr)).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 ir(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 Wr(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"?We(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 nr(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 ar(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&&sr({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 er(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 cr(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 Mr(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 qt(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 fr(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 Kr(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 Vr(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(Nt[e.storyId]!==o)return await Jt(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 Ht(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 Jt(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([...Et(),`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 Ft({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 Ut(e,t){const o=await pt(e),r=Ge(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===G&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===G&&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=G,v.steps_completed=[G]},{expectedRevision:d.revision,preCommit:async()=>{if(Ge(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 or(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 Fr(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 Yr(e,t,o,r,i="tracked"){return re(e,t,o,r,i)}function Jr(e){return B(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Ur=se,Zt="p205-wave:";function Zr(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 Qt(e){return`${Zt}${e.waveHeadSha}:${e.waveDigest}`}async function Qr(e){let t;try{t=await Ot(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 Xr(e,t,o,r){const i=ne(t);return await l(e,["push",i,o]),Qe(e,i,o,r)}async function eo(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:[Qt(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(Ge(r))),n=await O(r,{required:!0}),d=He(i,n),c=zt({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=Pt(p).filter(pr),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 to(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:We(t).receipt}}catch(t){return a(K(t,"governance-capture-failed"))}}function Ge(e){const t=Mt(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 We(e){const t=Tt(e);if(!t.ok)throw new Error(t.reasonCode);return Me(e,t.value.governanceDigest)}function Me(e,t){const o=Vt({...e,expectedGovernanceDigest:t});if(!o.ok)throw new Error(o.reasonCode);const r=o.value.files.get(Kt(e.storyId));if(!r)throw new Error(ye.MISMATCH);return{receipt:o.value.receipt,review:Lt(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=Bt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=Ct({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,Yt,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 Xt=["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 er(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(!ue(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")!==[...
|
|
3
|
-
`),await ee(o.path,o.parent)}async function yt(e,t){try{const o=await Ue(e,t);if(!ue(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")!==[...
|
|
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 nr(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 ar(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 cr(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 sr(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)&&dr(t.tokenDigest,r))}function dr(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 fr(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 $t(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 ur(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 ur(e,t,o,r){if(e.some(Wt))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 pr(e){return typeof e!="string"||e.length>512||!Xe(e)||!_t(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 lr(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 hr(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 W(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 W(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 yr=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],gr=["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!==yr.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==gr.join("\0")?void 0:r}async function mr(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,wr=3,vr="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class ke extends Error{}function Rr(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:vr}}}}async function Sr(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",...Rr(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 Ir=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function ro(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:Ir.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=At(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=jt({...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 oo(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<wr;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 Sr({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 W(e){const t=T(await H(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Xe(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return B([await H(e,["diff","--cached","--binary","--full-index"]),await H(e,["diff","--binary","--full-index"]),await H(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function io(e){const t=N(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await W(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{Ur as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Zt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,wt as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,zr as acceptDirectYoloSetupCheckpoint,Wr as beginDirectYoloStoryCommit,io as captureDirectYoloCheckoutEvidence,to as captureDirectYoloStoryGovernance,oo as captureEpicOriginBindingAtYoloopStart,Jr as directYoloCommitIdempotencyKey,Zr as directYoloWaveQaCoverage,Qt as directYoloWaveReceiptRef,Sr as fetchOriginForYoloopStart,Mr as finalizeDirectYoloStoryCheckpoint,pr as isDirectYoloWriteSetExtensionScope,Gr as issueDirectYoloSetupLeaseHandoff,eo as persistDirectYoloWaveStoryCheckpoint,Tr as prepareDirectYoloSetup,Xr as pushDirectYoloWaveHead,ro as readYoloopStartEpic,Vr as recoverLegacyDirectYoloStoryCheckpoint,Fr as resolveDirectYoloIntegrationAuthority,Qr as runDirectYoloWaveP205,Yr as validateDirectYoloWriteSet,Kr as verifyDirectYoloIntegrationCommit,Rr as yoloopStartGitNetworkExecOptions};
|
|
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(!ue(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")!==[...er].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 de(e,t){const o=await Fe(e,t);ue(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 ht="direct-yolo-worktree-setup-reservation",rr=["schemaVersion","kind","epicId","ownerStoryId","sessionId","idempotencyKey","leaseId","acquiredAt","expiresAt","setupHeadSha"],or=3600*1e3;async function Ue(e,t){const o=await Ne(e),r=await $e(o,"setup-reservations"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function ir(e,t){const o=await Ue(e,t.ownerStoryId);await qe(o.parent,o.name,`${JSON.stringify(t,null,2)}
|
|
3
|
+
`),await ee(o.path,o.parent)}async function yt(e,t){try{const o=await Ue(e,t);if(!ue(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")!==[...rr].sort().join("\0")||r.schemaVersion!==1||r.kind!==ht||r.ownerStoryId!==t||!be(r.epicId)||!be(r.leaseId)||typeof r.sessionId!="string"||!/^setup-[a-f0-9]{64}$/.test(r.sessionId)||r.idempotencyKey!==r.sessionId||typeof r.setupHeadSha!="string"||!/^[a-f0-9]{40,64}$/.test(r.setupHeadSha)||!Number.isFinite(Date.parse(String(r.acquiredAt)))||!(Date.parse(String(r.expiresAt))>Date.parse(String(r.acquiredAt)))?void 0:r}catch{return}}async function nr(e,t){const o=await Ue(e,t);ue(o.path)&&await ct(o.parent,o.name)}async function gt(e,t,o,r,i){const n=await yt(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 mt(e,t){const o=await Ne(e),r=await $e(o,"handoffs"),i=`direct-${B(t)}.json`;return{parent:r,name:i,path:X(r,i)}}async function Ze(e,t){const o=await mt(e,t.storyId);await qe(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 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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isAbsolute as l,relative as c,resolve as s,sep as i}from"node:path";function p(o,n){const e=new Set;for(const r of n.split("\0")){if(!r.startsWith("worktree "))continue;const t=c(s(o),s(r.slice(9)));t&&t!==".."&&!t.startsWith(`..${i}`)&&!l(t)&&e.add(`${t.split(i).join("/")}/`)}return e}export{p as registeredNestedWorktreeDirectories};
|