@ornexus/neocortex 4.64.0 → 4.64.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/install.ps1 CHANGED
@@ -17,7 +17,7 @@ param(
17
17
  [string]$ServerUrl = ('https://{0}.{1}.{2}' -f 'api','neocortex','sh')
18
18
  )
19
19
 
20
- $VERSION = "4.64.0"
20
+ $VERSION = "4.64.1"
21
21
 
22
22
  # =============================================================================
23
23
  # CONFIGURACOES
package/install.sh CHANGED
@@ -4,7 +4,7 @@
4
4
  # Development Orchestrator
5
5
 
6
6
  # Versao do instalador
7
- VERSION="4.64.0"
7
+ VERSION="4.64.1"
8
8
 
9
9
  # Flags
10
10
  MIGRATION_DETECTED=false
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ornexus/neocortex",
3
- "version": "4.64.0",
4
- "description": "Neocortex v4.64.0",
3
+ "version": "4.64.1",
4
+ "description": "Neocortex v4.64.1",
5
5
  "keywords": [
6
6
  "claude",
7
7
  "claude-code",
@@ -1,3 +1,3 @@
1
- import{execFile as ot}from"node:child_process";import{createHash as it,randomBytes as $e,timingSafeEqual as nt}from"node:crypto";import{existsSync as Pe}from"node:fs";import{readFile as P,realpath as he}from"node:fs/promises";import{join as G,resolve as O}from"node:path";import{promisify as at}from"node:util";import{readRootMemoryEffectForCheckpoint as ct}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as st,verifyRootMemoryPhysicalWriteSet as ue}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as dt,resolveEpicStoryIds as ft}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as qe,storyWriteSetCovers as ht,validateStoryWriteScope as ut}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as le,computeImmutableStoryQaEvidenceDigest as lt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as pt,computeLegacyDirectYoloRecoveryReceiptRef as yt,ensureRuntimeEpic as M,ensureRuntimeStory as ye,ensureGitLifecyclePrivateChildDirectory as Ne,executeP205TransientAuthorities as gt,executeP205TransientAuthority as mt,isP226GateReasonCode as ge,projectP205TransientExecutionEvidence as ze,publicStoryReviewArtifactFromGit as oe,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as wt,mutateGitLifecycleRuntime as L,P205_COMPLETE_COMMAND as Te,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Me,STORY_WRITE_SET_MAX_ENTRIES as vt,storyWriteSetExtensionPaths as Rt,assertGitLifecyclePrivateFile as ie,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as It,verifyGitLifecyclePhysicalIntegrationLock as ne,verifyAcceptedGitLifecycleStoryCheckpoint as me}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as We,anchoredRemoveFile as St}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as xt,trailerReasonKey as we,trailerValue as ve}from"./neocortex-trailers.js";import{StoryWorktreeManager as bt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as kt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Ge,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as W}from"./git-lifecycle-step-ids.js";const ee=at(ot),ae=3600*1e3;async function dr(e){let t,o=!1;try{const r=await Re(e.projectRoot,e.storyId);if(await Ke(r.projectRoot)){if(e.expiredSetupRecovery)return s("direct-yolo-expired-setup-recovery-invalid");const m=await Fe(r);return{ok:!0,value:Ye(r,m,!1)}}const i=N(e.nowIso),n=Date.parse(i),f=await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await l(r.projectRoot,["rev-parse","HEAD"]),d=await C(r.projectRoot,{required:!0}),a=p(d.epics[r.epicId]),u=p(a?.branch_lease),g=e.expiredSetupRecovery;if(g&&!qt(g,d.revision,u,e.storyId,n))return s("direct-yolo-expired-setup-recovery-invalid");const w=u&&Number.isFinite(Date.parse(String(u.expiresAt)))&&Date.parse(String(u.expiresAt))>n;if(w&&u?.ownerStoryId!==e.storyId)return s("direct-yolo-writer-active");let h=K(a?.origin_binding,r.executionBranch,r.originBranch),v;if(f===r.executionBranch){if(!h){if(a?.origin_binding!==void 0&&a?.origin_binding!==null||w)return s("direct-yolo-origin-binding-invalid");const m=await Mt(r,c,i);if(!m.ok)return m;h=m.value.binding,v={originRef:m.value.originRef,originHeadSha:m.value.binding.originHeadSha}}}else{if(f!==r.originBranch)return s("direct-yolo-current-branch-mismatch");if(h&&h.originHeadSha!==c){if(!g||!await B(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,c]))return s("direct-yolo-origin-binding-conflict");const y=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",y]))return s("direct-yolo-execution-branch-missing");const x=await l(r.projectRoot,["rev-parse",y]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",x,c]))return s("direct-yolo-execution-branch-diverged")}if(h??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await re(r.projectRoot)).some(y=>y.branch===r.executionBranch&&O(y.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const S=await z(r.projectRoot),I=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",I])){const y=await l(r.projectRoot,["rev-parse",I]);if(y!==c){if(!await B(r.projectRoot,["merge-base","--is-ancestor",y,c]))return s("direct-yolo-execution-branch-diverged");g||await l(r.projectRoot,["update-ref",I,c,y])}g?t={checkoutBefore:S,executionRef:I,executionBranch:r.executionBranch,executionHead:y,originBranch:r.originBranch,originHead:c}:await l(r.projectRoot,["switch",r.executionBranch])}else{if(g)return s("direct-yolo-execution-branch-missing");await l(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await z(r.projectRoot)!==S)return s("direct-yolo-checkout-payload-raced")}const R=t?.originHead??await l(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return s("direct-yolo-current-branch-mismatch");if(w&&u?.ownerStoryId===e.storyId)return u.setupHeadSha!==R?s("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:de(r,h,String(u.expiresAt),!0)};const b=i,k=new Date(n+3600*1e3).toISOString(),D=`setup-${$e(32).toString("hex")}`,j=g?d:await C(r.projectRoot,{required:!0});return await L(r.projectRoot,m=>{const S=M(m,r.epicId),I=p(S.branch_lease);if(g&&JSON.stringify(I)!==JSON.stringify(g.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(I&&Date.parse(String(I.expiresAt))>n&&I.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const y=K(S.origin_binding,r.executionBranch,r.originBranch);if(S.origin_binding&&!y)throw new Error("direct-yolo-origin-binding-conflict");if(y&&JSON.stringify(y)!==JSON.stringify(h))throw new Error("direct-yolo-origin-binding-conflict");S.branch_mode="epic",S.execution_branch=r.executionBranch,S.origin_branch=r.originBranch,S.graph_revision=r.graphRevision,S.origin_binding=h,S.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:b,expiresAt:k,setupHeadSha:R}},{expectedRevision:g?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot)||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await z(r.projectRoot)!==t.checkoutBefore||!await B(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 z(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==R)throw new Error("direct-yolo-setup-physical-state-raced");if(v&&(await l(r.projectRoot,["rev-parse","--verify","--quiet",`${v.originRef}^{commit}`]).catch(()=>"")!==v.originHeadSha||await He(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,R])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:de(r,h,k,!1)}}catch(r){return o&&t&&await Nt(O(e.projectRoot),t).catch(()=>{}),s(X(r,"direct-yolo-setup-failed"))}}async function fr(e){let t;try{const o=await Re(e.projectRoot,e.storyId);if(await Ke(o.projectRoot))return await Dt(o);const r=await V(e.projectRoot,e.storyId),i=N(e.nowIso),n=G(r.projectRoot,".neocortex/state.json"),f=await P(n,"utf8"),c=await z(r.projectRoot),d=await l(r.projectRoot,["rev-parse","HEAD"]),a=`refs/heads/${r.executionBranch}`,u=await C(r.projectRoot,{required:!0}),g=p(u.epics[r.epicId]),w=K(g?.origin_binding,r.executionBranch,r.originBranch),h=p(g?.branch_lease);if(!w)return s("direct-yolo-origin-binding-invalid");if(!h||!ke(h,e.storyId,i)||h?.sessionId!==h?.idempotencyKey)return s("direct-yolo-setup-lease-invalid");const v=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(h.sessionId),idempotencyKey:String(h.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!v.ok)return s(v.reasonCode);if(t=v,d!==h.setupHeadSha||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,d])||await l(r.projectRoot,["rev-parse",a])!==d)return s("direct-yolo-setup-head-mismatch");if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const b=p(JSON.parse(f)),k=p(p(b?.stories)?.[e.storyId]),D=p(u.stories[e.storyId]);if(!k||!["backlog","ready_to_start"].includes(String(k.status))||k.steps_completed!==void 0&&(!Array.isArray(k.steps_completed)||k.steps_completed.length>0)||k.branch_name||k.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const j=D?.status==="branch-ready"&&D.last_step===W&&Array.isArray(D.steps_completed)&&D.steps_completed.length===1&&D.steps_completed[0]===W&&U(D).sort().join(",")==="last_step,status,steps_completed";if(D&&U(D).length>0&&!j)return s("direct-yolo-setup-story-progress-conflict");const m=async()=>{if(Date.parse(String(h.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await ne(t.path,t.owner)||await P(n,"utf8")!==f||await z(r.projectRoot)!==c||await l(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await l(r.projectRoot,["rev-parse","HEAD"])!==d||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,d])||await l(r.projectRoot,["rev-parse",a])!==d)throw new Error("direct-yolo-setup-physical-state-raced")};return j?await m():await L(r.projectRoot,S=>{const I=p(S.epics[r.epicId]),y=ye(S,e.storyId);if(JSON.stringify(I?.branch_lease)!==JSON.stringify(h)||JSON.stringify(I?.origin_binding)!==JSON.stringify(w)||I?.graph_revision!==r.graphRevision||U(y).length>0)throw new Error("direct-yolo-setup-runtime-raced");y.status="branch-ready",y.last_step=W,y.steps_completed=[W]},{expectedRevision:u.revision,preCommit:m}),{ok:!0,value:Object.freeze({...de(r,w,String(h.expiresAt),j),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:d})}}catch(o){return s(X(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function hr(e){try{const t=await V(e.projectRoot,e.storyId),o=q(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Z(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return s(r.reasonCode);if(t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await l(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),oe(t.projectRoot,e.storyId,":")?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(q(await _(t.projectRoot,["diff","--name-only","-z"])).some(y=>o.includes(y)))return s("direct-yolo-user-overlap");const f=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!f)return s("direct-yolo-staged-diff-empty");const c=A(f),d=A([...t.authorizedWriteSet].sort().join("\0")),a=N(e.nowIso),u=await C(t.projectRoot,{required:!0}),g=p(u.epics[t.epicId]?.branch_lease);if(!ke(g,e.storyId,a))return s("direct-yolo-setup-handoff-owner-invalid");const w=String(g.sessionId),h=String(g.expiresAt),v=new Date(Math.min(Date.parse(h),Date.parse(a)+300*1e3)).toISOString(),R=await J(t.projectRoot,e.storyId),b=R?.state==="issued"&&R.fromSessionId===w&&R.bundleDigest===c&&R.claimRevision===d&&Date.parse(R.expiresAt)>Date.parse(a),k=b?R.expiresAt:v,D=b?R.token:$e(32).toString("base64url"),j=A(D),m=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:w,tokenDigest:j,bundleDigest:c,claimRevision:d,expiresAt:k}),S=A(JSON.stringify(m)),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:k,persistent:!1,createdAt:a});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await De(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:w,token:D,tokenDigest:j,bundleDigest:c,claimRevision:d,grantDigest:S,expiresAt:k}),await L(t.projectRoot,y=>{const x=p(M(y,t.epicId).branch_lease);if(!ke(x,e.storyId,a)||x?.sessionId!==w||x.idempotencyKey!==w)throw new Error("direct-yolo-setup-handoff-owner-raced");x.handoffGrant=m},{expectedRevision:u.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");const y=await J(t.projectRoot,e.storyId);if(!y||y.state!=="issued"||y.grantDigest!==S||y.tokenDigest!==j)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await Y(I.path,I.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:w,bundleDigest:c,claimRevision:d,grantDigest:S,expiresAt:k,reused:b,publicSafe:!0})}}catch(t){return s(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function ur(e){try{const t=await V(e.projectRoot,e.storyId),o=await l(t.projectRoot,["rev-parse","HEAD"]),r=q(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Z(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return s(i.reasonCode);t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=oe(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(q(await _(t.projectRoot,["diff","--name-only","-z"])).some(x=>r.includes(x)))return s("direct-yolo-user-overlap");const c=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return s("direct-yolo-staged-diff-empty");const d=A(c),a=A([...t.authorizedWriteSet].sort().join("\0")),u=await Ze(t.projectRoot,e.storyId),g=u.state==="valid"&&u.plan.epicId===t.epicId&&u.plan.executionBranch===t.executionBranch&&u.plan.preparedBase===o&&u.plan.bundleDigest===d&&u.plan.claimRevision===a?u.plan:void 0,w=g?.graphRevision??t.graphRevision,h=xe({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,graphRevision:w,claimRevision:a}),v=N(e.nowIso),R={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:w,preparedBase:o,bundleDigest:d,claimRevision:a,idempotencyKey:h,issuedAt:g?.issuedAt??v};let b=e.setupLeaseHandoff??await _t(t.projectRoot,e.storyId,d,a,v);const k=await C(t.projectRoot,{required:!0}),D=p(k.epics[t.epicId]?.branch_lease),j=D?.ownerStoryId===e.storyId&&D.sessionId===h&&D.idempotencyKey===h&&typeof D.expiresAt=="string"&&Date.parse(D.expiresAt)>Date.parse(v)?D:void 0;if(j&&e.setupLeaseHandoff)return s("direct-yolo-setup-handoff-replayed");const m=p(j?.handoffConsumption);if(m){const x=await J(t.projectRoot,e.storyId);if(!x||!["consuming","consumed"].includes(x.state)||x.fromSessionId!==m.fromSessionId||x.tokenDigest!==m.tokenDigest||x.bundleDigest!==d||x.claimRevision!==a||m.bundleDigest!==d||m.claimRevision!==a||x.consumedBySessionId!==h||m.consumedBySessionId!==h)return s("direct-yolo-setup-handoff-consume-invalid");if(x.state==="consuming"){if(!x.token||A(x.token)!==x.tokenDigest)return s("direct-yolo-setup-handoff-consume-invalid");b={sessionId:x.fromSessionId,token:x.token}}}const S=j?String(j.expiresAt):new Date(Date.parse(v)+ae).toISOString(),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:S,persistent:!0,createdAt:j&&typeof j.acquiredAt=="string"?j.acquiredAt:v});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{b&&e.setupLeaseHandoff===void 0&&(await Ct(t.projectRoot,e.storyId,b.sessionId,b.token,h,v),await e.setupHandoffFault?.("after-consuming-persisted")),await L(t.projectRoot,x=>{const $=M(x,t.epicId),E=p($.branch_lease),H=E&&Date.parse(String(E.expiresAt))>Date.parse(v),T=E?.ownerStoryId===e.storyId&&E.sessionId===h&&E.idempotencyKey===h,rt=E?.ownerStoryId===e.storyId&&E.sessionId===E.idempotencyKey&&typeof E.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(E.idempotencyKey),fe=H&&rt&&Ot({current:E,handoff:b,storyId:e.storyId,bundleDigest:d,claimRevision:a,nowIso:v});if(b&&H&&!T&&!fe)throw new Error("direct-yolo-setup-handoff-invalid");if(H&&!T&&!fe)throw new Error("direct-yolo-writer-active");const Oe=fe?p(E?.handoffGrant):void 0,Le=Oe?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(E?.sessionId),tokenDigest:String(Oe.tokenDigest),bundleDigest:d,claimRevision:a,consumedBySessionId:h,consumedAt:v}:void 0;$.branch_mode="epic",$.execution_branch=t.executionBranch,$.origin_branch=t.originBranch,$.graph_revision=t.graphRevision,$.branch_lease=H&&T?E:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:v,expiresAt:S,...Le?{handoffConsumption:Le}:{}}},{expectedRevision:k.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");await Bt(t.projectRoot,R)}})}catch(x){throw await Y(I.path,I.owner).catch(()=>{}),x}b&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Ht(t.projectRoot,t.epicId,e.storyId,b.sessionId,b.token,d,a,h,v));const y=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${d}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${w}`,`Neocortex-Claim-Revision: ${a}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${st(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:d,reviewArtifactDigest:n.digest,graphRevision:w,claimRevision:a,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:y})}}catch(t){return s(X(t,"direct-yolo-begin-failed"))}}async function lr(e){let t,o,r;try{const i=await V(e.projectRoot,e.storyId);t=i;const n=await l(i.projectRoot,["rev-parse","HEAD"]);let f=await C(i.projectRoot,{required:!0});const c=p(f.stories[e.storyId]?.checkpoint);if(c){const S=typeof c.headSha=="string"?c.headSha:"",I=typeof c.graphRevision=="string"?c.graphRevision:"",y=/^[a-f0-9]{40,64}$/.test(S)?q(await _(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",S])):[],x=Z(y,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(S)&&await B(i.projectRoot,["merge-base","--is-ancestor",S,n]))||!/^[a-f0-9]{64}$/.test(I)||!x.ok)return s("direct-yolo-replay-invalid");const E=await Ae(e,i.projectRoot,n,I);if(!await me(i.projectRoot,c,e.storyId,i.epicId,i.executionBranch,E.transientAuthority,i.authorizedWriteSet))return s("direct-yolo-replay-invalid");if(!await Be(i.projectRoot,i.executionBranch,n,y))return s("direct-yolo-replay-head-raced");if(e.push&&!await Je(i.projectRoot,e.remote??"origin",i.executionBranch,S))return s("direct-yolo-remote-head-mismatch");const H=Array.isArray(c.receiptRefs)?c.receiptRefs.find(T=>typeof T=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(T)):void 0;return H&&typeof c.idempotencyKey=="string"&&await It(i.projectRoot,{storyId:e.storyId,idempotencyKey:c.idempotencyKey,ownerDigest:H.slice(20)}),await ce(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:c}}const d=n,a=await Ve(i,e.storyId,d);if(!a.ok)return s(a.reasonCode);const{baseSha:u,changedPaths:g,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R}=a.value,b=p(f.epics[i.epicId]?.branch_lease),k=N(e.nowIso),D=b?.ownerStoryId===e.storyId&&b.idempotencyKey===R&&b.sessionId===R&&Date.parse(String(b.expiresAt))>Date.now()?b:void 0;if(b&&Date.parse(String(b.expiresAt))>Date.now()&&!D)return s("direct-yolo-writer-active");const j=D??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:R,idempotencyKey:R,acquiredAt:k,expiresAt:new Date(Date.parse(k)+ae).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:R,idempotencyKey:R,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return s(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,D||(f=(await L(i.projectRoot,I=>{const y=M(I,i.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(k))throw new Error("direct-yolo-writer-active");if(y.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");y.branch_lease=j},{expectedRevision:f.revision})).document),o=j;{const S=await Ae(e,i.projectRoot,d,h);if(!await Be(i.projectRoot,i.executionBranch,d,g))return s("direct-yolo-head-raced");if(e.push){const x=te(e.remote??"origin");if(await l(i.projectRoot,["push",x,i.executionBranch]),!await _e(i.projectRoot,x,i.executionBranch,d))return s("direct-yolo-remote-head-mismatch")}const I=await Ie({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:u,headSha:d,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R,qaExecution:S,physicalLockOwnerDigest:pe(m.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await Se({projectRoot:i.projectRoot,checkpoint:I,remote:e.push?e.remote??"origin":void 0,expectedRevision:f.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:h,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:S.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ce(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:I}):s("direct-yolo-checkpoint-persist-failed")}}catch(i){return s(X(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await Ee(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await $t(t,e.storyId).catch(()=>{})}}async function Ve(e,t,o){const r=await l(e.projectRoot,["rev-parse",`${o}^`]),i=await _(e.projectRoot,["show","--no-patch","--format=%B",o]),n=q(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),f=Z(n,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!f.ok)return s(f.reasonCode);e.rootMemoryEffect&&ue(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const c=A([...e.authorizedWriteSet].sort().join("\0")),d=await Ze(e.projectRoot,t);if(d.state==="invalid")return s("direct-yolo-commit-plan-invalid");const a=d.state==="valid"?d.plan:void 0;if(a&&(a.epicId!==e.epicId||a.executionBranch!==e.executionBranch))return s("direct-yolo-commit-plan-invalid");if(a&&a.claimRevision!==c)return s("direct-yolo-commit-plan-claim-changed");if(a&&a.preparedBase!==r)return s("direct-yolo-commit-plan-base-mismatch");const u=xt(i);if(!u.ok)return s(`direct-yolo-trailer-duplicate:${u.key}`);const g=u.values,w=a?.graphRevision??e.graphRevision,h=c,v=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",a?.bundleDigest??""],["Neocortex-Graph-Revision",w],["Neocortex-Claim-Revision",h]];for(const[m,S]of v){const I=ve(g,m);if(I===void 0)return s(`direct-yolo-trailer-missing:${we(m)}`);if(m==="Neocortex-Bundle-Digest"&&!a){if(!/^[a-f0-9]{64}$/.test(I))return s(`direct-yolo-trailer-mismatch:${we(m)}`);continue}if(I!==S)return s(`direct-yolo-trailer-mismatch:${we(m)}`)}const R=ve(g,"Neocortex-Bundle-Digest"),b=oe(e.projectRoot,t,o);if(b?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");const k=ve(g,"Neocortex-Review-Artifact-Digest");if(k!==void 0&&k!==b.digest)return s("direct-yolo-review-artifact-digest-mismatch");const D=A(await _(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(R!==D)return s("direct-yolo-bundle-digest-mismatch");const j=xe({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:R,graphRevision:w,claimRevision:h});return a&&a.idempotencyKey!==j?s("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:n,bundleDigest:R,graphRevision:w,claimRevision:h,idempotencyKey:j}}}async function pr(e){try{const t=await V(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return s("direct-yolo-recovery-commit-invalid");const o=await l(t.projectRoot,["rev-parse",e.commitSha]);if(wt[e.storyId]!==o)return s("direct-yolo-recovery-not-allowlisted");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o)return s("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 _(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=q(await _(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Z(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return s("direct-yolo-recovery-write-set-invalid");const c=A(i),d=A([...n].sort().join("\0")),a=A(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),u=N(e.nowIso),g=new Date(Date.parse(u)+ae).toISOString(),w=await C(t.projectRoot,{required:!0}),h=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:a,idempotencyKey:a,expiresAt:g,persistent:!0,createdAt:u});if(!h.ok)return s(h.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:a,idempotencyKey:a,acquiredAt:u,expiresAt:g};let R=!1;try{const b=await L(t.projectRoot,I=>{const y=M(I,t.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(u)&&!je(x,v))throw new Error("direct-yolo-recovery-writer-active");if(y.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");y.branch_mode="epic",y.execution_branch=t.executionBranch,y.origin_branch=t.originBranch,y.branch_lease=v},{expectedRevision:w.revision});R=!0;const k=await Ae(e,t.projectRoot,o,t.graphRevision);if(!await Be(t.projectRoot,t.executionBranch,o,n))return s("direct-yolo-recovery-head-raced");if(e.push){const I=te(e.remote??"origin"),y=(await l(t.projectRoot,["ls-remote","--heads",I,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!y||!await B(t.projectRoot,["merge-base","--is-ancestor",o,y]))return s("direct-yolo-recovery-remote-proof-missing")}const D=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:d,idempotencyKey:a,qaExecution:k,physicalLockOwnerDigest:pe(h.owner),nowIso:u,legacyReceiptRef:void 0}),j=await yt(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!j)return s("direct-yolo-recovery-evidence-invalid");const m=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,j])});return await Se({projectRoot:t.projectRoot,checkpoint:m,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:b.document.revision,expectedLease:v,expectedGraphRevision:t.graphRevision,physicalLockPath:h.path,physicalLockOwner:h.owner,transientAuthority:k.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:m}:s("direct-yolo-recovery-persist-failed")}finally{await Y(h.path,h.owner).catch(()=>{}),R&&await Ee(t.projectRoot,t.epicId,v).catch(()=>{})}}catch(t){return s(X(t,"direct-yolo-recovery-failed"))}}async function Ke(e){const t=await he(await l(e,["rev-parse","--absolute-git-dir"])),o=await he(await l(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Fe(e){const t=await C(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(g=>g.storyId===e.storyId&&g.epicId===e.epicId&&g.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await he(await l(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const f=await new bt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!f.ok||f.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=K(p(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const d=r.syncedSha??r.baseSha,a=await l(e.projectRoot,["rev-parse","HEAD"]),u=`refs/heads/${e.executionBranch}`;if(a!==d||!await B(e.projectRoot,["merge-base","--is-ancestor",d,u])||!await B(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,d]))throw new Error("direct-yolo-worktree-base-divergent");if(f.value.clean!==!0||(await _(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:d,headSha:a,expiresAt:r.expiresAt,binding:c}}function Ye(e,t,o){return Object.freeze({...de(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function Dt(e){const t=await Fe(e),o=G(e.projectRoot,".neocortex/state.json"),r=await P(o,"utf8"),i=p(JSON.parse(r)),n=p(p(i?.stories)?.[e.storyId]),f=await C(e.projectRoot,{required:!0}),c=p(f.stories[e.storyId]);if(!n||!["backlog","ready_to_start"].includes(String(n.status))||n.steps_completed!==void 0&&(!Array.isArray(n.steps_completed)||n.steps_completed.length>0)||n.branch_name||n.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const d=c?.status==="branch-ready"&&c.last_step===W&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===W&&U(c).sort().join(",")==="last_step,status,steps_completed";return c&&U(c).length>0&&!d?s("direct-yolo-setup-story-progress-conflict"):(d||await L(e.projectRoot,a=>{const u=ye(a,e.storyId);if(U(u).length>0)throw new Error("direct-yolo-setup-runtime-raced");u.status="branch-ready",u.last_step=W,u.steps_completed=[W]},{expectedRevision:f.revision,preCommit:async()=>{if(await P(o,"utf8")!==r||await l(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await l(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await _(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Ye(e,t,d),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function yr(e,t){const o=await V(e,t),r=await C(o.projectRoot,{required:!0}),i=K(p(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function gr(e,t,o,r){return Z(e,t,o,r)}function mr(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const wr=ae,jt="p205-wave:";function vr(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=A(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function Et(e){return`${jt}${e.waveHeadSha}:${e.waveDigest}`}async function Rr(e){let t;try{t=await gt(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:ge(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:ge(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Ir(e,t,o,r){const i=te(t);return await l(e,["push",i,o]),_e(e,i,o,r)}async function Sr(e){try{const t=await V(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return s("direct-yolo-wave-coverage-invalid");if(await l(t.projectRoot,["rev-parse","HEAD"])!==o||await l(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await B(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return s("direct-yolo-wave-head-raced");const i=await C(t.projectRoot,{required:!0}),n=p(i.stories[e.storyId]?.checkpoint);if(n){if(n.headSha!==e.headSha)return s("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(n.graphRevision));return await me(t.projectRoot,n,e.storyId,t.epicId,t.executionBranch,k??null,t.authorizedWriteSet)?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:n}):s("direct-yolo-replay-invalid")}const f=await Ve(t,e.storyId,e.headSha);if(!f.ok)return s(f.reasonCode);const{baseSha:c,bundleDigest:d,graphRevision:a,claimRevision:u,idempotencyKey:g}=f.value,w=r===0?void 0:e.coverage.waveCommitShas[r-1];if(w!==void 0&&c!==w)return s("direct-yolo-wave-chain-invalid");const h=e.authorities.get(a),v=ze(h);if(!h||!v||v.executionHeadSha!==o||v.graphRevision!==a)return s("direct-yolo-wave-qa-unbound");const R=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:c,headSha:e.headSha,bundleDigest:d,graphRevision:a,claimRevision:u,idempotencyKey:g,qaExecution:{contract:"P205-CI-02",command:Te,manifestDigest:v.manifestDigest,gateIds:v.gateIds,resultDigest:v.resultDigest,transientAuthority:h},physicalLockOwnerDigest:pe(e.physicalLock.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[Et(e.coverage)]});return await Se({projectRoot:t.projectRoot,checkpoint:R,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:a,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:h,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:R}):s("direct-yolo-checkpoint-persist-failed")}catch(t){return s(X(t,"direct-yolo-wave-persist-failed"))}}async function Re(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=O(e),r=p(JSON.parse(await P(G(o,".neocortex/state.json"),"utf8"))),i=await C(o,{required:!0}),n=le(r,i),f=p(n.stories),c=p(n.epics),d=p(f?.[t]),a=String(d?.epic_id??t.split(".")[0]),u=p(c?.[a]),g=String(u?.execution_branch??""),w=String(u?.origin_branch??""),h=String(u?.graph_revision??""),v=Array.isArray(d?.files_to_modify)?d.files_to_modify:[],R=Rt(d).filter(Pt),b=[...v,...R],k=b.length>0?qe(t,b):void 0,D=k?.ok?k.scopes:[];if(!d)throw new Error("direct-yolo-story-state-missing");if(R.length>0&&D.length>vt)throw new Error("direct-yolo-write-set-too-large");if(u?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Q(g)||!await B(o,["check-ref-format","--branch",g]))throw new Error("direct-yolo-execution-branch-invalid");if(!Q(w)||!await B(o,["check-ref-format","--branch",w]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(h))throw new Error("direct-yolo-graph-revision-invalid");const j=await ct({projectRoot:o,storyId:t,graphRevision:h,executionBranch:g,childPaths:D});return{projectRoot:o,storyId:t,story:d,epicId:a,executionBranch:g,originBranch:w,graphRevision:h,authorizedWriteSet:D,rootMemoryEffect:j}}async function V(e,t){const o=await Re(e,t);if(await l(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function Ie(e){const t=e.nowIso,o=await _(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=q(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=lt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=pt({gitEvidenceDigest:i,headSha:e.headSha,graphRevision:e.graphRevision,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest}),f=`story-qa:${n}`,c=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,contract:e.qaExecution.contract,command:e.qaExecution.command,manifestDigest:e.qaExecution.manifestDigest,gateIds:e.qaExecution.gateIds,resultDigest:e.qaExecution.resultDigest,sourceEvidenceDigest:n,verdict:"passed",checkedAt:t,receiptRef:f}),d=oe(e.projectRoot,e.storyId,e.headSha);if(d?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const a=A(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,f,A(o),[...r].sort().join(","),d.digest].join("\0")),u=`story-review:${a}`,g=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:a,reviewArtifactDigest:d.digest,qaReceiptRef:f,verdict:"approved",reviewedAt:t,receiptRef:u}),w=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,f,u,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(w),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:g,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function Se(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await L(t,n=>{const f=M(n,o.epicId);if(e.expectedLease){const u=p(f.branch_lease);if(!je(u,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(u?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(f.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=ye(n,o.storyId),d=p(c.checkpoint);if(d&&d.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=Ge;const a=Array.isArray(c.steps_completed)?c.steps_completed.filter(u=>typeof u=="string"):[];c.steps_completed=[...new Set([...a,kt,Ge])],e.keepLease||(f.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await l(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await l(t,["rev-parse","HEAD"])!==n||await l(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await B(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await me(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 ne(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Je(t,r,o.branch,o.headSha):await _e(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Je(e,t,o,r){const i=te(t),n=(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await B(e,["merge-base","--is-ancestor",r,n]))}function xe(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const At=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function be(e,t){const o=await Me(e),r=await Ne(o,"commit-plans"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function Bt(e,t){const o=await be(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
- `),await ie(o.path,o.parent)}async function Ze(e,t){let o;try{o=await be(e,t)}catch{return{state:"invalid"}}try{if(!Pe(o.path))return{state:"absent"};await ie(o.path,o.parent);const r=await P(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=p(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...At].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Q(i.executionBranch)||typeof i.preparedBase!="string"||!/^[a-f0-9]{40,64}$/.test(i.preparedBase)||![i.graphRevision,i.bundleDigest,i.claimRevision,i.idempotencyKey].every(f=>typeof f=="string"&&/^[a-f0-9]{64}$/.test(f))||typeof i.issuedAt!="string"||!Number.isFinite(Date.parse(i.issuedAt)))return{state:"invalid"};const n=i;return n.idempotencyKey!==xe({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ce(e,t){const o=await be(e,t);Pe(o.path)&&await St(o.parent,o.name)}function ke(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function Ue(e,t){const o=await Me(e),r=await Ne(o,"handoffs"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function De(e,t){const o=await Ue(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
- `),await ie(o.path,o.parent)}async function J(e,t){try{const o=await Ue(e,t);await ie(o.path,o.parent);const r=JSON.parse(await P(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 _t(e,t,o,r,i){const n=await J(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||A(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Ct(e,t,o,r,i,n){const f=await J(e,t);if(!f||f.state==="consumed"||f.fromSessionId!==o||f.token!==r||f.tokenDigest!==A(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(f.state==="consuming"){if(f.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await De(e,{...f,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Ht(e,t,o,r,i,n,f,c,d){const a=await J(e,o);if(a?.state==="consumed"&&a.fromSessionId===r&&a.consumedBySessionId===c)return;const u=await C(e,{required:!0}),g=p(u.epics[t]?.branch_lease),w=p(g?.handoffConsumption);if(!a||a.state!=="consuming"||a.fromSessionId!==r||a.token!==i||a.tokenDigest!==A(i)||a.bundleDigest!==n||a.claimRevision!==f||a.consumedBySessionId!==c||g?.ownerStoryId!==o||g.sessionId!==c||w?.kind!=="direct-yolo-setup-handoff-consumption"||w.state!=="consumed"||w.fromSessionId!==r||w.tokenDigest!==a.tokenDigest||w.bundleDigest!==n||w.claimRevision!==f||w.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await De(e,{schemaVersion:1,kind:a.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:a.tokenDigest,bundleDigest:a.bundleDigest,claimRevision:a.claimRevision,grantDigest:a.grantDigest,expiresAt:a.expiresAt,consumedBySessionId:c,consumedAt:d})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function Ot(e){const t=p(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?A(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&Lt(t.tokenDigest,r))}function Lt(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&nt(o,r)}function je(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Ee(e,t,o){await L(e,r=>{const i=M(r,t),n=p(i.branch_lease);je(n,o)&&(i.branch_lease=null)})}async function $t(e,t){const o=await C(e.projectRoot,{required:!0}),r=p(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Qe(r.sessionId)||!Qe(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 Ee(e.projectRoot,e.epicId,r)}async function Ae(e,t,o,r){const i=await mt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=ze(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Te,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function Be(e,t,o,r){return await l(e,["rev-parse","HEAD"])!==o||await l(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function _e(e,t,o,r){const i=te(t);return(await l(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Z(e,t,o,r){if(e.length===0||e.some(f=>!Ce(f)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=t.length>0?qe(o,t):void 0;return i?.ok?[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`].every(f=>e.includes(f))?r&&(r.storyId!==o||r.childClaimRevision!==A([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(f=>!ht(i.scopes,f)&&!r?.files.some(c=>c.path===f))?{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 U(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function Pt(e){return typeof e!="string"||e.length>512||!Ce(e)||!ut(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Ce(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Qe(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Q(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function te(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function A(e){return it("sha256").update(e).digest("hex")}function q(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function qt(e,t,o,r,i){const n=p(e.expectedLease),f=n?.sessionId,c=Date.parse(String(n?.expiresAt??""));return e.schemaVersion===1&&Number.isSafeInteger(e.expectedRuntimeRevision)&&e.expectedRuntimeRevision===t&&!!o&&JSON.stringify(o)===JSON.stringify(n)&&n?.schemaVersion===1&&n.ownerStoryId===r&&typeof f=="string"&&/^setup-[a-f0-9]{64}$/.test(f)&&n.idempotencyKey===f&&Number.isFinite(c)&&c<=i}async function Nt(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 z(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 z(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(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 zt=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],Tt=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function K(e,t,o){const r=p(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!==zt.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==Tt.join("\0")?void 0:r}async function Mt(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await B(e.projectRoot,["show-ref","--verify","--quiet",r]))return s("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 s("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await re(e.projectRoot)).some(d=>d.branch===e.executionBranch&&O(d.path)!==e.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const f=`refs/heads/${e.executionBranch}`;if(await l(e.projectRoot,["rev-parse","--verify","--quiet",f]).catch(()=>"")!==t)return s("direct-yolo-setup-physical-state-raced");const c=await He(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?s("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?s("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}const Xe=3e4,Wt=3,Gt="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class se extends Error{}function Vt(e,t=Xe){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:Gt}}}}async function Kt(e){if(!Q(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ee("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:O(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Vt(process.env,e.fetchTimeoutMs??Xe)}),{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 Ft=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function xr(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=O(e),i=p(JSON.parse(await P(G(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await C(r),f=le(i,n),c=p(p(f.epics)?.[t]);if(!c)return o;const d=et(f,t,c),a=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,u=typeof c.origin_branch=="string"&&c.origin_branch.length>0?c.origin_branch:String(p(i.config)?.default_branch??""),g=p(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:d,terminal:Ft.has(String(c.status??"").toLowerCase()),bound:!!K(g,a,u),executionBranch:a,originBranch:u})}catch{return o}}function et(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=p(e.stories)??{},n=ft(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const d=p(r[c]);return d?[{...d,id:c}]:[]}),f=dt({...o,id:t},n);return f.mode==="epic"&&(f.source==="new-epic-default"||f.source==="epic-boundary")?"resolved-epic":"not-epic"}function tt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function br(e){const t=N(e.nowIso),o=Date.parse(t),r=(c,d={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...d,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=O(e.projectRoot);let n=e.originFetch,f="origin-binding-start-raced";for(let c=0;c<Wt;c+=1){let d,a={};try{const u=p(JSON.parse(await P(G(i,".neocortex/state.json"),"utf8")));if(!u)return r("origin-binding-start-state-invalid");const g=await C(i),w=le(u,g),h=p(p(w.epics)?.[e.epicId]);if(!h)return r("origin-binding-start-target-ambiguous");if(et(w,e.epicId,h)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const v=typeof h.execution_branch=="string"&&h.execution_branch.length>0?h.execution_branch:`epic/${e.epicId}`,R=typeof h.origin_branch=="string"&&h.origin_branch.length>0?h.origin_branch:String(p(u.config)?.default_branch??"");if(a={executionBranch:v,originBranch:R},!Q(v)||!Q(R)||v===R||!await B(i,["check-ref-format","--branch",v])||!await B(i,["check-ref-format","--branch",R]))return r("origin-binding-start-branch-invalid",a);const b=p(g.epics[e.epicId]),k=b?.origin_binding??h.origin_binding;if(k!=null){const E=K(k,v,R);return E?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:E.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",a)}if(tt(p(b?.branch_lease??h.branch_lease),o))return r("origin-binding-start-lease-inconsistent",a);if(n??=await Kt({projectRoot:i,originBranch:R,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,a);const D=`refs/remotes/origin/${R}`,j=`refs/heads/${R}`,m=await l(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),S=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(m)||m!==S)return r("origin-binding-start-origin-stale",a);if((await re(i)).some(E=>E.branch===v&&O(E.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",a);const y=`refs/heads/${v}`,x=await l(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(x){const E=await He(i,["merge-base","--is-ancestor",m,x]);if(E===1)return r("direct-yolo-origin-not-ancestor",a);if(E!==0)return r("direct-yolo-origin-ancestry-unverifiable",a)}const $={schemaVersion:2,originBranch:R,originHeadSha:m,executionBranch:v,capturedFrom:"branch-ref",capturedAt:t};return await L(i,E=>{const H=M(E,e.epicId);if(H.origin_binding!==void 0&&H.origin_binding!==null)throw new se("origin-binding-start-raced");if(tt(p(H.branch_lease),o))throw new se("origin-binding-start-lease-inconsistent");H.origin_binding=$},{expectedRevision:g.revision,preCommit:async()=>{const E=await l(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),H=await l(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>""),T=await l(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(E!==m||H!==m||T!==x)throw new se("origin-binding-start-raced");x||(await l(i,["update-ref",y,m,""]),d={ref:y,sha:m})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:m,outcome:"captured",executionRefCreated:d!==void 0,capturedAt:t})}catch(u){if(d&&await l(i,["update-ref","-d",d.ref,d.sha]).catch(()=>{}),u instanceof Error&&u.message==="git-lifecycle-runtime-revision-conflict"){f="origin-binding-start-raced";continue}return u instanceof se?r(u.message,a):r("origin-binding-start-failed",a)}}return r(f)}function de(e,t,o,r){return Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-receipt",storyId:e.storyId,epicId:e.epicId,executionBranch:e.executionBranch,originBranch:e.originBranch,originHeadSha:t.originHeadSha,leaseExpiresAt:o,reused:r,publicSafe:!0})}async function z(e){const t=q(await _(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ce(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await l(e,["hash-object","--no-filters","--",r])}`}));return A([await _(e,["diff","--cached","--binary","--full-index"]),await _(e,["diff","--binary","--full-index"]),await _(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function kr(e){const t=O(e),o=await l(t,["rev-parse","HEAD"]),r=await l(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await z(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 re(e){const t=[];let o;for(const r of(await _(e,["worktree","list","--porcelain","-z"])).split("\0"))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function X(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&ge(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function s(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function He(e,t){try{return await ee("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 ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function _(e,t){return String((await ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await ee("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{wr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,jt as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Xe as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,fr as acceptDirectYoloSetupCheckpoint,ur as beginDirectYoloStoryCommit,kr as captureDirectYoloCheckoutEvidence,br as captureEpicOriginBindingAtYoloopStart,mr as directYoloCommitIdempotencyKey,vr as directYoloWaveQaCoverage,Et as directYoloWaveReceiptRef,Kt as fetchOriginForYoloopStart,lr as finalizeDirectYoloStoryCheckpoint,Pt as isDirectYoloWriteSetExtensionScope,hr as issueDirectYoloSetupLeaseHandoff,Sr as persistDirectYoloWaveStoryCheckpoint,dr as prepareDirectYoloSetup,Ir as pushDirectYoloWaveHead,xr as readYoloopStartEpic,pr as recoverLegacyDirectYoloStoryCheckpoint,yr as resolveDirectYoloIntegrationAuthority,Rr as runDirectYoloWaveP205,gr as validateDirectYoloWriteSet,Vt as yoloopStartGitNetworkExecOptions};
1
+ import{execFile as it}from"node:child_process";import{createHash as nt,randomBytes as $e,timingSafeEqual as at}from"node:crypto";import{existsSync as qe}from"node:fs";import{readFile as q,realpath as he}from"node:fs/promises";import{join as G,resolve as O}from"node:path";import{promisify as ct}from"node:util";import{readRootMemoryEffectForCheckpoint as st}from"../private-execution/root-memory-scope.js";import{rootMemoryEffectDigest as dt,verifyRootMemoryPhysicalWriteSet as ue}from"../private-execution/root-memory-git-evidence.js";import{resolveBranchUnit as ft,resolveEpicStoryIds as ht}from"../../../shared/dist/yoloop/branch-unit.js";import{expandStoryWriteScope as Pe,storyWriteSetCovers as ut,validateStoryWriteScope as lt}from"../../../shared/dist/yoloop/story-write-scope.js";import{acquireGitLifecyclePhysicalIntegrationLock as F,applyGitLifecycleRuntimeOverlay as le,computeImmutableStoryQaEvidenceDigest as pt,computeGitLifecyclePhysicalIntegrationLockOwnerDigest as pe,computeP205StoryQaEvidenceDigest as yt,computeLegacyDirectYoloRecoveryReceiptRef as gt,ensureRuntimeEpic as M,ensureRuntimeStory as ye,ensureGitLifecyclePrivateChildDirectory as Ne,executeP205TransientAuthorities as mt,executeP205TransientAuthority as wt,isP226GateReasonCode as ge,projectP205TransientExecutionEvidence as ze,publicStoryReviewArtifactFromGit as oe,LEGACY_DIRECT_YOLO_RECOVERY_COMMITS as vt,mutateGitLifecycleRuntime as L,P205_COMPLETE_COMMAND as Te,readGitLifecycleRuntime as C,gitLifecycleRuntimeDirectory as Me,STORY_WRITE_SET_MAX_ENTRIES as Rt,storyWriteSetExtensionPaths as It,assertGitLifecyclePrivateFile as ie,releaseGitLifecyclePhysicalIntegrationLock as Y,releaseGitLifecyclePhysicalIntegrationLockForCheckpoint as St,verifyGitLifecyclePhysicalIntegrationLock as ne,verifyAcceptedGitLifecycleStoryCheckpoint as me}from"./git-lifecycle-store.js";import{anchoredAtomicWriteFile as We,anchoredRemoveFile as xt}from"./secure-filesystem-boundary.js";import{parseNeocortexTrailers as bt,trailerReasonKey as we,trailerValue as ve}from"./neocortex-trailers.js";import{StoryWorktreeManager as kt}from"./story-worktree-manager.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Dt,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as Ge,GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as W}from"./git-lifecycle-step-ids.js";const ee=ct(it),ae=3600*1e3;async function fr(e){let t,o=!1;try{const r=await Re(e.projectRoot,e.storyId);if(await Ke(r.projectRoot)){if(e.expiredSetupRecovery)return s("direct-yolo-expired-setup-recovery-invalid");const m=await Fe(r);return{ok:!0,value:Ye(r,m,!1)}}const i=N(e.nowIso),n=Date.parse(i),d=await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),c=await u(r.projectRoot,["rev-parse","HEAD"]),f=await C(r.projectRoot,{required:!0}),a=p(f.epics[r.epicId]),l=p(a?.branch_lease),g=e.expiredSetupRecovery;if(g&&!Nt(g,f.revision,l,e.storyId,n))return s("direct-yolo-expired-setup-recovery-invalid");const w=l&&Number.isFinite(Date.parse(String(l.expiresAt)))&&Date.parse(String(l.expiresAt))>n;if(w&&l?.ownerStoryId!==e.storyId)return s("direct-yolo-writer-active");let h=K(a?.origin_binding,r.executionBranch,r.originBranch),v;if(d===r.executionBranch){if(!h){if(a?.origin_binding!==void 0&&a?.origin_binding!==null||w)return s("direct-yolo-origin-binding-invalid");const m=await Wt(r,c,i);if(!m.ok)return m;h=m.value.binding,v={originRef:m.value.originRef,originHeadSha:m.value.binding.originHeadSha}}}else{if(d!==r.originBranch)return s("direct-yolo-current-branch-mismatch");if(h&&h.originHeadSha!==c){if(!g||!await B(r.projectRoot,["merge-base","--is-ancestor",h.originHeadSha,c]))return s("direct-yolo-origin-binding-conflict");const y=`refs/heads/${r.executionBranch}`;if(!await B(r.projectRoot,["show-ref","--verify","--quiet",y]))return s("direct-yolo-execution-branch-missing");const x=await u(r.projectRoot,["rev-parse",y]);if(!await B(r.projectRoot,["merge-base","--is-ancestor",x,c]))return s("direct-yolo-execution-branch-diverged")}if(h??={schemaVersion:1,originBranch:r.originBranch,originHeadSha:c,executionBranch:r.executionBranch,capturedFromCurrentCheckout:!0,capturedAt:i},(await re(r.projectRoot)).some(y=>y.branch===r.executionBranch&&O(y.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const S=await z(r.projectRoot),I=`refs/heads/${r.executionBranch}`;if(await B(r.projectRoot,["show-ref","--verify","--quiet",I])){const y=await u(r.projectRoot,["rev-parse",I]);if(y!==c){if(!await B(r.projectRoot,["merge-base","--is-ancestor",y,c]))return s("direct-yolo-execution-branch-diverged");g||await u(r.projectRoot,["update-ref",I,c,y])}g?t={checkoutBefore:S,executionRef:I,executionBranch:r.executionBranch,executionHead:y,originBranch:r.originBranch,originHead:c}:await u(r.projectRoot,["switch",r.executionBranch])}else{if(g)return s("direct-yolo-execution-branch-missing");await u(r.projectRoot,["switch","-c",r.executionBranch])}if(!t&&await z(r.projectRoot)!==S)return s("direct-yolo-checkout-payload-raced")}const R=t?.originHead??await u(r.projectRoot,["rev-parse","HEAD"]);if(!t&&await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch)return s("direct-yolo-current-branch-mismatch");if(w&&l?.ownerStoryId===e.storyId)return l.setupHeadSha!==R?s("direct-yolo-setup-lease-head-unbound"):{ok:!0,value:de(r,h,String(l.expiresAt),!0)};const b=i,k=new Date(n+3600*1e3).toISOString(),D=`setup-${$e(32).toString("hex")}`,j=g?f:await C(r.projectRoot,{required:!0});return await L(r.projectRoot,m=>{const S=M(m,r.epicId),I=p(S.branch_lease);if(g&&JSON.stringify(I)!==JSON.stringify(g.expectedLease))throw new Error("direct-yolo-expired-setup-recovery-raced");if(I&&Date.parse(String(I.expiresAt))>n&&I.ownerStoryId!==e.storyId)throw new Error("direct-yolo-writer-active");const y=K(S.origin_binding,r.executionBranch,r.originBranch);if(S.origin_binding&&!y)throw new Error("direct-yolo-origin-binding-conflict");if(y&&JSON.stringify(y)!==JSON.stringify(h))throw new Error("direct-yolo-origin-binding-conflict");S.branch_mode="epic",S.execution_branch=r.executionBranch,S.origin_branch=r.originBranch,S.graph_revision=r.graphRevision,S.origin_binding=h,S.branch_lease={schemaVersion:1,ownerStoryId:e.storyId,sessionId:D,idempotencyKey:D,acquiredAt:b,expiresAt:k,setupHeadSha:R}},{expectedRevision:g?.expectedRuntimeRevision??j.revision,preCommit:async()=>{if(t){if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot)||await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.originBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==t.originHead||await z(r.projectRoot)!==t.checkoutBefore||!await B(r.projectRoot,["show-ref","--verify","--quiet",t.executionRef])||await u(r.projectRoot,["rev-parse",t.executionRef])!==t.executionHead)throw new Error("direct-yolo-expired-setup-recovery-raced");if(o=!0,t.executionHead!==t.originHead&&await u(r.projectRoot,["update-ref",t.executionRef,t.originHead,t.executionHead]),await u(r.projectRoot,["switch",r.executionBranch]),await z(r.projectRoot)!==t.checkoutBefore)throw new Error("direct-yolo-checkout-payload-raced")}if(await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==R)throw new Error("direct-yolo-setup-physical-state-raced");if(v&&(await u(r.projectRoot,["rev-parse","--verify","--quiet",`${v.originRef}^{commit}`]).catch(()=>"")!==v.originHeadSha||await He(r.projectRoot,["merge-base","--is-ancestor",v.originHeadSha,R])!==0))throw new Error("direct-yolo-origin-ref-raced")}}),{ok:!0,value:de(r,h,k,!1)}}catch(r){return o&&t&&await zt(O(e.projectRoot),t).catch(()=>{}),s(X(r,"direct-yolo-setup-failed"))}}async function hr(e){let t;try{const o=await Re(e.projectRoot,e.storyId);if(await Ke(o.projectRoot))return await jt(o);const r=await V(e.projectRoot,e.storyId),i=N(e.nowIso),n=G(r.projectRoot,".neocortex/state.json"),d=await q(n,"utf8"),c=await z(r.projectRoot),f=await u(r.projectRoot,["rev-parse","HEAD"]),a=`refs/heads/${r.executionBranch}`,l=await C(r.projectRoot,{required:!0}),g=p(l.epics[r.epicId]),w=K(g?.origin_binding,r.executionBranch,r.originBranch),h=p(g?.branch_lease);if(!w)return s("direct-yolo-origin-binding-invalid");if(!h||!ke(h,e.storyId,i)||h?.sessionId!==h?.idempotencyKey)return s("direct-yolo-setup-lease-invalid");const v=await F(r.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:String(h.sessionId),idempotencyKey:String(h.idempotencyKey),expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1});if(!v.ok)return s(v.reasonCode);if(t=v,f!==h.setupHeadSha||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,f])||await u(r.projectRoot,["rev-parse",a])!==f)return s("direct-yolo-setup-head-mismatch");if((await re(r.projectRoot)).some(S=>S.branch===r.executionBranch&&O(S.path)!==r.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const b=p(JSON.parse(d)),k=p(p(b?.stories)?.[e.storyId]),D=p(l.stories[e.storyId]);if(!k||!["backlog","ready_to_start"].includes(String(k.status))||k.steps_completed!==void 0&&(!Array.isArray(k.steps_completed)||k.steps_completed.length>0)||k.branch_name||k.checkpoint)return s("direct-yolo-setup-story-progress-conflict");const j=D?.status==="branch-ready"&&D.last_step===W&&Array.isArray(D.steps_completed)&&D.steps_completed.length===1&&D.steps_completed[0]===W&&U(D).sort().join(",")==="last_step,status,steps_completed";if(D&&U(D).length>0&&!j)return s("direct-yolo-setup-story-progress-conflict");const m=async()=>{if(Date.parse(String(h.expiresAt))<=(e.nowIso?Date.parse(i):Date.now())||!t||!await ne(t.path,t.owner)||await q(n,"utf8")!==d||await z(r.projectRoot)!==c||await u(r.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==r.executionBranch||await u(r.projectRoot,["rev-parse","HEAD"])!==f||!await B(r.projectRoot,["merge-base","--is-ancestor",w.originHeadSha,f])||await u(r.projectRoot,["rev-parse",a])!==f)throw new Error("direct-yolo-setup-physical-state-raced")};return j?await m():await L(r.projectRoot,S=>{const I=p(S.epics[r.epicId]),y=ye(S,e.storyId);if(JSON.stringify(I?.branch_lease)!==JSON.stringify(h)||JSON.stringify(I?.origin_binding)!==JSON.stringify(w)||I?.graph_revision!==r.graphRevision||U(y).length>0)throw new Error("direct-yolo-setup-runtime-raced");y.status="branch-ready",y.last_step=W,y.steps_completed=[W]},{expectedRevision:l.revision,preCommit:m}),{ok:!0,value:Object.freeze({...de(r,w,String(h.expiresAt),j),checkpointAccepted:!0,graphRevision:r.graphRevision,headSha:f})}}catch(o){return s(X(o,"direct-yolo-setup-acceptance-failed"))}finally{t&&await Y(t.path,t.owner).catch(()=>{})}}async function ur(e){try{const t=await V(e.projectRoot,e.storyId),o=P(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),r=Z(o,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!r.ok)return s(r.reasonCode);if(t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:await u(t.projectRoot,["rev-parse","HEAD"]),headRef:":",childPaths:t.authorizedWriteSet}),oe(t.projectRoot,e.storyId,":")?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(P(await _(t.projectRoot,["diff","--name-only","-z"])).some(y=>o.includes(y)))return s("direct-yolo-user-overlap");const d=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!d)return s("direct-yolo-staged-diff-empty");const c=A(d),f=A([...t.authorizedWriteSet].sort().join("\0")),a=N(e.nowIso),l=await C(t.projectRoot,{required:!0}),g=p(l.epics[t.epicId]?.branch_lease);if(!ke(g,e.storyId,a))return s("direct-yolo-setup-handoff-owner-invalid");const w=String(g.sessionId),h=String(g.expiresAt),v=new Date(Math.min(Date.parse(h),Date.parse(a)+300*1e3)).toISOString(),R=await J(t.projectRoot,e.storyId),b=R?.state==="issued"&&R.fromSessionId===w&&R.bundleDigest===c&&R.claimRevision===f&&Date.parse(R.expiresAt)>Date.parse(a),k=b?R.expiresAt:v,D=b?R.token:$e(32).toString("base64url"),j=A(D),m=Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff",storyId:e.storyId,fromSessionId:w,tokenDigest:j,bundleDigest:c,claimRevision:f,expiresAt:k}),S=A(JSON.stringify(m)),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:w,idempotencyKey:w,expiresAt:k,persistent:!1,createdAt:a});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{await De(t.projectRoot,{schemaVersion:1,kind:"direct-yolo-setup-handoff-token",state:"issued",storyId:e.storyId,fromSessionId:w,token:D,tokenDigest:j,bundleDigest:c,claimRevision:f,grantDigest:S,expiresAt:k}),await L(t.projectRoot,y=>{const x=p(M(y,t.epicId).branch_lease);if(!ke(x,e.storyId,a)||x?.sessionId!==w||x.idempotencyKey!==w)throw new Error("direct-yolo-setup-handoff-owner-raced");x.handoffGrant=m},{expectedRevision:l.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");const y=await J(t.projectRoot,e.storyId);if(!y||y.state!=="issued"||y.grantDigest!==S||y.tokenDigest!==j)throw new Error("direct-yolo-setup-handoff-token-raced")}})}finally{await Y(I.path,I.owner).catch(()=>{})}return{ok:!0,value:Object.freeze({schemaVersion:1,kind:"direct-yolo-setup-handoff-receipt",storyId:e.storyId,sessionId:w,bundleDigest:c,claimRevision:f,grantDigest:S,expiresAt:k,reused:b,publicSafe:!0})}}catch(t){return s(t instanceof Error&&/^direct-yolo-/.test(t.message)?t.message:"direct-yolo-setup-handoff-failed")}}async function lr(e){try{const t=await V(e.projectRoot,e.storyId),o=await u(t.projectRoot,["rev-parse","HEAD"]),r=P(await _(t.projectRoot,["diff","--cached","--name-only","-z"])),i=Z(r,t.authorizedWriteSet,e.storyId,t.rootMemoryEffect);if(!i.ok)return s(i.reasonCode);t.rootMemoryEffect&&ue(t.projectRoot,t.rootMemoryEffect,{storyId:e.storyId,executionBranch:t.executionBranch,baseSha:o,headRef:":",childPaths:t.authorizedWriteSet});const n=oe(t.projectRoot,e.storyId,":");if(n?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");if(P(await _(t.projectRoot,["diff","--name-only","-z"])).some(x=>r.includes(x)))return s("direct-yolo-user-overlap");const c=await _(t.projectRoot,["diff","--cached","--binary","--full-index"]);if(!c)return s("direct-yolo-staged-diff-empty");const f=A(c),a=A([...t.authorizedWriteSet].sort().join("\0")),l=await Ze(t.projectRoot,e.storyId),g=l.state==="valid"&&l.plan.epicId===t.epicId&&l.plan.executionBranch===t.executionBranch&&l.plan.preparedBase===o&&l.plan.bundleDigest===f&&l.plan.claimRevision===a?l.plan:void 0,w=g?.graphRevision??t.graphRevision,h=xe({storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:f,graphRevision:w,claimRevision:a}),v=N(e.nowIso),R={schemaVersion:1,kind:"direct-yolo-commit-plan",storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:w,preparedBase:o,bundleDigest:f,claimRevision:a,idempotencyKey:h,issuedAt:g?.issuedAt??v};let b=e.setupLeaseHandoff??await Ct(t.projectRoot,e.storyId,f,a,v);const k=await C(t.projectRoot,{required:!0}),D=p(k.epics[t.epicId]?.branch_lease),j=D?.ownerStoryId===e.storyId&&D.sessionId===h&&D.idempotencyKey===h&&typeof D.expiresAt=="string"&&Date.parse(D.expiresAt)>Date.parse(v)?D:void 0;if(j&&e.setupLeaseHandoff)return s("direct-yolo-setup-handoff-replayed");const m=p(j?.handoffConsumption);if(m){const x=await J(t.projectRoot,e.storyId);if(!x||!["consuming","consumed"].includes(x.state)||x.fromSessionId!==m.fromSessionId||x.tokenDigest!==m.tokenDigest||x.bundleDigest!==f||x.claimRevision!==a||m.bundleDigest!==f||m.claimRevision!==a||x.consumedBySessionId!==h||m.consumedBySessionId!==h)return s("direct-yolo-setup-handoff-consume-invalid");if(x.state==="consuming"){if(!x.token||A(x.token)!==x.tokenDigest)return s("direct-yolo-setup-handoff-consume-invalid");b={sessionId:x.fromSessionId,token:x.token}}}const S=j?String(j.expiresAt):new Date(Date.parse(v)+ae).toISOString(),I=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:h,idempotencyKey:h,expiresAt:S,persistent:!0,createdAt:j&&typeof j.acquiredAt=="string"?j.acquiredAt:v});if(!I.ok)return s(I.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");try{b&&e.setupLeaseHandoff===void 0&&(await Ht(t.projectRoot,e.storyId,b.sessionId,b.token,h,v),await e.setupHandoffFault?.("after-consuming-persisted")),await L(t.projectRoot,x=>{const $=M(x,t.epicId),E=p($.branch_lease),H=E&&Date.parse(String(E.expiresAt))>Date.parse(v),T=E?.ownerStoryId===e.storyId&&E.sessionId===h&&E.idempotencyKey===h,ot=E?.ownerStoryId===e.storyId&&E.sessionId===E.idempotencyKey&&typeof E.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(E.idempotencyKey),fe=H&&ot&&Lt({current:E,handoff:b,storyId:e.storyId,bundleDigest:f,claimRevision:a,nowIso:v});if(b&&H&&!T&&!fe)throw new Error("direct-yolo-setup-handoff-invalid");if(H&&!T&&!fe)throw new Error("direct-yolo-writer-active");const Oe=fe?p(E?.handoffGrant):void 0,Le=Oe?{schemaVersion:1,kind:"direct-yolo-setup-handoff-consumption",state:"consumed",storyId:e.storyId,fromSessionId:String(E?.sessionId),tokenDigest:String(Oe.tokenDigest),bundleDigest:f,claimRevision:a,consumedBySessionId:h,consumedAt:v}:void 0;$.branch_mode="epic",$.execution_branch=t.executionBranch,$.origin_branch=t.originBranch,$.graph_revision=t.graphRevision,$.branch_lease=H&&T?E:{schemaVersion:1,ownerStoryId:e.storyId,sessionId:h,idempotencyKey:h,acquiredAt:v,expiresAt:S,...Le?{handoffConsumption:Le}:{}}},{expectedRevision:k.revision,preCommit:async()=>{if(!await ne(I.path,I.owner))throw new Error("direct-yolo-integration-lock-raced");await _t(t.projectRoot,R)}})}catch(x){throw await Y(I.path,I.owner).catch(()=>{}),x}b&&e.setupLeaseHandoff===void 0&&(await e.setupHandoffFault?.("before-consumed-persist"),await Ot(t.projectRoot,t.epicId,e.storyId,b.sessionId,b.token,f,a,h,v));const y=Object.freeze([`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${t.epicId}`,`Neocortex-Execution-Branch: ${t.executionBranch}`,`Neocortex-Prepared-Base: ${o}`,`Neocortex-Bundle-Digest: ${f}`,`Neocortex-Review-Artifact-Digest: ${n.digest}`,`Neocortex-Graph-Revision: ${w}`,`Neocortex-Claim-Revision: ${a}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${dt(t.rootMemoryEffect)}`]:[]]);return{ok:!0,value:Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:o,bundleDigest:f,reviewArtifactDigest:n.digest,graphRevision:w,claimRevision:a,idempotencyKey:h,changedPaths:Object.freeze(r),trailers:y})}}catch(t){return s(X(t,"direct-yolo-begin-failed"))}}async function pr(e){let t,o,r;try{const i=await V(e.projectRoot,e.storyId);t=i;const n=await u(i.projectRoot,["rev-parse","HEAD"]);let d=await C(i.projectRoot,{required:!0});const c=p(d.stories[e.storyId]?.checkpoint);if(c){const S=typeof c.headSha=="string"?c.headSha:"",I=typeof c.graphRevision=="string"?c.graphRevision:"",y=/^[a-f0-9]{40,64}$/.test(S)?P(await _(i.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",S])):[],x=Z(y,i.authorizedWriteSet,e.storyId,i.rootMemoryEffect);if(!(/^[a-f0-9]{40,64}$/.test(S)&&await B(i.projectRoot,["merge-base","--is-ancestor",S,n]))||!/^[a-f0-9]{64}$/.test(I)||!x.ok)return s("direct-yolo-replay-invalid");const E=await Ae(e,i.projectRoot,n,I);if(!await me(i.projectRoot,c,e.storyId,i.epicId,i.executionBranch,E.transientAuthority,i.authorizedWriteSet))return s("direct-yolo-replay-invalid");if(!await Be(i.projectRoot,i.executionBranch,n,y))return s("direct-yolo-replay-head-raced");if(e.push&&!await Je(i.projectRoot,e.remote??"origin",i.executionBranch,S))return s("direct-yolo-remote-head-mismatch");const H=Array.isArray(c.receiptRefs)?c.receiptRefs.find(T=>typeof T=="string"&&/^physical-lock-owner:[a-f0-9]{64}$/.test(T)):void 0;return H&&typeof c.idempotencyKey=="string"&&await St(i.projectRoot,{storyId:e.storyId,idempotencyKey:c.idempotencyKey,ownerDigest:H.slice(20)}),await ce(i.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:c}}const f=n,a=await Ve(i,e.storyId,f);if(!a.ok)return s(a.reasonCode);const{baseSha:l,changedPaths:g,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R}=a.value,b=p(d.epics[i.epicId]?.branch_lease),k=N(e.nowIso),D=b?.ownerStoryId===e.storyId&&b.idempotencyKey===R&&b.sessionId===R&&Date.parse(String(b.expiresAt))>Date.now()?b:void 0;if(b&&Date.parse(String(b.expiresAt))>Date.now()&&!D)return s("direct-yolo-writer-active");const j=D??{schemaVersion:1,ownerStoryId:e.storyId,sessionId:R,idempotencyKey:R,acquiredAt:k,expiresAt:new Date(Date.parse(k)+ae).toISOString()},m=await F(i.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:R,idempotencyKey:R,expiresAt:String(j.expiresAt),persistent:!0,createdAt:String(j.acquiredAt)});if(!m.ok)return s(m.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-integration-backpressure":"direct-yolo-integration-lock-failed");r=m,D||(d=(await L(i.projectRoot,I=>{const y=M(I,i.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(k))throw new Error("direct-yolo-writer-active");if(y.graph_revision!==i.graphRevision)throw new Error("direct-yolo-graph-revision-raced");y.branch_lease=j},{expectedRevision:d.revision})).document),o=j;{const S=await Ae(e,i.projectRoot,f,h);if(!await Be(i.projectRoot,i.executionBranch,f,g))return s("direct-yolo-head-raced");if(e.push){const x=te(e.remote??"origin");if(await u(i.projectRoot,["push",x,i.executionBranch]),!await _e(i.projectRoot,x,i.executionBranch,f))return s("direct-yolo-remote-head-mismatch")}const I=await Ie({projectRoot:i.projectRoot,storyId:e.storyId,epicId:i.epicId,executionBranch:i.executionBranch,baseSha:l,headSha:f,bundleDigest:w,graphRevision:h,claimRevision:v,idempotencyKey:R,qaExecution:S,physicalLockOwnerDigest:pe(m.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:i.rootMemoryEffect});return await e.beforeCheckpointPersist?.(),await Se({projectRoot:i.projectRoot,checkpoint:I,remote:e.push?e.remote??"origin":void 0,expectedRevision:d.revision,expectedLease:j,expectedGraphRevision:i.graphRevision,expectedCheckpointGraphRevision:h,physicalLockPath:m.path,physicalLockOwner:m.owner,transientAuthority:S.transientAuthority,authorizedWriteSet:i.authorizedWriteSet})?(await ce(i.projectRoot,e.storyId).catch(()=>{}),await e.afterCheckpointPersist?.(),{ok:!0,value:I}):s("direct-yolo-checkpoint-persist-failed")}}catch(i){return s(X(i,"direct-yolo-finalize-failed"))}finally{r&&await Y(r.path,r.owner).catch(()=>{}),t&&o?await Ee(t.projectRoot,t.epicId,o).catch(()=>{}):t&&await qt(t,e.storyId).catch(()=>{})}}async function Ve(e,t,o){const r=await u(e.projectRoot,["rev-parse",`${o}^`]),i=await _(e.projectRoot,["show","--no-patch","--format=%B",o]),n=P(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o])),d=Z(n,e.authorizedWriteSet,t,e.rootMemoryEffect);if(!d.ok)return s(d.reasonCode);e.rootMemoryEffect&&ue(e.projectRoot,e.rootMemoryEffect,{storyId:t,executionBranch:e.executionBranch,baseSha:r,headRef:o,childPaths:e.authorizedWriteSet});const c=A([...e.authorizedWriteSet].sort().join("\0")),f=await Ze(e.projectRoot,t);if(f.state==="invalid")return s("direct-yolo-commit-plan-invalid");const a=f.state==="valid"?f.plan:void 0;if(a&&(a.epicId!==e.epicId||a.executionBranch!==e.executionBranch))return s("direct-yolo-commit-plan-invalid");if(a&&a.claimRevision!==c)return s("direct-yolo-commit-plan-claim-changed");if(a&&a.preparedBase!==r)return s("direct-yolo-commit-plan-base-mismatch");const l=bt(i);if(!l.ok)return s(`direct-yolo-trailer-duplicate:${l.key}`);const g=l.values,w=a?.graphRevision??e.graphRevision,h=c,v=[["Neocortex-Story",t],["Neocortex-Epic",e.epicId],["Neocortex-Execution-Branch",e.executionBranch],["Neocortex-Prepared-Base",r],["Neocortex-Bundle-Digest",a?.bundleDigest??""],["Neocortex-Graph-Revision",w],["Neocortex-Claim-Revision",h]];for(const[m,S]of v){const I=ve(g,m);if(I===void 0)return s(`direct-yolo-trailer-missing:${we(m)}`);if(m==="Neocortex-Bundle-Digest"&&!a){if(!/^[a-f0-9]{64}$/.test(I))return s(`direct-yolo-trailer-mismatch:${we(m)}`);continue}if(I!==S)return s(`direct-yolo-trailer-mismatch:${we(m)}`)}const R=ve(g,"Neocortex-Bundle-Digest"),b=oe(e.projectRoot,t,o);if(b?.verdict!=="approved")return s("direct-yolo-review-artifact-not-approved");const k=ve(g,"Neocortex-Review-Artifact-Digest");if(k!==void 0&&k!==b.digest)return s("direct-yolo-review-artifact-digest-mismatch");const D=A(await _(e.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]));if(R!==D)return s("direct-yolo-bundle-digest-mismatch");const j=xe({storyId:t,epicId:e.epicId,executionBranch:e.executionBranch,baseSha:r,bundleDigest:R,graphRevision:w,claimRevision:h});return a&&a.idempotencyKey!==j?s("direct-yolo-commit-plan-invalid"):{ok:!0,value:{baseSha:r,changedPaths:n,bundleDigest:R,graphRevision:w,claimRevision:h,idempotencyKey:j}}}async function yr(e){try{const t=await V(e.projectRoot,e.storyId);if(!/^[a-f0-9]{40,64}$/.test(e.commitSha))return s("direct-yolo-recovery-commit-invalid");const o=await u(t.projectRoot,["rev-parse",e.commitSha]);if(vt[e.storyId]!==o)return s("direct-yolo-recovery-not-allowlisted");if(await u(t.projectRoot,["rev-parse","HEAD"])!==o)return s("direct-yolo-recovery-head-mismatch");await u(t.projectRoot,["merge-base","--is-ancestor",o,`refs/heads/${t.executionBranch}`]);const r=await u(t.projectRoot,["rev-parse",`${o}^`]),i=await _(t.projectRoot,["diff","--binary","--full-index",`${r}..${o}`]),n=P(await _(t.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!Z(n,t.authorizedWriteSet.length>0?t.authorizedWriteSet:n,e.storyId).ok)return s("direct-yolo-recovery-write-set-invalid");const c=A(i),f=A([...n].sort().join("\0")),a=A(["legacy-direct-yolo-recovery-v1",e.storyId,o].join("\0")),l=N(e.nowIso),g=new Date(Date.parse(l)+ae).toISOString(),w=await C(t.projectRoot,{required:!0}),h=await F(t.projectRoot,{kind:"direct",storyId:e.storyId,sessionId:a,idempotencyKey:a,expiresAt:g,persistent:!0,createdAt:l});if(!h.ok)return s(h.reasonCode==="git-lifecycle-integration-backpressure"?"direct-yolo-recovery-integration-backpressure":"direct-yolo-recovery-integration-lock-failed");const v={schemaVersion:1,ownerStoryId:e.storyId,sessionId:a,idempotencyKey:a,acquiredAt:l,expiresAt:g};let R=!1;try{const b=await L(t.projectRoot,I=>{const y=M(I,t.epicId),x=p(y.branch_lease);if(x&&Date.parse(String(x.expiresAt))>Date.parse(l)&&!je(x,v))throw new Error("direct-yolo-recovery-writer-active");if(y.graph_revision!==t.graphRevision)throw new Error("direct-yolo-recovery-graph-raced");y.branch_mode="epic",y.execution_branch=t.executionBranch,y.origin_branch=t.originBranch,y.branch_lease=v},{expectedRevision:w.revision});R=!0;const k=await Ae(e,t.projectRoot,o,t.graphRevision);if(!await Be(t.projectRoot,t.executionBranch,o,n))return s("direct-yolo-recovery-head-raced");if(e.push){const I=te(e.remote??"origin"),y=(await u(t.projectRoot,["ls-remote","--heads",I,`refs/heads/${t.executionBranch}`])).split(/\s+/)[0];if(!y||!await B(t.projectRoot,["merge-base","--is-ancestor",o,y]))return s("direct-yolo-recovery-remote-proof-missing")}const D=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision,claimRevision:f,idempotencyKey:a,qaExecution:k,physicalLockOwnerDigest:pe(h.owner),nowIso:l,legacyReceiptRef:void 0}),j=await gt(t.projectRoot,{storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:r,headSha:o,bundleDigest:c,graphRevision:t.graphRevision});if(!j)return s("direct-yolo-recovery-evidence-invalid");const m=Object.freeze({...D,receiptRefs:Object.freeze([...D.receiptRefs,j])});return await Se({projectRoot:t.projectRoot,checkpoint:m,remote:e.push?e.remote??"origin":void 0,remotePolicy:"ancestor-recovery",expectedRevision:b.document.revision,expectedLease:v,expectedGraphRevision:t.graphRevision,physicalLockPath:h.path,physicalLockOwner:h.owner,transientAuthority:k.transientAuthority,authorizedWriteSet:t.authorizedWriteSet})?{ok:!0,value:m}:s("direct-yolo-recovery-persist-failed")}finally{await Y(h.path,h.owner).catch(()=>{}),R&&await Ee(t.projectRoot,t.epicId,v).catch(()=>{})}}catch(t){return s(X(t,"direct-yolo-recovery-failed"))}}async function Ke(e){const t=await he(await u(e,["rev-parse","--absolute-git-dir"])),o=await he(await u(e,["rev-parse","--path-format=absolute","--git-common-dir"]));return t!==o}async function Fe(e){const t=await C(e.projectRoot,{required:!0}),o=Object.values(t.storyWorktrees?.entries??{}).filter(g=>g.storyId===e.storyId&&g.epicId===e.epicId&&g.state==="active");if(o.length===0)throw new Error("direct-yolo-worktree-lease-missing");if(o.length>1)throw new Error("direct-yolo-worktree-lease-ambiguous");const r=o[0];if(r.executionBranch!==e.executionBranch)throw new Error("direct-yolo-worktree-branch-mismatch");if(await he(await u(e.projectRoot,["rev-parse","--show-toplevel"]))!==r.worktreePath)throw new Error("direct-yolo-worktree-path-mismatch");if(await u(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]).catch(()=>"")!==r.temporaryBranch)throw new Error("direct-yolo-worktree-branch-mismatch");const d=await new kt({projectRoot:e.projectRoot}).probe(r.leaseId);if(!d.ok||d.value.ownership!=="proven")throw new Error("direct-yolo-worktree-ownership-unproven");const c=K(p(t.epics[e.epicId])?.origin_binding,e.executionBranch,e.originBranch);if(!c)throw new Error("direct-yolo-origin-binding-invalid");const f=r.syncedSha??r.baseSha,a=await u(e.projectRoot,["rev-parse","HEAD"]),l=`refs/heads/${e.executionBranch}`;if(a!==f||!await B(e.projectRoot,["merge-base","--is-ancestor",f,l])||!await B(e.projectRoot,["merge-base","--is-ancestor",c.originHeadSha,f]))throw new Error("direct-yolo-worktree-base-divergent");if(d.value.clean!==!0||(await _(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:f,headSha:a,expiresAt:r.expiresAt,binding:c}}function Ye(e,t,o){return Object.freeze({...de(e,t.binding,t.expiresAt,o),workspace:"story-worktree",temporaryBranch:t.temporaryBranch,baseSha:t.authorizedBase})}async function jt(e){const t=await Fe(e),o=G(e.projectRoot,".neocortex/state.json"),r=await q(o,"utf8"),i=p(JSON.parse(r)),n=p(p(i?.stories)?.[e.storyId]),d=await C(e.projectRoot,{required:!0}),c=p(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 s("direct-yolo-setup-story-progress-conflict");const f=c?.status==="branch-ready"&&c.last_step===W&&Array.isArray(c.steps_completed)&&c.steps_completed.length===1&&c.steps_completed[0]===W&&U(c).sort().join(",")==="last_step,status,steps_completed";return c&&U(c).length>0&&!f?s("direct-yolo-setup-story-progress-conflict"):(f||await L(e.projectRoot,a=>{const l=ye(a,e.storyId);if(U(l).length>0)throw new Error("direct-yolo-setup-runtime-raced");l.status="branch-ready",l.last_step=W,l.steps_completed=[W]},{expectedRevision:d.revision,preCommit:async()=>{if(await q(o,"utf8")!==r||await u(e.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.temporaryBranch||await u(e.projectRoot,["rev-parse","HEAD"])!==t.headSha||(await _(e.projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])).length>0)throw new Error("direct-yolo-setup-physical-state-raced")}}),{ok:!0,value:Object.freeze({...Ye(e,t,f),checkpointAccepted:!0,graphRevision:e.graphRevision,headSha:t.headSha})})}async function gr(e,t){const o=await V(e,t),r=await C(o.projectRoot,{required:!0}),i=K(p(r.epics[o.epicId])?.origin_binding,o.executionBranch,o.originBranch);return{...o,originBinding:i}}function mr(e,t,o,r){return Z(e,t,o,r)}function wr(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const vr=ae,Et="p205-wave:";function Rr(e){if(e.waveStoryIds.length===0||e.waveStoryIds.length!==e.waveCommitShas.length||e.waveCommitShas[e.waveCommitShas.length-1]!==e.waveHeadSha||e.waveCommitShas.some(o=>!/^[a-f0-9]{40,64}$/.test(o)))throw new Error("direct-yolo-wave-coverage-invalid");const t=A(["p205-wave-coverage-v1",e.epicId,e.executionBranch,e.waveHeadSha,...e.waveStoryIds.map((o,r)=>`${o}=${e.waveCommitShas[r]}`)].join("\0"));return Object.freeze({kind:"wave",waveHeadSha:e.waveHeadSha,waveStoryIds:Object.freeze([...e.waveStoryIds]),waveCommitShas:Object.freeze([...e.waveCommitShas]),waveDigest:t})}function At(e){return`${Et}${e.waveHeadSha}:${e.waveDigest}`}async function Ir(e){let t;try{t=await mt(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:ge(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:ge(r)||/^p205-[a-z0-9-]{1,64}$/.test(r)?r:"p205-complete-gate-failed"}}return{ok:!0,headSha:e.headSha,authorities:t}}async function Sr(e,t,o,r){const i=te(t);return await u(e,["push",i,o]),_e(e,i,o,r)}async function xr(e){try{const t=await V(e.projectRoot,e.storyId),o=e.coverage.waveHeadSha,r=e.coverage.waveStoryIds.indexOf(e.storyId);if(r<0||e.coverage.waveCommitShas[r]!==e.headSha)return s("direct-yolo-wave-coverage-invalid");if(await u(t.projectRoot,["rev-parse","HEAD"])!==o||await u(t.projectRoot,["rev-parse",`refs/heads/${t.executionBranch}`])!==o||!await B(t.projectRoot,["merge-base","--is-ancestor",e.headSha,o]))return s("direct-yolo-wave-head-raced");const i=await C(t.projectRoot,{required:!0}),n=p(i.stories[e.storyId]?.checkpoint);if(n){if(n.headSha!==e.headSha)return s("direct-yolo-checkpoint-conflict");const k=e.authorities.get(String(n.graphRevision));return await me(t.projectRoot,n,e.storyId,t.epicId,t.executionBranch,k??null,t.authorizedWriteSet)?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:n}):s("direct-yolo-replay-invalid")}const d=await Ve(t,e.storyId,e.headSha);if(!d.ok)return s(d.reasonCode);const{baseSha:c,bundleDigest:f,graphRevision:a,claimRevision:l,idempotencyKey:g}=d.value,w=r===0?void 0:e.coverage.waveCommitShas[r-1];if(w!==void 0&&c!==w)return s("direct-yolo-wave-chain-invalid");const h=e.authorities.get(a),v=ze(h);if(!h||!v||v.executionHeadSha!==o||v.graphRevision!==a)return s("direct-yolo-wave-qa-unbound");const R=await Ie({projectRoot:t.projectRoot,storyId:e.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:c,headSha:e.headSha,bundleDigest:f,graphRevision:a,claimRevision:l,idempotencyKey:g,qaExecution:{contract:"P205-CI-02",command:Te,manifestDigest:v.manifestDigest,gateIds:v.gateIds,resultDigest:v.resultDigest,transientAuthority:h},physicalLockOwnerDigest:pe(e.physicalLock.owner),nowIso:N(e.nowIso),legacyReceiptRef:void 0,rootMemoryEffect:t.rootMemoryEffect,extraReceiptRefs:[At(e.coverage)]});return await Se({projectRoot:t.projectRoot,checkpoint:R,remote:e.remote,expectedRevision:i.revision,expectedLease:e.expectedLease,expectedGraphRevision:t.graphRevision,expectedCheckpointGraphRevision:a,physicalLockPath:e.physicalLock.path,physicalLockOwner:e.physicalLock.owner,transientAuthority:h,authorizedWriteSet:t.authorizedWriteSet,expectedHeadSha:o,keepLease:!0})?(await ce(t.projectRoot,e.storyId).catch(()=>{}),{ok:!0,value:R}):s("direct-yolo-checkpoint-persist-failed")}catch(t){return s(X(t,"direct-yolo-wave-persist-failed"))}}async function Re(e,t){if(!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(t))throw new Error("direct-yolo-story-id-invalid");const o=O(e),r=p(JSON.parse(await q(G(o,".neocortex/state.json"),"utf8"))),i=await C(o,{required:!0}),n=le(r,i),d=p(n.stories),c=p(n.epics),f=p(d?.[t]),a=String(f?.epic_id??t.split(".")[0]),l=p(c?.[a]),g=String(l?.execution_branch??""),w=String(l?.origin_branch??""),h=String(l?.graph_revision??""),v=Array.isArray(f?.files_to_modify)?f.files_to_modify:[],R=It(f).filter(Pt),b=[...v,...R],k=b.length>0?Pe(t,b):void 0,D=k?.ok?k.scopes:[];if(!f)throw new Error("direct-yolo-story-state-missing");if(R.length>0&&D.length>Rt)throw new Error("direct-yolo-write-set-too-large");if(l?.branch_mode!=="epic")throw new Error("direct-yolo-branch-mode-invalid");if(!Q(g)||!await B(o,["check-ref-format","--branch",g]))throw new Error("direct-yolo-execution-branch-invalid");if(!Q(w)||!await B(o,["check-ref-format","--branch",w]))throw new Error("direct-yolo-origin-branch-invalid");if(!/^[a-f0-9]{64}$/.test(h))throw new Error("direct-yolo-graph-revision-invalid");const j=await st({projectRoot:o,storyId:t,graphRevision:h,executionBranch:g,childPaths:D});return{projectRoot:o,storyId:t,story:f,epicId:a,executionBranch:g,originBranch:w,graphRevision:h,authorizedWriteSet:D,rootMemoryEffect:j}}async function V(e,t){const o=await Re(e,t);if(await u(o.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==o.executionBranch)throw new Error("direct-yolo-current-branch-mismatch");return o}async function Ie(e){const t=e.nowIso,o=await _(e.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),r=P(await _(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha])),i=pt({storyId:e.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,commitBody:o,changedPaths:r}),n=yt({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}),f=oe(e.projectRoot,e.storyId,e.headSha);if(f?.verdict!=="approved")throw new Error("direct-yolo-review-artifact-not-approved");const a=A(["root-commit-range-review-v2",e.storyId,e.baseSha,e.headSha,e.bundleDigest,e.graphRevision,d,A(o),[...r].sort().join(","),f.digest].join("\0")),l=`story-review:${a}`,g=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.storyId,epicId:e.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,sourceEvidenceDigest:a,reviewArtifactDigest:f.digest,qaReceiptRef:d,verdict:"approved",reviewedAt:t,receiptRef:l}),w=[`.neocortex/stories/${e.storyId}/qa-gate-result.json`,`.neocortex/stories/${e.storyId}/validation-evidence.md`,d,l,...e.physicalLockOwnerDigest?[`physical-lock-owner:${e.physicalLockOwnerDigest}`]:[],...e.legacyReceiptRef?[e.legacyReceiptRef]:[],...e.extraReceiptRefs??[]];return Object.freeze({schemaVersion:1,storyId:e.storyId,epicId:e.epicId,branch:e.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.idempotencyKey,bundleDigest:e.bundleDigest,graphRevision:e.graphRevision,claimRevision:e.claimRevision,receiptRefs:Object.freeze(w),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:c,reviewReceipt:g,recordedAt:t,...e.rootMemoryEffect?{rootMemoryEffect:e.rootMemoryEffect}:{}})}async function Se(e){const{projectRoot:t,checkpoint:o,remote:r}=e;let i=!1;return await L(t,n=>{const d=M(n,o.epicId);if(e.expectedLease){const l=p(d.branch_lease);if(!je(l,e.expectedLease))throw new Error("direct-yolo-runtime-revision-conflict");if(Date.parse(String(l?.expiresAt))<=Date.now())throw new Error("direct-yolo-writer-lease-expired");if(d.graph_revision!==e.expectedGraphRevision||o.graphRevision!==(e.expectedCheckpointGraphRevision??e.expectedGraphRevision))throw new Error("direct-yolo-graph-revision-raced")}const c=ye(n,o.storyId),f=p(c.checkpoint);if(f&&f.headSha!==o.headSha){i=!0;return}c.checkpoint=o,c.status="done",c.last_step=Ge;const a=Array.isArray(c.steps_completed)?c.steps_completed.filter(l=>typeof l=="string"):[];c.steps_completed=[...new Set([...a,Dt,Ge])],e.keepLease||(d.branch_lease=null)},{expectedRevision:e.expectedRevision,preCommit:async()=>{if(i)throw new Error("direct-yolo-checkpoint-conflict");const n=e.expectedHeadSha??o.headSha;if(await u(t,["symbolic-ref","--quiet","--short","HEAD"])!==o.branch||await u(t,["rev-parse","HEAD"])!==n||await u(t,["rev-parse",`refs/heads/${o.branch}`])!==n||!await B(t,["merge-base","--is-ancestor",o.headSha,n]))throw new Error("direct-yolo-checkpoint-head-raced");if(!await me(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 ne(e.physicalLockPath,e.physicalLockOwner))throw new Error("direct-yolo-integration-lock-raced");if(r&&!(e.remotePolicy==="ancestor-recovery"?await Je(t,r,o.branch,o.headSha):await _e(t,r,o.branch,n)))throw new Error("direct-yolo-checkpoint-remote-raced")}}),!i}async function Je(e,t,o,r){const i=te(t),n=(await u(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0];return!!(n&&await B(e,["merge-base","--is-ancestor",r,n]))}function xe(e){return A(["direct-yolo-commit-v1",e.storyId,e.epicId,e.executionBranch,e.baseSha,e.bundleDigest,e.graphRevision,e.claimRevision].join("\0"))}const Bt=["schemaVersion","kind","storyId","epicId","executionBranch","graphRevision","preparedBase","bundleDigest","claimRevision","idempotencyKey","issuedAt"];async function be(e,t){const o=await Me(e),r=await Ne(o,"commit-plans"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function _t(e,t){const o=await be(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
2
+ `),await ie(o.path,o.parent)}async function Ze(e,t){let o;try{o=await be(e,t)}catch{return{state:"invalid"}}try{if(!qe(o.path))return{state:"absent"};await ie(o.path,o.parent);const r=await q(o.path,"utf8");if(r.length>16*1024)return{state:"invalid"};const i=p(JSON.parse(r));if(!i||Object.keys(i).sort().join("\0")!==[...Bt].sort().join("\0")||i.schemaVersion!==1||i.kind!=="direct-yolo-commit-plan"||i.storyId!==t||typeof i.epicId!="string"||typeof i.executionBranch!="string"||!Q(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!==xe({...n,baseSha:n.preparedBase})?{state:"invalid"}:{state:"valid",plan:n}}catch{return{state:"invalid"}}}async function ce(e,t){const o=await be(e,t);qe(o.path)&&await xt(o.parent,o.name)}function ke(e,t,o){return!!(e?.ownerStoryId===t&&e.sessionId===e.idempotencyKey&&typeof e.idempotencyKey=="string"&&/^setup-[a-f0-9]{64}$/.test(e.idempotencyKey)&&typeof e.expiresAt=="string"&&Date.parse(e.expiresAt)>Date.parse(o))}async function Ue(e,t){const o=await Me(e),r=await Ne(o,"handoffs"),i=`direct-${A(t)}.json`;return{parent:r,name:i,path:G(r,i)}}async function De(e,t){const o=await Ue(e,t.storyId);await We(o.parent,o.name,`${JSON.stringify(t,null,2)}
3
+ `),await ie(o.path,o.parent)}async function J(e,t){try{const o=await Ue(e,t);await ie(o.path,o.parent);const r=JSON.parse(await q(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 Ct(e,t,o,r,i){const n=await J(e,t);if(!(!n||n.state==="consumed"||!n.token||n.bundleDigest!==o||n.claimRevision!==r||Date.parse(n.expiresAt)<=Date.parse(i)||A(n.token)!==n.tokenDigest))return{sessionId:n.fromSessionId,token:n.token}}async function Ht(e,t,o,r,i,n){const d=await J(e,t);if(!d||d.state==="consumed"||d.fromSessionId!==o||d.token!==r||d.tokenDigest!==A(r))throw new Error("direct-yolo-setup-handoff-consume-invalid");if(d.state==="consuming"){if(d.consumedBySessionId!==i)throw new Error("direct-yolo-setup-handoff-consume-raced");return}await De(e,{...d,state:"consuming",consumedBySessionId:i,consumeStartedAt:n})}async function Ot(e,t,o,r,i,n,d,c,f){const a=await J(e,o);if(a?.state==="consumed"&&a.fromSessionId===r&&a.consumedBySessionId===c)return;const l=await C(e,{required:!0}),g=p(l.epics[t]?.branch_lease),w=p(g?.handoffConsumption);if(!a||a.state!=="consuming"||a.fromSessionId!==r||a.token!==i||a.tokenDigest!==A(i)||a.bundleDigest!==n||a.claimRevision!==d||a.consumedBySessionId!==c||g?.ownerStoryId!==o||g.sessionId!==c||w?.kind!=="direct-yolo-setup-handoff-consumption"||w.state!=="consumed"||w.fromSessionId!==r||w.tokenDigest!==a.tokenDigest||w.bundleDigest!==n||w.claimRevision!==d||w.consumedBySessionId!==c)throw new Error("direct-yolo-setup-handoff-consume-invalid");try{await De(e,{schemaVersion:1,kind:a.kind,state:"consumed",storyId:o,fromSessionId:r,tokenDigest:a.tokenDigest,bundleDigest:a.bundleDigest,claimRevision:a.claimRevision,grantDigest:a.grantDigest,expiresAt:a.expiresAt,consumedBySessionId:c,consumedAt:f})}catch{throw new Error("direct-yolo-setup-handoff-consume-persist-failed")}}function Lt(e){const t=p(e.current?.handoffGrant),o=e.handoff?.token,r=typeof o=="string"&&/^[A-Za-z0-9_-]{32,256}$/.test(o)?A(o):void 0;return!!(t&&r&&e.handoff&&e.handoff.sessionId===e.current?.sessionId&&t.schemaVersion===1&&t.kind==="direct-yolo-setup-handoff"&&t.storyId===e.storyId&&t.fromSessionId===e.current?.sessionId&&t.bundleDigest===e.bundleDigest&&t.claimRevision===e.claimRevision&&typeof t.expiresAt=="string"&&Date.parse(t.expiresAt)>Date.parse(e.nowIso)&&typeof t.tokenDigest=="string"&&/^[a-f0-9]{64}$/.test(t.tokenDigest)&&$t(t.tokenDigest,r))}function $t(e,t){const o=Buffer.from(e,"hex"),r=Buffer.from(t,"hex");return o.length===32&&r.length===32&&at(o,r)}function je(e,t){return!!(e&&["schemaVersion","ownerStoryId","sessionId","idempotencyKey","acquiredAt","expiresAt"].every(o=>e[o]===t[o]))}async function Ee(e,t,o){await L(e,r=>{const i=M(r,t),n=p(i.branch_lease);je(n,o)&&(i.branch_lease=null)})}async function qt(e,t){const o=await C(e.projectRoot,{required:!0}),r=p(o.epics[e.epicId]?.branch_lease);if(!r||r.ownerStoryId!==t||!Qe(r.sessionId)||!Qe(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 Ee(e.projectRoot,e.epicId,r)}async function Ae(e,t,o,r){const i=await wt(t,{headSha:o,graphRevision:r,nowIso:e.nowIso});await e.qaRunner?.({projectRoot:t,storyId:e.storyId,headSha:o});const n=ze(i);if(!n)throw new Error("p205-transient-authority-invalid");return{contract:"P205-CI-02",command:Te,manifestDigest:n.manifestDigest,gateIds:n.gateIds,resultDigest:n.resultDigest,transientAuthority:i}}async function Be(e,t,o,r){return await u(e,["rev-parse","HEAD"])!==o||await u(e,["symbolic-ref","--quiet","--short","HEAD"])!==t||!await B(e,["diff","--cached","--quiet"])?!1:B(e,["diff","--quiet","HEAD","--",...r])}async function _e(e,t,o,r){const i=te(t);return(await u(e,["ls-remote","--heads",i,`refs/heads/${o}`])).split(/\s+/)[0]===r}function Z(e,t,o,r){if(e.length===0||e.some(d=>!Ce(d)))return{ok:!1,reasonCode:"direct-yolo-write-set-invalid"};const i=t.length>0?Pe(o,t):void 0;return i?.ok?[".neocortex/state.json",`docs/stories/${o}.story.md`,`.neocortex/stories/${o}/qa-gate-result.json`,`.neocortex/stories/${o}/validation-evidence.md`,`.neocortex/stories/${o}/review.md`].every(d=>e.includes(d))?r&&(r.storyId!==o||r.childClaimRevision!==A([...i.scopes].sort().join("\0")))?{ok:!1,reasonCode:"direct-yolo-root-memory-claim-mismatch"}:e.some(d=>!ut(i.scopes,d)&&!r?.files.some(c=>c.path===d))?{ok:!1,reasonCode:"direct-yolo-write-set-unauthorized"}:{ok:!0}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}:{ok:!1,reasonCode:"direct-yolo-write-set-invalid"}}function U(e){return Object.keys(e).filter(t=>t!=="write_set_extension")}function Pt(e){return typeof e!="string"||e.length>512||!Ce(e)||!lt(e).ok||/^(?:\.neocortex|\.claude|\.git[^/]*)(?:\/|$)/i.test(e)||/^docs\/stories(?:\/|$)/i.test(e)?!1:!e.split("/")[0].includes("*")}function Ce(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!e.includes("\\")&&!e.split("/").includes("..")&&!e.startsWith(".git/")&&!e.includes("\0")}function Qe(e){return typeof e=="string"&&e.length>0&&e.length<=512&&/^[A-Za-z0-9._:@/+\-=]+$/.test(e)}function Q(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!/[\s~^:?*[\\]/.test(e)&&!e.includes("..")}function te(e){if(!/^[A-Za-z0-9._-]{1,128}$/.test(e))throw new Error("direct-yolo-remote-invalid");return e}function A(e){return nt("sha256").update(e).digest("hex")}function P(e){return e.split("\0").filter(Boolean)}function N(e){return e&&Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function p(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Nt(e,t,o,r,i){const n=p(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 zt(e,t){let o=await u(e,["symbolic-ref","--quiet","--short","HEAD"]);if(o===t.executionBranch){if(await u(e,["rev-parse","HEAD"])!==t.originHead||await z(e)!==t.checkoutBefore)return;await u(e,["switch",t.originBranch]),o=t.originBranch}if(o!==t.originBranch||await u(e,["rev-parse","HEAD"])!==t.originHead||await z(e)!==t.checkoutBefore||t.executionHead===t.originHead||!await B(e,["show-ref","--verify","--quiet",t.executionRef]))return;await u(e,["rev-parse",t.executionRef])===t.originHead&&await u(e,["update-ref",t.executionRef,t.executionHead,t.originHead])}const Tt=["capturedAt","capturedFromCurrentCheckout","executionBranch","originBranch","originHeadSha","schemaVersion"],Mt=["capturedAt","capturedFrom","executionBranch","originBranch","originHeadSha","schemaVersion"];function K(e,t,o){const r=p(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!==Tt.join("\0")?void 0:r;if(r.schemaVersion===2)return r.capturedFrom!=="current-checkout"&&r.capturedFrom!=="branch-ref"||i!==Mt.join("\0")?void 0:r}async function Wt(e,t,o){const r=`refs/heads/${e.originBranch}`;if(!await B(e.projectRoot,["show-ref","--verify","--quiet",r]))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");const i=await u(e.projectRoot,["rev-parse","--verify","--quiet",`${r}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(i))return s("direct-yolo-origin-ref-missing","fetch-origin-branch");if((await re(e.projectRoot)).some(f=>f.branch===e.executionBranch&&O(f.path)!==e.projectRoot))return s("direct-yolo-execution-branch-checked-out-elsewhere");const d=`refs/heads/${e.executionBranch}`;if(await u(e.projectRoot,["rev-parse","--verify","--quiet",d]).catch(()=>"")!==t)return s("direct-yolo-setup-physical-state-raced");const c=await He(e.projectRoot,["merge-base","--is-ancestor",i,t]);return c===1?s("direct-yolo-origin-not-ancestor","checkout-origin-or-rebase"):c!==0?s("direct-yolo-origin-ancestry-unverifiable"):{ok:!0,value:{originRef:r,binding:{schemaVersion:2,originBranch:e.originBranch,originHeadSha:i,executionBranch:e.executionBranch,capturedFrom:"branch-ref",capturedAt:o}}}}const Xe=3e4,Gt=3,Vt="ssh -o BatchMode=yes -o ConnectTimeout=15 -o ServerAliveInterval=15 -o ServerAliveCountMax=2";class se extends Error{}function Kt(e,t=Xe){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:Vt}}}}async function Ft(e){if(!Q(e.originBranch))return{ok:!1,reasonCode:"origin-binding-start-fetch-unavailable"};try{return await ee("git",["fetch","--no-tags","origin",`refs/heads/${e.originBranch}:refs/remotes/origin/${e.originBranch}`],{cwd:O(e.projectRoot),maxBuffer:1024*1024,encoding:"utf8",...Kt(process.env,e.fetchTimeoutMs??Xe)}),{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 Yt=new Set(["done","completed","complete","closed","cancelled","canceled","archived","terminal"]);async function br(e,t){const o=Object.freeze({exists:!1,mode:"not-epic",terminal:!1,bound:!1});try{const r=O(e),i=p(JSON.parse(await q(G(r,".neocortex/state.json"),"utf8")));if(!i)return o;const n=await C(r),d=le(i,n),c=p(p(d.epics)?.[t]);if(!c)return o;const f=tt(d,t,c),a=typeof c.execution_branch=="string"&&c.execution_branch.length>0?c.execution_branch:`epic/${t}`,l=await et(r,c,i),g=p(n.epics[t])?.origin_binding??c.origin_binding;return Object.freeze({exists:!0,mode:f,terminal:Yt.has(String(c.status??"").toLowerCase()),bound:!!K(g,a,l),executionBranch:a,originBranch:l})}catch{return o}}async function et(e,t,o){if(typeof t.origin_branch=="string"&&t.origin_branch.length>0)return t.origin_branch;const r=p(o.config)?.default_branch;if(r!=null&&String(r).length>0)return String(r);const i=await u(e,["symbolic-ref","--quiet","--short","refs/remotes/origin/HEAD"]).catch(()=>"");if(i.startsWith("origin/")&&i.length>7)return i.slice(7);const n=[];for(const d of["main","master"])await B(e,["rev-parse","--verify","--quiet",`refs/heads/${d}^{commit}`])&&await B(e,["rev-parse","--verify","--quiet",`refs/remotes/origin/${d}^{commit}`])&&n.push(d);return n.length===1?n[0]:""}function tt(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=p(e.stories)??{},n=ht(t,Array.isArray(o.stories)?o.stories:void 0,Object.keys(r)).flatMap(c=>{const f=p(r[c]);return f?[{...f,id:c}]:[]}),d=ft({...o,id:t},n);return d.mode==="epic"&&(d.source==="new-epic-default"||d.source==="epic-boundary")?"resolved-epic":"not-epic"}function rt(e,t){if(!e)return!1;const o=Date.parse(String(e.expiresAt));return!(Number.isFinite(o)&&o<=t)}async function kr(e){const t=N(e.nowIso),o=Date.parse(t),r=(c,f={})=>Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...f,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=O(e.projectRoot);let n=e.originFetch,d="origin-binding-start-raced";for(let c=0;c<Gt;c+=1){let f,a={};try{const l=p(JSON.parse(await q(G(i,".neocortex/state.json"),"utf8")));if(!l)return r("origin-binding-start-state-invalid");const g=await C(i),w=le(l,g),h=p(p(w.epics)?.[e.epicId]);if(!h)return r("origin-binding-start-target-ambiguous");if(tt(w,e.epicId,h)==="not-epic")return r("origin-binding-start-branch-mode-not-epic");const v=typeof h.execution_branch=="string"&&h.execution_branch.length>0?h.execution_branch:`epic/${e.epicId}`,R=await et(i,h,l);if(a={executionBranch:v,originBranch:R},!Q(v)||!Q(R)||v===R||!await B(i,["check-ref-format","--branch",v])||!await B(i,["check-ref-format","--branch",R]))return r("origin-binding-start-branch-invalid",a);const b=p(g.epics[e.epicId]),k=b?.origin_binding??h.origin_binding;if(k!=null){const E=K(k,v,R);return E?Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:E.originHeadSha,outcome:"already-bound",executionRefCreated:!1,capturedAt:t}):r("origin-binding-start-binding-invalid",a)}if(rt(p(b?.branch_lease??h.branch_lease),o))return r("origin-binding-start-lease-inconsistent",a);if(n??=await Ft({projectRoot:i,originBranch:R,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}),!n.ok)return r(n.reasonCode,a);const D=`refs/remotes/origin/${R}`,j=`refs/heads/${R}`,m=await u(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),S=await u(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>"");if(!/^[a-f0-9]{40,64}$/.test(m)||m!==S)return r("origin-binding-start-origin-stale",a);if((await re(i)).some(E=>E.branch===v&&O(E.path)!==i))return r("direct-yolo-execution-branch-checked-out-elsewhere",a);const y=`refs/heads/${v}`,x=await u(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(x){const E=await He(i,["merge-base","--is-ancestor",m,x]);if(E===1)return r("direct-yolo-origin-not-ancestor",a);if(E!==0)return r("direct-yolo-origin-ancestry-unverifiable",a)}const $={schemaVersion:2,originBranch:R,originHeadSha:m,executionBranch:v,capturedFrom:"branch-ref",capturedAt:t};return await L(i,E=>{const H=M(E,e.epicId);if(H.origin_binding!==void 0&&H.origin_binding!==null)throw new se("origin-binding-start-raced");if(rt(p(H.branch_lease),o))throw new se("origin-binding-start-lease-inconsistent");H.origin_binding=$},{expectedRevision:g.revision,preCommit:async()=>{const E=await u(i,["rev-parse","--verify","--quiet",`${j}^{commit}`]).catch(()=>""),H=await u(i,["rev-parse","--verify","--quiet",`${D}^{commit}`]).catch(()=>""),T=await u(i,["rev-parse","--verify","--quiet",`${y}^{commit}`]).catch(()=>"");if(E!==m||H!==m||T!==x)throw new se("origin-binding-start-raced");x||(await u(i,["update-ref",y,m,""]),f={ref:y,sha:m})}}),Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e.epicId,...a,originHeadSha:m,outcome:"captured",executionRefCreated:f!==void 0,capturedAt:t})}catch(l){if(f&&await u(i,["update-ref","-d",f.ref,f.sha]).catch(()=>{}),l instanceof Error&&l.message==="git-lifecycle-runtime-revision-conflict"){d="origin-binding-start-raced";continue}return l instanceof se?r(l.message,a):r("origin-binding-start-failed",a)}}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 z(e){const t=P(await _(e,["ls-files","--others","--exclude-standard","-z"])).sort(),o=await Promise.all(t.map(async r=>{if(!Ce(r))throw new Error("direct-yolo-checkout-payload-invalid");return`${r}\0${await u(e,["hash-object","--no-filters","--",r])}`}));return A([await _(e,["diff","--cached","--binary","--full-index"]),await _(e,["diff","--binary","--full-index"]),await _(e,["status","--porcelain=v1","-z","--untracked-files=all"]),...o].join("\0"))}async function Dr(e){const t=O(e),o=await u(t,["rev-parse","HEAD"]),r=await u(t,["symbolic-ref","--quiet","--short","HEAD"]),i=await z(t);if(await u(t,["rev-parse","HEAD"])!==o||await u(t,["symbolic-ref","--quiet","--short","HEAD"])!==r)throw new Error("direct-yolo-checkout-observation-raced");return Object.freeze({headSha:o,branch:r,payloadDigest:i})}async function re(e){const t=[];let o;for(const r of(await _(e,["worktree","list","--porcelain","-z"])).split("\0"))r.startsWith("worktree ")?(o={path:r.slice(9)},t.push(o)):o&&r.startsWith("branch refs/heads/")&&(o.branch=r.slice(18));return t}function X(e,t){return e instanceof Error&&e.message==="git-lifecycle-runtime-revision-conflict"?"direct-yolo-runtime-revision-conflict":e instanceof Error&&ge(e.message)||e instanceof Error&&/^direct-yolo-[a-z0-9-]+(?::[a-z0-9-]+)?$/.test(e.message)?e.message:t}function s(e,t){return t?{ok:!1,reasonCode:e,hint:t}:{ok:!1,reasonCode:e}}async function He(e,t){try{return await ee("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),0}catch(o){const r=o.code;return typeof r=="number"?r:-1}}async function u(e,t){return String((await ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout).trim()}async function _(e,t){return String((await ee("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024})).stdout)}async function B(e,t){try{return await ee("git",[...t],{cwd:e,maxBuffer:8*1024*1024}),!0}catch{return!1}}export{vr as DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS,Et as DIRECT_YOLO_WAVE_RECEIPT_REF_PREFIX,Xe as ORIGIN_BINDING_START_FETCH_TIMEOUT_MS,hr as acceptDirectYoloSetupCheckpoint,lr as beginDirectYoloStoryCommit,Dr as captureDirectYoloCheckoutEvidence,kr as captureEpicOriginBindingAtYoloopStart,wr as directYoloCommitIdempotencyKey,Rr as directYoloWaveQaCoverage,At as directYoloWaveReceiptRef,Ft as fetchOriginForYoloopStart,pr as finalizeDirectYoloStoryCheckpoint,Pt as isDirectYoloWriteSetExtensionScope,ur as issueDirectYoloSetupLeaseHandoff,xr as persistDirectYoloWaveStoryCheckpoint,fr as prepareDirectYoloSetup,Sr as pushDirectYoloWaveHead,br as readYoloopStartEpic,yr as recoverLegacyDirectYoloStoryCheckpoint,gr as resolveDirectYoloIntegrationAuthority,Ir as runDirectYoloWaveP205,mr as validateDirectYoloWriteSet,Kt as yoloopStartGitNetworkExecOptions};
@@ -42,6 +42,8 @@ export interface YoloopStartAdaptationOptions {
42
42
  /** Test seams forwarded to P227.20; production uses its `gh` provider and origin URL. */
43
43
  readonly prProvider?: LegacyBranchModeConversionPrProvider;
44
44
  readonly repository?: string;
45
+ /** 4.64.1: start-resolved origin branch, so a state without `config.default_branch` still converts. */
46
+ readonly originBranch?: string;
45
47
  }
46
48
  /**
47
49
  * P227.21 DEC-15 (closes DEC-14): run P227.20's legacy branch-mode conversion
@@ -1 +1 @@
1
- import{captureEpicOriginBindingAtYoloopStart as g,fetchOriginForYoloopStart as h,readYoloopStartEpic as f}from"../git/direct-yolo-checkpoint.js";import{applyLegacyBranchModeConversion as l,LegacyBranchModeConversionError as I,planLegacyBranchModeConversion as w}from"../git/legacy-branch-mode-conversion.js";const b=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function d(e,r){const t=[...e.matchAll(/(?:^|\s)@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md(?=\s|$)/g)].map(n=>n[1]),o=[...new Set(t)];if(!(o.length>1))return o.length===1?{epicId:o[0],source:"explicit"}:typeof r=="string"&&b.test(r)?{epicId:r,source:"persisted"}:void 0}function M(e,r){return d(e,r)?.epicId}function a(e,r,t){return Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e,outcome:"refused",reasonCode:r,executionRefCreated:!1,capturedAt:new Date(t&&Number.isFinite(Date.parse(t))?Date.parse(t):Date.now()).toISOString()})}const v=new Set(["branch-mode-conversion-git-raced","branch-mode-conversion-state-raced"]),u=2;async function R(e){const r={schemaVersion:1,kind:"branch-mode-conversion-start",epicId:e.epicId},t=e.nowIso&&Number.isFinite(Date.parse(e.nowIso))?()=>new Date(Date.parse(e.nowIso)):void 0;let o="branch-mode-conversion-internal-error";for(let n=1;n<=u;n+=1)try{const c=await w({projectRoot:e.projectRoot,epicId:e.epicId,...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{},...t?{now:t}:{}});if(c.kind!=="convert")return Object.freeze({...r,outcome:c.kind,attempts:n});const i=l(e.projectRoot,c,t?{now:t}:{});return Object.freeze({...r,outcome:"converted",attempts:n,...i.receipt?{receiptDigest:i.receipt.receiptDigest}:{}})}catch(c){if(o=c instanceof I?c.reasonCode:"branch-mode-conversion-internal-error",!v.has(o)||n===u)return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:n})}return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:u})}async function S(e){const r=d(e.args,e.persistedCurrentEpicId);if(!r)return{originBinding:a("unknown","origin-binding-start-target-ambiguous",e.nowIso),fetches:0};const{epicId:t}=r,o=await f(e.projectRoot,t);if(!o.exists)return{epicId:t,originBinding:a(t,"origin-binding-start-target-ambiguous",e.nowIso),fetches:0};if(r.source==="persisted"&&o.terminal)return{epicId:t,originBinding:a(t,"origin-binding-start-target-terminal",e.nowIso),fetches:0};const n=o.mode==="not-epic",c=n||!o.bound;let i;c&&o.originBranch&&(i=await h({projectRoot:e.projectRoot,originBranch:o.originBranch,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}));const p={projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{}};let s;o.mode==="resolved-epic"?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"not-required",attempts:0}):n&&i&&!i.ok?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"refused",reasonCode:i.reasonCode,attempts:0}):s=await R(p);const m=await g({projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{},...i?{originFetch:i}:{}});return{epicId:t,branchModeConversion:s,originBinding:m,fetches:i?1:0}}async function B(e){const r=d(e.args,e.persistedCurrentEpicId);return r?r.source==="persisted"&&(await f(e.projectRoot,r.epicId)).terminal?a(r.epicId,"origin-binding-start-target-terminal",e.nowIso):g({projectRoot:e.projectRoot,epicId:r.epicId,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}):a("unknown","origin-binding-start-target-ambiguous",e.nowIso)}export{B as planYoloopStartOriginBinding,d as resolveYoloopStartTarget,M as resolveYoloopStartTargetEpic,S as runYoloopStartAdaptations,R as runYoloopStartBranchModeConversion};
1
+ import{captureEpicOriginBindingAtYoloopStart as g,fetchOriginForYoloopStart as h,readYoloopStartEpic as f}from"../git/direct-yolo-checkpoint.js";import{applyLegacyBranchModeConversion as l,LegacyBranchModeConversionError as I,planLegacyBranchModeConversion as w}from"../git/legacy-branch-mode-conversion.js";const b=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function d(e,r){const t=[...e.matchAll(/(?:^|\s)@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md(?=\s|$)/g)].map(n=>n[1]),o=[...new Set(t)];if(!(o.length>1))return o.length===1?{epicId:o[0],source:"explicit"}:typeof r=="string"&&b.test(r)?{epicId:r,source:"persisted"}:void 0}function O(e,r){return d(e,r)?.epicId}function a(e,r,t){return Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e,outcome:"refused",reasonCode:r,executionRefCreated:!1,capturedAt:new Date(t&&Number.isFinite(Date.parse(t))?Date.parse(t):Date.now()).toISOString()})}const v=new Set(["branch-mode-conversion-git-raced","branch-mode-conversion-state-raced"]),u=2;async function B(e){const r={schemaVersion:1,kind:"branch-mode-conversion-start",epicId:e.epicId},t=e.nowIso&&Number.isFinite(Date.parse(e.nowIso))?()=>new Date(Date.parse(e.nowIso)):void 0;let o="branch-mode-conversion-internal-error";for(let n=1;n<=u;n+=1)try{const c=await w({projectRoot:e.projectRoot,epicId:e.epicId,...e.originBranch?{originBranch:e.originBranch}:{},...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{},...t?{now:t}:{}});if(c.kind!=="convert")return Object.freeze({...r,outcome:c.kind,attempts:n});const i=l(e.projectRoot,c,t?{now:t}:{});return Object.freeze({...r,outcome:"converted",attempts:n,...i.receipt?{receiptDigest:i.receipt.receiptDigest}:{}})}catch(c){if(o=c instanceof I?c.reasonCode:"branch-mode-conversion-internal-error",!v.has(o)||n===u)return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:n})}return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:u})}async function M(e){const r=d(e.args,e.persistedCurrentEpicId);if(!r)return{originBinding:a("unknown","origin-binding-start-target-ambiguous",e.nowIso),fetches:0};const{epicId:t}=r,o=await f(e.projectRoot,t);if(!o.exists)return{epicId:t,originBinding:a(t,"origin-binding-start-target-ambiguous",e.nowIso),fetches:0};if(r.source==="persisted"&&o.terminal)return{epicId:t,originBinding:a(t,"origin-binding-start-target-terminal",e.nowIso),fetches:0};const n=o.mode==="not-epic",c=n||!o.bound;let i;c&&o.originBranch&&(i=await h({projectRoot:e.projectRoot,originBranch:o.originBranch,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}));const m={projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...o.originBranch?.trim()?{originBranch:o.originBranch.trim()}:{},...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{}};let s;o.mode==="resolved-epic"?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"not-required",attempts:0}):n&&i&&!i.ok?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"refused",reasonCode:i.reasonCode,attempts:0}):s=await B(m);const p=await g({projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{},...i?{originFetch:i}:{}});return{epicId:t,branchModeConversion:s,originBinding:p,fetches:i?1:0}}async function S(e){const r=d(e.args,e.persistedCurrentEpicId);return r?r.source==="persisted"&&(await f(e.projectRoot,r.epicId)).terminal?a(r.epicId,"origin-binding-start-target-terminal",e.nowIso):g({projectRoot:e.projectRoot,epicId:r.epicId,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}):a("unknown","origin-binding-start-target-ambiguous",e.nowIso)}export{S as planYoloopStartOriginBinding,d as resolveYoloopStartTarget,O as resolveYoloopStartTargetEpic,M as runYoloopStartAdaptations,B as runYoloopStartBranchModeConversion};
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.64.0 | OrNexus Team
1
+ # 🧠 Neocortex v4.64.1 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.64.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.64.1 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root)'
6
6
  icon: '>'
7
- version: '4.64.0'
7
+ version: '4.64.1'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.64.0 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.64.1 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  tools:
@@ -108,7 +108,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
108
108
  ┌────────────────────────────────────────────────────────────┐
109
109
  │ │
110
110
  │ ####### N E O C O R T E X │
111
- │ ### ######## v4.64.0 │
111
+ │ ### ######## v4.64.1 │
112
112
  │ ######### ##### │
113
113
  │ ## ############## Development Orchestrator │
114
114
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.64.0'
7
+ version: '4.64.1'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.64.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.64.1 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  permissionMode: bypassPermissions
@@ -106,7 +106,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
106
106
  ┌────────────────────────────────────────────────────────────┐
107
107
  │ │
108
108
  │ ####### N E O C O R T E X │
109
- │ ### ######## v4.64.0 │
109
+ │ ### ######## v4.64.1 │
110
110
  │ ######### ##### │
111
111
  │ ## ############## Development Orchestrator │
112
112
  │ ## ### ###### ## OrNexus Team │
@@ -32,7 +32,7 @@ Codex built-in commands or actions.
32
32
 
33
33
  <!-- END: Plugin Conflict Prevention -->
34
34
 
35
- # Neocortex v4.64.0 | OrNexus Team
35
+ # Neocortex v4.64.1 | OrNexus Team
36
36
 
37
37
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
38
38
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.64.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.64.1 | OrNexus Team"
4
4
  model: inherit
5
5
  readonly: false
6
6
  is_background: false
@@ -104,7 +104,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
104
104
  ┌────────────────────────────────────────────────────────────┐
105
105
  │ │
106
106
  │ ####### N E O C O R T E X │
107
- │ ### ######## v4.64.0 │
107
+ │ ### ######## v4.64.1 │
108
108
  │ ######### ##### │
109
109
  │ ## ############## Development Orchestrator │
110
110
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex v4.64.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.64.1 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -62,7 +62,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
62
62
  ┌────────────────────────────────────────────────────────────┐
63
63
  │ │
64
64
  │ ####### N E O C O R T E X │
65
- │ ### ######## v4.64.0 │
65
+ │ ### ######## v4.64.1 │
66
66
  │ ######### ##### │
67
67
  │ ## ############## Development Orchestrator │
68
68
  │ ## ### ###### ## OrNexus Team │
@@ -64,7 +64,7 @@ task directive, I keep root-owned inline/shell-loop execution.
64
64
  ┌────────────────────────────────────────────────────────────┐
65
65
  │ │
66
66
  │ ####### N E O C O R T E X │
67
- │ ### ######## v4.64.0 │
67
+ │ ### ######## v4.64.1 │
68
68
  │ ######### ##### │
69
69
  │ ## ############## Development Orchestrator │
70
70
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: "neocortex"
3
- description: "Neocortex v4.64.0 | OrNexus Team"
3
+ description: "Neocortex v4.64.1 | OrNexus Team"
4
4
  tools:
5
5
  # Read / Edit (built-in tool sets)
6
6
  - read
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
72
72
  ┌────────────────────────────────────────────────────────────┐
73
73
  │ │
74
74
  │ ####### N E O C O R T E X │
75
- │ ### ######## v4.64.0 │
75
+ │ ### ######## v4.64.1 │
76
76
  │ ######### ##### │
77
77
  │ ## ############## Development Orchestrator │
78
78
  │ ## ### ###### ## OrNexus Team │