@ornexus/neocortex 4.60.24 → 4.60.26

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.
@@ -1,4 +1,4 @@
1
- import{execFile as at,spawn as Je}from"node:child_process";import{createHash as G,randomBytes as Me}from"node:crypto";import{lstat as le,readFile as B,realpath as X,stat as ct}from"node:fs/promises";import{basename as $,dirname as O,isAbsolute as Ke,join as D,relative as st,resolve as dt}from"node:path";import{promisify as ut}from"node:util";import{admitPreparedStoryBundle as ht}from"./prepared-story-bundle.js";import{acquireGitLifecyclePhysicalIntegrationLock as ft,assertGitLifecyclePrivateDirectory as q,assertGitLifecyclePrivateFile as V,applyGitLifecycleRuntimeOverlay as re,computeImmutableStoryQaEvidenceDigest as pt,computeP205StoryQaEvidenceDigest as lt,ensureGitLifecyclePrivateChildDirectory as be,ensureRuntimeEpic as ye,ensureRuntimeStory as yt,gitLifecycleRuntimeDirectory as wt,mutateGitLifecycleRuntime as Y,P205_COMPLETE_COMMAND as mt,readGitLifecycleRuntime as F,releaseGitLifecyclePhysicalIntegrationLock as gt,removeGitLifecyclePrivateDirectory as oe,verifyAcceptedGitLifecycleStoryCheckpoint as Re,verifyGitLifecyclePhysicalIntegrationLock as ke}from"../../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as St,anchoredCreateDirectory as xe,anchoredDirectoryIdentity as It,anchoredExecuteGit as Ee,anchoredEnsureDirectory as vt,anchoredRemoveFile as bt}from"../../git/secure-filesystem-boundary.js";const Ae=ut(at),Rt=String.raw`
1
+ import{execFile as st,spawn as Me}from"node:child_process";import{createHash as G,randomBytes as Ke}from"node:crypto";import{lstat as le,readFile as B,realpath as Y,stat as dt}from"node:fs/promises";import{basename as $,dirname as C,isAbsolute as Fe,join as D,relative as ut,resolve as ht}from"node:path";import{promisify as ft}from"node:util";import{admitPreparedStoryBundle as pt}from"./prepared-story-bundle.js";import{acquireGitLifecyclePhysicalIntegrationLock as lt,assertGitLifecyclePrivateDirectory as W,assertGitLifecyclePrivateFile as F,applyGitLifecycleRuntimeOverlay as re,computeImmutableStoryQaEvidenceDigest as yt,computeP205StoryQaEvidenceDigest as wt,ensureGitLifecyclePrivateChildDirectory as be,ensureRuntimeEpic as ye,ensureRuntimeStory as mt,gitLifecycleRuntimeDirectory as gt,mutateGitLifecycleRuntime as X,P205_COMPLETE_COMMAND as St,readGitLifecycleRuntime as V,releaseGitLifecyclePhysicalIntegrationLock as It,removeGitLifecyclePrivateDirectory as oe,verifyAcceptedGitLifecycleStoryCheckpoint as ke,verifyGitLifecyclePhysicalIntegrationLock as xe}from"../../git/git-lifecycle-store.js";import{anchoredAtomicWriteFile as vt,anchoredCreateDirectory as Ee,anchoredDirectoryIdentity as Rt,anchoredExecuteGit as Ae,anchoredEnsureDirectory as bt,anchoredRemoveFile as kt}from"../../git/secure-filesystem-boundary.js";import{GIT_LIFECYCLE_COMMIT_PUSH_STEP_ID as Ve,GIT_LIFECYCLE_REVIEW_PR_STEP_ID as we}from"../../git/git-lifecycle-step-ids.js";const je=ft(st),xt=String.raw`
2
2
  const fs = require('node:fs');
3
3
  const cp = require('node:child_process');
4
4
  const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encoded, handshake] = process.argv.slice(1);
@@ -46,13 +46,13 @@ runtime.on('close', (code, signal) => {
46
46
  if (signal) process.kill(process.pid, signal);
47
47
  else process.exit(Number.isInteger(code) ? code : 1);
48
48
  });
49
- `;function cr(e,r={}){return async(t,o,n={})=>Ot(e,t,o,n,r)}function sr(e={}){let r=Promise.resolve();return{async prepare(t){if((e.platform??process.platform)==="win32")return f("continuous-sandbox-platform-unsupported");if(!/^[a-f0-9]{64}$/.test(t.dispatchId))return f("continuous-sandbox-dispatch-invalid");if(!ce(t.targetRef))return f("continuous-sandbox-target-invalid");if(!Wt(t.executionBranch))return f("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(t.graphRevision))return f("continuous-graph-revision-invalid");const o=qt(t.authorizedWriteSet);if(o.length===0||o.length!==t.authorizedWriteSet.length)return f("continuous-authorized-write-set-invalid");const n=ze(o),a=r;let c=()=>{};r=new Promise(s=>{c=s}),await a;let i,d;try{const s=await xt(t.projectRoot),g=await P(s,["rev-parse","HEAD"]),S=await Se(s,t.epicId,t.storyId),v=S.revision,A=await wt(s),w=await be(A,"leases"),j=D(w,t.dispatchId);try{await xe(w,t.dispatchId),await q(j,w)}catch(m){if(!W(m,"EEXIST"))throw m;await q(j,w);const l=await ue(j,w);if(l!==void 0&&Vt(l.pid))return f("continuous-sandbox-lease-active");if(!l||!await oe(j,w,async E=>tt(await ue(E,w),l)))return f("continuous-sandbox-lease-owner-replaced");await xe(w,t.dispatchId),await q(j,w)}i=j,d=Object.freeze({pid:process.pid,createdAt:new Date().toISOString(),nonce:Me(16).toString("hex")}),await te(j,"owner.json",Buffer.from(JSON.stringify(d)),e.beforeSandboxWriteCommit),await V(D(j,"owner.json"),j);const b=await be(A,"sandboxes"),p=D(b,t.dispatchId.slice(0,20)),I=await Te(p,b);let R,u;const k=I?.preparedAt??new Date().toISOString(),x=I?.workspaceOwnerNonce??Me(16).toString("hex");if(I){if(I.projectRoot!==s||I.storyId!==t.storyId||I.targetRef!==t.targetRef||I.dispatchId!==t.dispatchId||I.epicId!==t.epicId||I.executionBranch!==t.executionBranch||I.graphRevision!==t.graphRevision||I.claimRevision!==n||I.graphAuthorityRevision!==v||I.graphAuthorityEpoch!==S.epoch||I.graphAuthorityStoryStatus!==S.storyStatus||!et(I.authorizedWriteSet,o)||(R=I.contextSnapshots.map(m=>({path:m.path,...m.contentBase64!==void 0?{content:Buffer.from(m.contentBase64,"base64")}:{}})),u=await It(p),u.dev!==I.workspaceIdentity.dev||u.ino!==I.workspaceIdentity.ino))return f("continuous-sandbox-recovery-mismatch")}else await oe(p,b),u=await xe(b,$(p)),await q(p,b),await ne(b,$(p),u,["init","--quiet"]),await At(s,p),await Et(s,b,$(p),u),await ne(b,$(p),u,["remote","add","neocortex-root",s]),await ne(b,$(p),u,["fetch","--quiet","--no-tags","neocortex-root",g]),await ne(b,$(p),u,["checkout","--quiet","--detach","FETCH_HEAD"]),R=await kt(s,p,t.epicId,t.targetRef,e.beforeSandboxWriteCommit),await Ft(p,b,{schemaVersion:1,projectRoot:s,storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:v,graphAuthorityEpoch:S.epoch,graphAuthorityStoryStatus:S.storyStatus,authorizedWriteSet:o,claimRevision:n,dispatchId:t.dispatchId,baseSha:g,preparedAt:k,workspaceOwnerNonce:x,workspaceIdentity:u,contextSnapshots:R.map(m=>({path:m.path,...m.content!==void 0?{contentBase64:m.content.toString("base64")}:{}}))},e.beforeSandboxWriteCommit);return i=void 0,{ok:!0,value:{projectRoot:s,workspacePath:p,workspaceStrategy:"branchless_sandbox",storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:v,graphAuthorityEpoch:S.epoch,graphAuthorityStoryStatus:S.storyStatus,authorizedWriteSet:o,claimRevision:n,baseSha:I?.baseSha??g,dispatchId:t.dispatchId,preparedAt:k,leasePath:j,leaseOwnerNonce:d.nonce,workspaceOwnerNonce:x,workspaceIdentity:u,contextSnapshots:R}}}catch{if(i&&d){const s=i,g=d;await oe(s,O(s),async S=>tt(await ue(S,O(s)),g)).catch(()=>{})}return f("continuous-sandbox-prepare-failed")}finally{c()}},async integrate(t,o){const n=await ue(t.leasePath,O(t.leasePath)).catch(()=>{}),a=await Te(t.workspacePath,O(t.workspacePath)).catch(()=>{});if(!n||n.nonce!==t.leaseOwnerNonce||a?.workspaceOwnerNonce!==t.workspaceOwnerNonce||a.dispatchId!==t.dispatchId||a.storyId!==t.storyId)return f("continuous-sandbox-owner-mismatch");const c=Ue(o?.nowIso??new Date().toISOString()),i=await ft(t.projectRoot,{kind:"continuous",storyId:t.storyId,sessionId:t.dispatchId,idempotencyKey:t.dispatchId,expiresAt:new Date(Date.parse(c)+1800*1e3).toISOString(),persistent:!1,createdAt:c});if(!i.ok)return f(i.reasonCode==="git-lifecycle-integration-backpressure"?"continuous-integration-backpressure":"continuous-integration-lease-failed");let d=[],s=!1,g=!1;try{const S=(await ie(t,["status","--porcelain"])).trimEnd(),v=await je(t,["rev-parse","HEAD"]);if(await ee(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch)return f("continuous-execution-branch-mismatch");const w=O(O(t.leasePath)),j=await be(w,"integrated"),b=D(j,t.dispatchId),p=await Qt(b,j);if(p?.childHeadSha===v&&p.bundle.storyId===t.storyId&&p.bundle.epicId===t.epicId&&p.bundle.executionBranch===t.executionBranch&&p.bundle.graphRevision===t.graphRevision&&p.bundle.claimRevision===t.claimRevision&&et(p.bundle.authorizedWriteSet,t.authorizedWriteSet)&&p.checkpoint.idempotencyKey===t.dispatchId&&p.checkpoint.bundleId===p.bundle.bundleId&&p.checkpoint.bundleDigest===p.bundle.bundleDigest&&p.checkpoint.graphRevision===t.graphRevision&&p.checkpoint.claimRevision===t.claimRevision&&await ae(t.projectRoot,["merge-base","--is-ancestor",p.rootHeadSha,"HEAD"])&&await Zt(t,p.checkpoint))return{ok:!0,value:{headSha:p.rootHeadSha,alreadyIntegrated:!0,bundle:p.bundle,checkpoint:p.checkpoint}};if(v!==t.baseSha)return f("continuous-sandbox-child-git-authority-denied");if(S.length===0)return f("continuous-bundle-empty");const I=S.split(`
50
- `).some(y=>y.length>0&&y[0]!==" "&&y[0]!=="?");I||await je(t,["add","-A"]);const R=L(await ie(t,["diff","--cached","--name-only","-z",t.baseSha]));if(R.length===0||R.some(y=>!ce(y)))return f("continuous-integration-write-set-invalid");if(!await jt(t,["merge-base","--is-ancestor",t.baseSha,v]))return f("continuous-bundle-base-not-ancestor");if(!await ae(t.projectRoot,["merge-base","--is-ancestor",t.baseSha,"HEAD"]))return f("continuous-root-base-not-ancestor");const u=o?.nowIso??new Date().toISOString(),k=Mt(o?.receiptRefs,t.dispatchId),x=await ie(t,["diff","--cached","--binary",t.baseSha]),m={schemaVersion:1,storyId:t.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:t.baseSha,bundleDigest:G("sha256").update(x).digest("hex"),graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,contextDigests:Object.fromEntries(t.contextSnapshots.map(y=>[y.path,G("sha256").update(y.content??Buffer.alloc(0)).digest("hex")])),validationRefs:k,createdAt:t.preparedAt,expiresAt:new Date(Date.parse(t.preparedAt)+1440*60*1e3).toISOString(),branchless:!0},l=Object.freeze({...m,bundleId:ze(m)}),E=await Xt(t,l);if(E){const y=await Ut(t,l,E);if(y)return await Le(b,v,E.headSha,l,y,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:l,checkpoint:y}}}if(!E&&await Jt(t.projectRoot,t.epicId)!==t.graphAuthorityRevision)return f("continuous-graph-revision-stale");if(E){const y=await Ze({lease:t,bundle:l,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:k,nowIso:u,qaRunner:e.storyQaRunner});if(!y.ok)return y;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:E.headSha});const N=await Qe({lease:t,physicalLock:i,checkpointAuthority:E.checkpointAuthority,bundle:l,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:[...k,`bundle:${l.bundleId}`,y.value.qaReceipt.receiptRef,y.value.reviewReceipt.receiptRef],qaReceipt:y.value.qaReceipt,reviewReceipt:y.value.reviewReceipt,recordedAt:u,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return N.ok?(await Le(b,v,E.headSha,l,N.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:l,checkpoint:N.value}}):N}if(I)return f("continuous-sandbox-child-git-authority-denied");if(L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])).length>0)return f("continuous-integration-root-index-dirty");const J=new Set(t.contextSnapshots.map(y=>y.path));if(R.filter(y=>!t.authorizedWriteSet.some(N=>ge(N,y))).length>0)return f("continuous-bundle-write-set-unauthorized");const M=R.filter(y=>!J.has(y)),ve=new Set(L(await z(t.projectRoot,["diff","--name-only","-z",`${t.baseSha}..HEAD`])));if(M.some(y=>ve.has(y)))return f("continuous-bundle-intervening-conflict");const he=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(M.some(y=>he.has(y)))return f("continuous-integration-root-conflict");d=await Bt(t.projectRoot,[...new Set([...R,".neocortex/state.json"])]);const H=await Pt(t,u);if(!H.ok)return H;const K=ht({bundle:l,payload:Buffer.from(x),expected:{epicId:t.epicId,storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,nowIso:u},writerLease:H.value});if(K.length>0)return await Ne(t.projectRoot,d),f(`continuous-bundle-admission-${K[0]}`);const fe=await P(t.projectRoot,["rev-parse","HEAD"]);let Q;await e.beforeRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:fe});try{await Y(t.projectRoot,y=>{const N=h(ye(y,t.epicId).branch_lease);if(N?.ownerStoryId!==t.storyId||N.sessionId!==t.dispatchId||N.idempotencyKey!==t.dispatchId||Date.parse(String(N.expiresAt))<=Date.now())throw new Error("continuous-checkpoint-writer-lease-lost")},{preCommit:async y=>{const N=await Se(t.projectRoot,t.epicId,t.storyId,y);if(N.revision!==t.graphAuthorityRevision||N.epoch!==t.graphAuthorityEpoch||N.storyStatus!==t.graphAuthorityStoryStatus)throw new Error("continuous-graph-revision-stale");if(!await ke(i.path,i.owner))throw new Error("continuous-integration-lock-raced");const rt=await ee(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),ot=await P(t.projectRoot,["rev-parse","HEAD"]);if(rt!==t.executionBranch||ot!==fe)throw new Error("continuous-integration-head-raced");const nt=L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])),it=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(nt.length>0)throw new Error("continuous-integration-root-index-dirty");if(M.some(_=>it.has(_)))throw new Error("continuous-integration-root-conflict");if(g=!0,M.length>0){const _=await ie(t,["diff","--cached","--binary",t.baseSha,"--",...M]);if(_.length>0&&!await Nt(t.projectRoot,["apply","--index","--3way","--whitespace=nowarn"],_))throw new Error("continuous-integration-conflict")}for(const _ of t.contextSnapshots){if(!R.includes(_.path))continue;const qe=await De(D(t.projectRoot,_.path)),We=await Dt(t,_.path),He=_.path===".neocortex/state.json"?Lt(_.content,qe,zt(_.content,We,t.storyId)):Gt(_.content,qe,We);if(!He.ok)throw new Error(_.path===".neocortex/state.json"?"continuous-state-merge-conflict":"continuous-context-merge-conflict");await te(t.projectRoot,_.path,He.value),await P(t.projectRoot,["add","-A","--",_.path])}if(R.includes(".neocortex/state.json")&&await P(t.projectRoot,["add","-A","--",".neocortex/state.json"]),await ae(t.projectRoot,["diff","--cached","--quiet"]))throw new Error("continuous-integration-empty-after-admission");Q=await Se(t.projectRoot,t.epicId,t.storyId,y),await P(t.projectRoot,["commit","-m",`feat(yoloop): integrate ${t.storyId}`,"-m",`Neocortex-Story: ${t.storyId}`,"-m",`Neocortex-Epic: ${t.epicId}`,"-m",`Neocortex-Execution-Branch: ${t.executionBranch}`,"-m",`Neocortex-Prepared-Base: ${t.baseSha}`,"-m",`Neocortex-Dispatch: ${t.dispatchId}`,"-m",`Neocortex-Bundle: ${l.bundleId}`,"-m",`Neocortex-Bundle-Digest: ${l.bundleDigest}`,"-m",`Neocortex-Graph-Revision: ${t.graphRevision}`,"-m",`Neocortex-Claim-Revision: ${t.claimRevision}`,"-m",`Neocortex-Checkpoint-Authority: ${Q.revision}`,"-m",`Neocortex-Checkpoint-Epoch: ${Q.epoch??"null"}`,"-m",`Neocortex-Checkpoint-Story-Status: ${Q.storyStatus??"null"}`]),s=!0}})}catch(y){g&&!s&&await Ne(t.projectRoot,d);const N=y instanceof Error&&/^continuous-/.test(y.message)?y.message:"continuous-integration-failed";return f(N)}const Z=await P(t.projectRoot,["rev-parse","HEAD"]);if(!Q)return f("continuous-checkpoint-authority-missing");await e.afterRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Z});const U=await Ze({lease:t,bundle:l,baseSha:fe,headSha:Z,receiptRefs:k,nowIso:u,qaRunner:e.storyQaRunner});if(!U.ok)return U;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Z});const pe=await Qe({lease:t,physicalLock:i,checkpointAuthority:Q,bundle:l,baseSha:fe,headSha:Z,receiptRefs:[...k,`bundle:${l.bundleId}`,U.value.qaReceipt.receiptRef,U.value.reviewReceipt.receiptRef],qaReceipt:U.value.qaReceipt,reviewReceipt:U.value.reviewReceipt,recordedAt:u,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return pe.ok?(await Le(b,v,Z,l,pe.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:Z,alreadyIntegrated:!1,bundle:l,checkpoint:pe.value}}):pe}catch{return g&&!s&&d.length>0&&await Ne(t.projectRoot,d),f("continuous-integration-failed")}finally{await $t(t).catch(()=>{}),await gt(i.path,i.owner).catch(()=>{})}},async release(t,o){o||await oe(t.workspacePath,O(t.workspacePath),async n=>{const a=await Te(n,O(t.workspacePath)).catch(()=>{});return a?.workspaceOwnerNonce===t.workspaceOwnerNonce&&a.dispatchId===t.dispatchId&&a.storyId===t.storyId}),await oe(t.leasePath,O(t.leasePath),async n=>(await ue(n,O(t.leasePath)).catch(()=>{}))?.nonce===t.leaseOwnerNonce)}}}async function kt(e,r,t,o,n){const a=[...new Set([".neocortex/state.json",o,`docs/epics/epic-${Kt(t)}.md`])],c=[];for(const i of a){if(!ce(i))continue;const d=await De(D(e,i));c.push({path:i,...d!==void 0?{content:d}:{}}),d!==void 0&&await te(r,i,d,n)}return c}async function xt(e){const r=await P(e,["rev-parse","--show-toplevel"]),[t,o]=await Promise.all([X(r),X(e)]);if(t!==o)throw new Error("project root mismatch");return t}async function Et(e,r,t,o){for(const n of["user.name","user.email"]){const a=await ee(e,["config","--get",n]);a&&await ne(r,t,o,["config",n,a])}}async function At(e,r){const t=await F(e);await Y(r,o=>{for(const[n,a]of Object.entries(t.epics))o.epics[n]={...structuredClone(a),branch_lease:null};for(const[n,a]of Object.entries(t.stories))o.stories[n]=structuredClone(a)})}async function ne(e,r,t,o){return(await Ee(e,r,t,o)).toString("utf8").trim()}async function ie(e,r){return(await Ee(O(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,r)).toString("utf8")}async function je(e,r){return(await ie(e,r)).trim()}async function jt(e,r){try{return await je(e,r),!0}catch{return!1}}async function Dt(e,r){try{return await Ee(O(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,["show",`:${r}`])}catch{return}}async function Ot(e,r,t,o,n){const a=Date.now(),c=A=>({exitCode:null,timedOut:!1,durationMs:Date.now()-a,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0,...A});if(o.signal?.aborted)return c({signal:"SIGTERM",cancelled:!0});if(!r||r.length>4096||r.includes("\0")||t.length>512||t.some(A=>A.length>32768||A.includes("\0")))return c({exitCode:73,stderr:"continuous-child-invocation-invalid",stderrBytes:35});const i=O(e.workspacePath),d=await le(i,{bigint:!0}),s=await ct(i,{bigint:!0});if(!d.isDirectory()||d.isSymbolicLink()||!s.isDirectory()||d.dev!==s.dev||d.ino!==s.ino)return c({exitCode:73,stderr:"continuous-child-parent-invalid",stderrBytes:31});await n.beforeHandoff?.();const g=Buffer.from(JSON.stringify({command:r,args:[...t]})).toString("base64url"),S=o.maxOutputBytes??64e3,v=Math.max(1,Math.min(o.timeoutMs??600*1e3,1800*1e3));return await new Promise(A=>{const w=Je(process.execPath,["-e",Rt,String(s.dev),String(s.ino),$(e.workspacePath),e.workspaceIdentity.dev,e.workspaceIdentity.ino,g,n.afterHandoff?"1":"0"],{cwd:i,env:o.env,stdio:["pipe","pipe","pipe"]});let j="",b="",p=0,I=0,R=!1,u=!1,k=!1,x=!n.afterHandoff;const m=(C,J)=>{R||(R=!0,clearTimeout(E),o.signal?.removeEventListener("abort",l),A({exitCode:C,...J?{signal:J}:{},timedOut:u,...k?{cancelled:!0}:{},durationMs:Date.now()-a,stdout:j,stderr:b,stdoutBytes:p,stderrBytes:I}))},l=()=>{k=!0,w.kill("SIGTERM")};o.signal?.addEventListener("abort",l,{once:!0});const E=setTimeout(()=>{u=!0,w.kill("SIGTERM")},v);w.stdout.on("data",C=>{p+=C.length,p+I>S?w.kill("SIGTERM"):j+=C.toString("utf8")}),w.stderr.on("data",C=>{I+=C.length,p+I>S?w.kill("SIGTERM"):b+=C.toString("utf8"),!x&&b.includes(`continuous-child-handoff-ready
51
- `)&&(x=!0,Promise.resolve(n.afterHandoff?.()).then(()=>w.stdin.end()).catch(()=>w.kill("SIGTERM")))}),w.once("error",()=>m(null)),w.once("close",(C,J)=>m(C,J)),n.afterHandoff||w.stdin.end()})}async function P(e,r){return(await z(e,r)).trim()}async function z(e,r){const t=await Ae("git",r,{cwd:e,encoding:"utf8",maxBuffer:16777216});return String(t.stdout)}async function ee(e,r){try{return await P(e,r)}catch(t){if(W(t,"ENOENT"))return;throw t}}async function ae(e,r){try{return await P(e,r),!0}catch{return!1}}async function Nt(e,r,t){return await new Promise(o=>{const n=Je("git",[...r],{cwd:e,stdio:["pipe","ignore","ignore"]});n.once("error",()=>o(!1)),n.once("close",a=>o(a===0)),n.stdin.end(t)})}async function dr(e,r,t){try{const o=await Ae("git",["show",`${r}:${t}`],{cwd:e,encoding:"buffer",maxBuffer:16777216});return Buffer.from(o.stdout)}catch(o){if(W(o,"ENOENT"))return;throw o}}async function De(e){try{return await B(e)}catch(r){if(W(r,"ENOENT"))return;throw r}}async function te(e,r,t,o){const n=se(r);if(!ce(n))throw new Error("continuous-sandbox-write-path-invalid");const a=await X(e);if(a!==dt(e))throw new Error("continuous-sandbox-write-root-symlink");const c=O(n)==="."?"":O(n),i=await Ct(a,c),d=await Ve(i),s=D(i,$(n));if(await we(s,a,!0),t===void 0){await o?.({boundaryRoot:a,relativePath:n,destinationPath:s}),await Fe(i,a,d),await we(s,a,!0),await bt(i,$(n));return}await o?.({boundaryRoot:a,relativePath:n,destinationPath:s}),await Fe(i,a,d),await we(s,a,!0),await St(i,$(n),t),await we(s,a,!1)}async function Ct(e,r){let t=e;for(const o of r.split("/").filter(Boolean)){t=D(t,o),await vt(O(t),$(t));const n=await le(t);if(!n.isDirectory()||n.isSymbolicLink()||await X(t)!==t)throw new Error("continuous-sandbox-write-component-unsafe");Oe(e,t)}return t}async function we(e,r,t){Oe(r,e);try{const o=await le(e);if(o.isSymbolicLink()||!o.isFile())throw new Error("continuous-sandbox-write-destination-unsafe");if(await X(e)!==e)throw new Error("continuous-sandbox-write-destination-symlink")}catch(o){if(t&&W(o,"ENOENT"))return;throw o}}function Oe(e,r){const t=st(e,r);if(t===""||t.startsWith("..")||Ke(t))throw new Error("continuous-sandbox-write-containment-invalid")}async function Ve(e){const r=await le(e,{bigint:!0});if(!r.isDirectory()||r.isSymbolicLink())throw new Error("continuous-sandbox-write-parent-unsafe");return{dev:r.dev,ino:r.ino}}async function _t(e,r,t){try{if(e!==r&&Oe(r,e),await X(e)!==e)return!1;const o=await Ve(e);return o.dev===t.dev&&o.ino===t.ino}catch{return!1}}async function Fe(e,r,t){if(!await _t(e,r,t))throw new Error("continuous-sandbox-write-parent-raced")}async function Bt(e,r){return await Promise.all(r.map(async t=>{const o=await De(D(e,t));return{path:t,...o!==void 0?{content:o}:{}}}))}async function Ne(e,r){const t=r.map(o=>o.path);t.length>0&&await ae(e,["reset","--quiet","HEAD","--",...t]);for(const o of r)await te(e,o.path,o.content)}async function Pt(e,r){try{const t=D(e.projectRoot,".neocortex/state.json"),o=T(JSON.parse((await B(t)).toString("utf8"))),n=h(h(o.epics)?.[e.epicId]),a=h(n?.branch_lease),c=Object.freeze({schemaVersion:1,ownerStoryId:e.storyId,sessionId:e.dispatchId,idempotencyKey:e.dispatchId,acquiredAt:r,expiresAt:new Date(Date.parse(r)+600*1e3).toISOString()});let i=!1;return await Y(e.projectRoot,d=>{const s=ye(d,e.epicId),g=h(s.branch_lease)??a;if(g&&typeof g.expiresAt=="string"&&g.expiresAt>r&&(g.ownerStoryId!==e.storyId||g.idempotencyKey!==e.dispatchId)){i=!0;return}s.branch_mode="epic",s.execution_branch=e.executionBranch,s.branch_lease=c}),i?f("continuous-epic-checkout-writer-active"):{ok:!0,value:c}}catch{return f("continuous-writer-lease-persist-failed")}}async function $t(e){await Y(e.projectRoot,r=>{const t=ye(r,e.epicId),o=h(t.branch_lease);o?.ownerStoryId===e.storyId&&o.idempotencyKey===e.dispatchId&&(t.branch_lease=null)})}async function Qe(e){try{const r=D(e.lease.projectRoot,".neocortex/state.json"),t=Object.freeze({schemaVersion:1,storyId:e.lease.storyId,epicId:e.lease.epicId,branch:e.lease.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.lease.dispatchId,dispatchId:e.lease.dispatchId,bundleId:e.bundle.bundleId,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,claimRevision:e.lease.claimRevision,receiptRefs:Object.freeze([...new Set(e.receiptRefs)]),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:e.qaReceipt,reviewReceipt:e.reviewReceipt,recordedAt:e.recordedAt}),o=T(JSON.parse((await B(r)).toString("utf8"))),n=h(h(o.stories)?.[e.lease.storyId]);let a="persisted",c,i,d,s,g=!1,S;const v=async(u,k,x)=>{const m=await ee(e.lease.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),l=await P(e.lease.projectRoot,["rev-parse","HEAD"]);if(m!==e.lease.executionBranch||l!==e.headSha)throw new Error("continuous-checkpoint-head-raced");if(u.graphRevision!==e.lease.graphRevision||u.claimRevision!==e.lease.claimRevision||u.bundleId!==e.bundle.bundleId||u.bundleDigest!==e.bundle.bundleDigest)throw new Error("continuous-checkpoint-graph-raced");const E=x??T(JSON.parse((await B(r)).toString("utf8"))),C=re(E,k??await F(e.lease.projectRoot)),J=h(h(C.epics)?.[e.lease.epicId]),Ie=h(h(C.stories)?.[e.lease.storyId]),M=Array.isArray(Ie?.depends_on)?Ie.depends_on.filter(H=>typeof H=="string"):[],ve=h(C.stories);if(J?.execution_branch!==e.lease.executionBranch||M.some(H=>{const K=h(ve?.[H]);return!K||!["done","completed","merged"].includes(String(K.status))}))throw new Error("continuous-checkpoint-dependency-raced");const he=L(await z(e.lease.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha]));if(he.length===0||he.some(H=>!e.lease.authorizedWriteSet.some(K=>ge(K,H))))throw new Error("continuous-checkpoint-write-set-raced");if(!await Re(e.lease.projectRoot,u,e.lease.storyId,e.lease.epicId,e.lease.executionBranch,void 0,e.lease.authorizedWriteSet))throw new Error("continuous-checkpoint-receipt-revalidation-failed")},A=await F(e.lease.projectRoot,{required:!0}),w=h(h(A.epics[e.lease.epicId])?.branch_lease);if(w?.ownerStoryId!==e.lease.storyId||w.idempotencyKey!==e.lease.dispatchId||w.sessionId!==e.lease.dispatchId||typeof w.expiresAt!="string"||Date.parse(w.expiresAt)<=(e.checkpointNow?.("before-mutation")??Date.now()))return f("continuous-checkpoint-writer-lease-lost");if(!await ke(e.physicalLock.path,e.physicalLock.owner))return f("continuous-checkpoint-integration-lock-raced");const j=await B(r),b=G("sha256").update(j).digest("hex");await v(t,A);const p=Pe(T(JSON.parse(j.toString("utf8"))),A,e.lease.epicId,e.lease.storyId);if(p.revision!==e.checkpointAuthority.revision||p.epoch!==e.checkpointAuthority.epoch||p.storyStatus!==e.checkpointAuthority.storyStatus)return f("continuous-graph-revision-stale");const I=await Y(e.lease.projectRoot,u=>{const k=ye(u,e.lease.epicId),x=h(k.branch_lease);i=x===void 0?void 0:structuredClone(x),d=structuredClone(u),g=u.stories[e.lease.storyId]!==void 0,s=structuredClone(u.stories[e.lease.storyId]??{}),S=structuredClone(k.branch_lease);const m=yt(u,e.lease.storyId),l=h(m.checkpoint)??h(n?.checkpoint);if(l?.idempotencyKey===e.lease.dispatchId){l.baseSha!==e.baseSha||l.headSha!==e.headSha||l.bundleId!==e.bundle.bundleId||l.bundleDigest!==e.bundle.bundleDigest||l.graphRevision!==e.lease.graphRevision||l.claimRevision!==e.lease.claimRevision?a="conflict":(a="reused",c=l,k.branch_lease=null);return}if(x?.ownerStoryId!==e.lease.storyId||x.idempotencyKey!==e.lease.dispatchId||x.sessionId!==e.lease.dispatchId){a="lease-lost";return}m.checkpoint=t,m.status="done",m.last_step="step-c-11-review-pr";const E=Array.isArray(m.steps_completed)?m.steps_completed.filter(C=>typeof C=="string"):[];m.steps_completed=[...new Set([...E,"step-c-08-commit-push","step-c-11-review-pr"])],k.branch_lease=null},{expectedRevision:A.revision,preCommit:async u=>{if(i?.ownerStoryId!==e.lease.storyId||i.idempotencyKey!==e.lease.dispatchId||i.sessionId!==e.lease.dispatchId||typeof i.expiresAt!="string"||Date.parse(i.expiresAt)<=(e.checkpointNow?.("pre-commit")??Date.now()))throw new Error("continuous-checkpoint-writer-lease-lost");if(await e.insideCheckpointPreCommit?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),!await ke(e.physicalLock.path,e.physicalLock.owner))throw new Error("continuous-checkpoint-integration-lock-raced");await v(c??t,u);const k=await B(r);if(G("sha256").update(k).digest("hex")!==b)throw new Error("continuous-graph-revision-stale");if(!d)throw new Error("continuous-checkpoint-authority-missing");const x=T(JSON.parse(k.toString("utf8"))),m=Pe(x,d,e.lease.epicId,e.lease.storyId);if(m.revision!==e.checkpointAuthority.revision||m.epoch!==e.checkpointAuthority.epoch||m.storyStatus!==e.checkpointAuthority.storyStatus)throw new Error("continuous-graph-revision-stale");if(a==="persisted"&&!$e(x,u,e.lease,t))throw new Error("continuous-checkpoint-projection-raced")}}),R=a;if(R==="conflict")return f("continuous-checkpoint-idempotency-conflict");if(R==="lease-lost")return f("continuous-checkpoint-writer-lease-lost");if(R==="reused"&&c)try{return await v(c),{ok:!0,value:c}}catch{return f("continuous-checkpoint-reused-evidence-invalid")}try{await e.afterCheckpointPersist?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha});const u=await F(e.lease.projectRoot,{required:!0});if(u.revision!==I.document.revision)throw new Error("continuous-checkpoint-post-persist-runtime-raced");await v(t,u);const k=await B(r);if(G("sha256").update(k).digest("hex")!==b)throw new Error("continuous-checkpoint-post-persist-authority-raced");const x=T(JSON.parse(k.toString("utf8")));if(!$e(x,u,e.lease,t))throw new Error("continuous-checkpoint-post-persist-projection-raced")}catch{const u=await B(r).catch(()=>{}),k=u===void 0||G("sha256").update(u).digest("hex")!==b;return await Y(e.lease.projectRoot,x=>{const m=h(x.epics[e.lease.epicId]),l=h(x.stories[e.lease.storyId]),E=u===void 0?void 0:T(JSON.parse(u.toString("utf8")));if(!m||!l||!E||!$e(E,x,e.lease,t))throw new Error("continuous-checkpoint-cleanup-cas-conflict");if(k){g?Ht(l,s??{}):delete x.stories[e.lease.storyId],S===void 0?delete m.branch_lease:m.branch_lease=structuredClone(S);return}l.checkpoint=null,l.status="blocked",m.branch_lease=null},{expectedRevision:I.document.revision}).catch(()=>{}),f("continuous-checkpoint-post-persist-raced")}return{ok:!0,value:t}}catch(r){const t=r instanceof Error&&/^continuous-/.test(r.message)?r.message:"continuous-checkpoint-persist-failed";return f(t)}}async function Ze(e){try{if(await P(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return f("continuous-story-evidence-head-raced");const r=await B(D(e.lease.projectRoot,"config","release-gates.v2.json"),"utf8"),t=JSON.parse(r),o=Array.isArray(t.requiredCompleteClasses)?t.requiredCompleteClasses.filter(R=>typeof R=="string"&&/^[a-z0-9-]+$/.test(R)):[];if(t.contract!=="P205-CI-02"||o.length===0)return f("continuous-story-qa-manifest-invalid");const n=String((await Ae(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:e.lease.projectRoot,encoding:"utf8",maxBuffer:32*1024*1024})).stdout);if(await e.qaRunner?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),await P(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return f("continuous-story-qa-head-raced");const a=Ue(e.nowIso),c=await P(e.lease.projectRoot,["rev-list","--count",`${e.baseSha}..${e.headSha}`]),i=await z(e.lease.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),d=L(await z(e.lease.projectRoot,["diff","--name-only","-z",`${e.baseSha}..${e.headSha}`])),s=pt({storyId:e.lease.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,commitBody:i,changedPaths:d}),g=G("sha256").update(r).digest("hex"),S=G("sha256").update(n).digest("hex"),v=lt({gitEvidenceDigest:s,headSha:e.headSha,graphRevision:e.lease.graphRevision,manifestDigest:g,gateIds:o,resultDigest:S}),A=`story-qa:${v}`,w=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,contract:"P205-CI-02",command:mt,manifestDigest:g,gateIds:Object.freeze(o),resultDigest:S,sourceEvidenceDigest:v,verdict:"passed",checkedAt:a,receiptRef:A}),j=[`Neocortex-Story: ${e.lease.storyId}`,`Neocortex-Epic: ${e.lease.epicId}`,`Neocortex-Bundle-Digest: ${e.bundle.bundleDigest}`,`Neocortex-Graph-Revision: ${e.lease.graphRevision}`];if(c!=="1"||!j.every(R=>i.includes(R))||d.length===0||d.some(R=>!e.lease.authorizedWriteSet.some(u=>ge(u,R))))return f("continuous-story-review-evidence-rejected");const b=G("sha256").update(["root-commit-range-review-v1",e.lease.storyId,e.baseSha,e.headSha,e.bundle.bundleDigest,e.lease.graphRevision,A,G("sha256").update(i).digest("hex"),[...d].sort().join(",")].join("\0")).digest("hex"),p=`story-review:${b}`,I=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,sourceEvidenceDigest:b,qaReceiptRef:A,verdict:"approved",reviewedAt:a,receiptRef:p});return{ok:!0,value:{qaReceipt:w,reviewReceipt:I}}}catch{return f("continuous-story-evidence-production-failed")}}function Ue(e){return Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function zt(e,r,t){if(r!==void 0)try{const o=e===void 0?{}:T(JSON.parse(e.toString("utf8"))),n=T(JSON.parse(r.toString("utf8"))),a=structuredClone(o),c=h(h(o.stories)?.[t]),i=h(h(n.stories)?.[t]),d=Tt(a,"stories"),s=structuredClone(c??{});for(const g of["status","last_step","steps_completed","last_updated","blocked_reason","blocked_at","implementation_evidence","validation_evidence","qa_gate"])i&&Object.prototype.hasOwnProperty.call(i,g)&&(s[g]=structuredClone(i[g]));return d[t]=s,Buffer.from(`${JSON.stringify(a,null,2)}
52
- `)}catch{return Buffer.from("{invalid-child-state")}}function Tt(e,r){const t=h(e[r]);if(t)return t;const o={};return e[r]=o,o}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("record expected");return e}function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Gt(e,r,t){return Be(t,e)||Be(r,t)?{ok:!0,value:r}:Be(r,e)?{ok:!0,value:t}:f("continuous-context-merge-conflict")}function Lt(e,r,t){try{const o=Xe(Ce(e),Ce(r),Ce(t));return o.ok?{ok:!0,value:o.value===void 0?void 0:Buffer.from(`${JSON.stringify(o.value,null,2)}
53
- `)}:o}catch{return f("continuous-state-merge-invalid")}}function Ce(e){return e===void 0?void 0:JSON.parse(e.toString("utf8"))}function Xe(e,r,t){if(me(t,e)||me(r,t))return{ok:!0,value:r};if(me(r,e))return{ok:!0,value:t};if(_e(e)&&_e(r)&&_e(t)){const o={};for(const n of[...new Set([...Object.keys(e),...Object.keys(r),...Object.keys(t)])].sort()){const a=Xe(e[n],r[n],t[n]);if(!a.ok)return a;a.value!==void 0&&(o[n]=a.value)}return{ok:!0,value:o}}if(Array.isArray(e)&&Array.isArray(r)&&Array.isArray(t)&&Ye(e,r)&&Ye(e,t)){const o=[...e,...r.slice(e.length),...t.slice(e.length)],n=new Set;return{ok:!0,value:o.filter(a=>{const c=JSON.stringify(a);return n.has(c)?!1:(n.add(c),!0)})}}return f("continuous-state-merge-conflict")}function _e(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ye(e,r){return e.length<=r.length&&e.every((t,o)=>me(t,r[o]))}function me(e,r){return JSON.stringify(e)===JSON.stringify(r)}function Be(e,r){return e===void 0||r===void 0?e===r:e.equals(r)}function L(e){return e.split("\0").filter(Boolean)}function ce(e){const r=se(e);return r.length>0&&r.length<=1024&&!Ke(r)&&!/^[A-Za-z]:\//.test(r)&&!r.split("/").includes("..")&&!r.includes("\0")&&!r.startsWith("/")}function se(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/")}function qt(e){const r=e.map(se).filter(ce);return[...new Set(r)].sort()}function ge(e,r){const t=se(e),o=se(r);return t===o||t.endsWith("/")&&o.startsWith(t)}function Wt(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function et(e,r){return e.length===r.length&&e.every((t,o)=>t===r[o])}async function Se(e,r,t,o){const n=T(JSON.parse(await B(D(e,".neocortex/state.json"),"utf8")));return Pe(n,o??await F(e),r,t)}function Pe(e,r,t,o){const n=re(e,r),a=h(n.epics),c=h(n.stories),i=h(a?.[t])??{},d=(Array.isArray(i.stories)?i.stories:Array.isArray(i.story_ids)?i.story_ids:[]).filter(v=>typeof v=="string"),s=d.length>0?d:Object.entries(c??{}).filter(([v,A])=>h(A)?.epic_id===t||v.startsWith(`${t}.`)).map(([v])=>v).sort(),g=["status","depends_on","files_to_modify","contracts","contract_refs","shared_surfaces","steps_completed","last_step","branch_name","physicalMergeStatus","merged","checkpoint","planning","attempts","retry_count","rollback_receipt","cancelled_at"],S=Object.fromEntries(s.map(v=>{const A=h(c?.[v])??{};return[v,Object.fromEntries(g.filter(w=>Object.prototype.hasOwnProperty.call(A,w)).map(w=>[w,A[w]]))]}));return{revision:ze({epicId:t,epic:{stories:s,status:i.status??null,branch_mode:i.branch_mode??null,execution_branch:i.execution_branch??null,graph_revision:i.graph_revision??null,depends_on:i.depends_on??null,planning:i.planning??null,execution_plan:i.execution_plan??null,waves:i.waves??null,current_wave:i.current_wave??null,replan:i.replan??null,replan_revision:i.replan_revision??null,dependency_graph:i.dependency_graph??null,scheduler:i.scheduler??null,attempts:i.attempts??null,retry_count:i.retry_count??null},stories:S}),epoch:typeof i.graph_revision=="string"?i.graph_revision:null,storyStatus:typeof h(c?.[o])?.status=="string"?String(h(c?.[o])?.status):null}}function $e(e,r,t,o){const n=re(e,r),a=h(h(n.epics)?.[t.epicId]),c=h(h(n.stories)?.[t.storyId]),i=Array.isArray(c?.steps_completed)?c.steps_completed.filter(d=>typeof d=="string"):[];return!!(a&&c&&a.branch_lease===null&&c.status==="done"&&c.last_step==="step-c-11-review-pr"&&i.includes("step-c-08-commit-push")&&i.includes("step-c-11-review-pr")&&de(c.checkpoint)===de(o))}function Ht(e,r){for(const t of Object.keys(e))delete e[t];Object.assign(e,structuredClone(r))}async function Jt(e,r){return(await Se(e,r,"")).revision}function ze(e){return G("sha256").update(de(e)).digest("hex")}function de(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(de).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${de(t)}`).join(",")}}`}function Mt(e,r){const t=(e??[]).filter(o=>/^[A-Za-z0-9._/:@#-]{1,200}$/.test(o)&&!o.includes(".."));return Object.freeze([...new Set(t.length>0?t:[`dispatch:${r}`])].sort())}function Kt(e){return e.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,80)}function f(e){return{ok:!1,reasonCode:e}}function W(e,r){return e instanceof Error&&"code"in e&&e.code===r}async function ue(e,r){try{await q(e,r);const t=D(e,"owner.json");await V(t,e);const o=JSON.parse(await B(t,"utf8"));if(!Number.isSafeInteger(o.pid)||Number(o.pid)<=0||typeof o.createdAt!="string"||!Number.isFinite(Date.parse(o.createdAt))||typeof o.nonce!="string"||!/^[a-f0-9]{32}$/.test(o.nonce))throw new Error("continuous-sandbox-lease-owner-invalid");return{pid:Number(o.pid),createdAt:o.createdAt,nonce:o.nonce}}catch(t){if(W(t,"ENOENT"))return;throw t}}function tt(e,r){return e?.pid===r.pid&&e.createdAt===r.createdAt&&e.nonce===r.nonce}function Vt(e){try{return process.kill(e,0),!0}catch(r){return W(r,"EPERM")}}async function Te(e,r){try{await q(e,r);const t=D(e,".git");await q(t,e);const o=D(t,"neocortex-sandbox.json");await V(o,t);const n=JSON.parse(await B(o,"utf8"));if(n.schemaVersion!==1||typeof n.workspaceOwnerNonce!="string"||!/^[a-f0-9]{32}$/.test(n.workspaceOwnerNonce)||!/^[a-f0-9]{64}$/.test(n.graphAuthorityRevision)||!(n.graphAuthorityEpoch===null||/^[a-f0-9]{64}$/.test(n.graphAuthorityEpoch))||!(n.graphAuthorityStoryStatus===null||typeof n.graphAuthorityStoryStatus=="string"&&n.graphAuthorityStoryStatus.length<=80)||typeof n.workspaceIdentity?.dev!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.dev)||typeof n.workspaceIdentity?.ino!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.ino))throw new Error("continuous-sandbox-metadata-invalid");return n}catch(t){if(W(t,"ENOENT"))return;throw t}}async function Ft(e,r,t,o){await q(e,r);const n=D(e,".git");await q(n,e);const a=D(n,"neocortex-sandbox.json");await te(e,".git/neocortex-sandbox.json",Buffer.from(`${JSON.stringify(t,null,2)}
54
- `),o),await V(a,n)}async function Qt(e,r){try{await V(e,r);const t=JSON.parse(await B(e,"utf8"));return typeof t.childHeadSha=="string"&&typeof t.rootHeadSha=="string"&&/^[a-f0-9]{40,64}$/.test(t.childHeadSha)&&/^[a-f0-9]{40,64}$/.test(t.rootHeadSha)&&t.bundle?.schemaVersion===1&&t.checkpoint?.schemaVersion===1?t:void 0}catch(t){if(W(t,"ENOENT"))return;throw t}}async function Zt(e,r){try{const t=T(JSON.parse(await B(D(e.projectRoot,".neocortex/state.json"),"utf8"))),o=re(t,await F(e.projectRoot)),n=h(h(o.stories)?.[e.storyId]),a=h(n?.checkpoint);return a?.idempotencyKey===r.idempotencyKey&&a.headSha===r.headSha&&a.bundleDigest===r.bundleDigest&&h(h(o.epics)?.[e.epicId])?.branch_lease===null&&await Re(e.projectRoot,a,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)}catch{return!1}}async function Ut(e,r,t){try{const o=T(JSON.parse(await B(D(e.projectRoot,".neocortex/state.json"),"utf8"))),n=re(o,await F(e.projectRoot)),a=h(h(n.stories)?.[e.storyId]),c=h(a?.checkpoint);return c?.schemaVersion!==1||c.storyId!==e.storyId||c.epicId!==e.epicId||c.branch!==e.executionBranch||c.baseSha!==t.baseSha||c.headSha!==t.headSha||c.idempotencyKey!==e.dispatchId||c.dispatchId!==e.dispatchId||c.bundleId!==r.bundleId||c.bundleDigest!==r.bundleDigest||c.graphRevision!==e.graphRevision||c.claimRevision!==e.claimRevision||h(h(n.epics)?.[e.epicId])?.branch_lease!==null||!await Re(e.projectRoot,c,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)?void 0:c}catch{return}}async function Xt(e,r){const t=(await ee(e.projectRoot,["log","--format=%H","--fixed-strings",`--grep=Neocortex-Dispatch: ${e.dispatchId}`]))?.split(`
49
+ `;function ur(e,r={}){return async(t,o,n={})=>Nt(e,t,o,n,r)}function hr(e={}){let r=Promise.resolve();return{async prepare(t){if((e.platform??process.platform)==="win32")return f("continuous-sandbox-platform-unsupported");if(!/^[a-f0-9]{64}$/.test(t.dispatchId))return f("continuous-sandbox-dispatch-invalid");if(!ce(t.targetRef))return f("continuous-sandbox-target-invalid");if(!Jt(t.executionBranch))return f("continuous-execution-branch-invalid");if(!/^[a-f0-9]{64}$/.test(t.graphRevision))return f("continuous-graph-revision-invalid");const o=Ht(t.authorizedWriteSet);if(o.length===0||o.length!==t.authorizedWriteSet.length)return f("continuous-authorized-write-set-invalid");const n=Te(o),a=r;let c=()=>{};r=new Promise(s=>{c=s}),await a;let i,d;try{const s=await At(t.projectRoot),g=await P(s,["rev-parse","HEAD"]),S=await Ie(s,t.epicId,t.storyId),v=S.revision,A=await gt(s),w=await be(A,"leases"),j=D(w,t.dispatchId);try{await Ee(w,t.dispatchId),await W(j,w)}catch(m){if(!q(m,"EEXIST"))throw m;await W(j,w);const l=await ue(j,w);if(l!==void 0&&Qt(l.pid))return f("continuous-sandbox-lease-active");if(!l||!await oe(j,w,async E=>ot(await ue(E,w),l)))return f("continuous-sandbox-lease-owner-replaced");await Ee(w,t.dispatchId),await W(j,w)}i=j,d=Object.freeze({pid:process.pid,createdAt:new Date().toISOString(),nonce:Ke(16).toString("hex")}),await te(j,"owner.json",Buffer.from(JSON.stringify(d)),e.beforeSandboxWriteCommit),await F(D(j,"owner.json"),j);const R=await be(A,"sandboxes"),p=D(R,t.dispatchId.slice(0,20)),I=await Ge(p,R);let b,u;const k=I?.preparedAt??new Date().toISOString(),x=I?.workspaceOwnerNonce??Ke(16).toString("hex");if(I){if(I.projectRoot!==s||I.storyId!==t.storyId||I.targetRef!==t.targetRef||I.dispatchId!==t.dispatchId||I.epicId!==t.epicId||I.executionBranch!==t.executionBranch||I.graphRevision!==t.graphRevision||I.claimRevision!==n||I.graphAuthorityRevision!==v||I.graphAuthorityEpoch!==S.epoch||I.graphAuthorityStoryStatus!==S.storyStatus||!rt(I.authorizedWriteSet,o)||(b=I.contextSnapshots.map(m=>({path:m.path,...m.contentBase64!==void 0?{content:Buffer.from(m.contentBase64,"base64")}:{}})),u=await Rt(p),u.dev!==I.workspaceIdentity.dev||u.ino!==I.workspaceIdentity.ino))return f("continuous-sandbox-recovery-mismatch")}else await oe(p,R),u=await Ee(R,$(p)),await W(p,R),await ne(R,$(p),u,["init","--quiet"]),await Dt(s,p),await jt(s,R,$(p),u),await ne(R,$(p),u,["remote","add","neocortex-root",s]),await ne(R,$(p),u,["fetch","--quiet","--no-tags","neocortex-root",g]),await ne(R,$(p),u,["checkout","--quiet","--detach","FETCH_HEAD"]),b=await Et(s,p,t.epicId,t.targetRef,e.beforeSandboxWriteCommit),await Zt(p,R,{schemaVersion:1,projectRoot:s,storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:v,graphAuthorityEpoch:S.epoch,graphAuthorityStoryStatus:S.storyStatus,authorizedWriteSet:o,claimRevision:n,dispatchId:t.dispatchId,baseSha:g,preparedAt:k,workspaceOwnerNonce:x,workspaceIdentity:u,contextSnapshots:b.map(m=>({path:m.path,...m.content!==void 0?{contentBase64:m.content.toString("base64")}:{}}))},e.beforeSandboxWriteCommit);return i=void 0,{ok:!0,value:{projectRoot:s,workspacePath:p,workspaceStrategy:"branchless_sandbox",storyId:t.storyId,targetRef:t.targetRef,epicId:t.epicId,executionBranch:t.executionBranch,graphRevision:t.graphRevision,graphAuthorityRevision:v,graphAuthorityEpoch:S.epoch,graphAuthorityStoryStatus:S.storyStatus,authorizedWriteSet:o,claimRevision:n,baseSha:I?.baseSha??g,dispatchId:t.dispatchId,preparedAt:k,leasePath:j,leaseOwnerNonce:d.nonce,workspaceOwnerNonce:x,workspaceIdentity:u,contextSnapshots:b}}}catch{if(i&&d){const s=i,g=d;await oe(s,C(s),async S=>ot(await ue(S,C(s)),g)).catch(()=>{})}return f("continuous-sandbox-prepare-failed")}finally{c()}},async integrate(t,o){const n=await ue(t.leasePath,C(t.leasePath)).catch(()=>{}),a=await Ge(t.workspacePath,C(t.workspacePath)).catch(()=>{});if(!n||n.nonce!==t.leaseOwnerNonce||a?.workspaceOwnerNonce!==t.workspaceOwnerNonce||a.dispatchId!==t.dispatchId||a.storyId!==t.storyId)return f("continuous-sandbox-owner-mismatch");const c=Xe(o?.nowIso??new Date().toISOString()),i=await lt(t.projectRoot,{kind:"continuous",storyId:t.storyId,sessionId:t.dispatchId,idempotencyKey:t.dispatchId,expiresAt:new Date(Date.parse(c)+1800*1e3).toISOString(),persistent:!1,createdAt:c});if(!i.ok)return f(i.reasonCode==="git-lifecycle-integration-backpressure"?"continuous-integration-backpressure":"continuous-integration-lease-failed");let d=[],s=!1,g=!1;try{const S=(await ie(t,["status","--porcelain"])).trimEnd(),v=await De(t,["rev-parse","HEAD"]);if(await ee(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"])!==t.executionBranch)return f("continuous-execution-branch-mismatch");const w=C(C(t.leasePath)),j=await be(w,"integrated"),R=D(j,t.dispatchId),p=await Ut(R,j);if(p?.childHeadSha===v&&p.bundle.storyId===t.storyId&&p.bundle.epicId===t.epicId&&p.bundle.executionBranch===t.executionBranch&&p.bundle.graphRevision===t.graphRevision&&p.bundle.claimRevision===t.claimRevision&&rt(p.bundle.authorizedWriteSet,t.authorizedWriteSet)&&p.checkpoint.idempotencyKey===t.dispatchId&&p.checkpoint.bundleId===p.bundle.bundleId&&p.checkpoint.bundleDigest===p.bundle.bundleDigest&&p.checkpoint.graphRevision===t.graphRevision&&p.checkpoint.claimRevision===t.claimRevision&&await ae(t.projectRoot,["merge-base","--is-ancestor",p.rootHeadSha,"HEAD"])&&await Yt(t,p.checkpoint))return{ok:!0,value:{headSha:p.rootHeadSha,alreadyIntegrated:!0,bundle:p.bundle,checkpoint:p.checkpoint}};if(v!==t.baseSha)return f("continuous-sandbox-child-git-authority-denied");if(S.length===0)return f("continuous-bundle-empty");const I=S.split(`
50
+ `).some(y=>y.length>0&&y[0]!==" "&&y[0]!=="?");I||await De(t,["add","-A"]);const b=L(await ie(t,["diff","--cached","--name-only","-z",t.baseSha]));if(b.length===0||b.some(y=>!ce(y)))return f("continuous-integration-write-set-invalid");if(!await Ct(t,["merge-base","--is-ancestor",t.baseSha,v]))return f("continuous-bundle-base-not-ancestor");if(!await ae(t.projectRoot,["merge-base","--is-ancestor",t.baseSha,"HEAD"]))return f("continuous-root-base-not-ancestor");const u=o?.nowIso??new Date().toISOString(),k=Ft(o?.receiptRefs,t.dispatchId),x=await ie(t,["diff","--cached","--binary",t.baseSha]),m={schemaVersion:1,storyId:t.storyId,epicId:t.epicId,executionBranch:t.executionBranch,baseSha:t.baseSha,bundleDigest:G("sha256").update(x).digest("hex"),graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,contextDigests:Object.fromEntries(t.contextSnapshots.map(y=>[y.path,G("sha256").update(y.content??Buffer.alloc(0)).digest("hex")])),validationRefs:k,createdAt:t.preparedAt,expiresAt:new Date(Date.parse(t.preparedAt)+1440*60*1e3).toISOString(),branchless:!0},l=Object.freeze({...m,bundleId:Te(m)}),E=await er(t,l);if(E){const y=await Xt(t,l,E);if(y)return await We(R,v,E.headSha,l,y,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:l,checkpoint:y}}}if(!E&&await Kt(t.projectRoot,t.epicId)!==t.graphAuthorityRevision)return f("continuous-graph-revision-stale");if(E){const y=await Ye({lease:t,bundle:l,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:k,nowIso:u,qaRunner:e.storyQaRunner});if(!y.ok)return y;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:E.headSha});const O=await Ue({lease:t,physicalLock:i,checkpointAuthority:E.checkpointAuthority,bundle:l,baseSha:E.baseSha,headSha:E.headSha,receiptRefs:[...k,`bundle:${l.bundleId}`,y.value.qaReceipt.receiptRef,y.value.reviewReceipt.receiptRef],qaReceipt:y.value.qaReceipt,reviewReceipt:y.value.reviewReceipt,recordedAt:u,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return O.ok?(await We(R,v,E.headSha,l,O.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:E.headSha,alreadyIntegrated:!0,bundle:l,checkpoint:O.value}}):O}if(I)return f("continuous-sandbox-child-git-authority-denied");if(L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])).length>0)return f("continuous-integration-root-index-dirty");const J=new Set(t.contextSnapshots.map(y=>y.path));if(b.filter(y=>!t.authorizedWriteSet.some(O=>Se(O,y))).length>0)return f("continuous-bundle-write-set-unauthorized");const M=b.filter(y=>!J.has(y)),Re=new Set(L(await z(t.projectRoot,["diff","--name-only","-z",`${t.baseSha}..HEAD`])));if(M.some(y=>Re.has(y)))return f("continuous-bundle-intervening-conflict");const he=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(M.some(y=>he.has(y)))return f("continuous-integration-root-conflict");d=await $t(t.projectRoot,[...new Set([...b,".neocortex/state.json"])]);const H=await zt(t,u);if(!H.ok)return H;const K=pt({bundle:l,payload:Buffer.from(x),expected:{epicId:t.epicId,storyId:t.storyId,executionBranch:t.executionBranch,baseSha:t.baseSha,graphRevision:t.graphRevision,claimRevision:t.claimRevision,authorizedWriteSet:t.authorizedWriteSet,nowIso:u},writerLease:H.value});if(K.length>0)return await Ne(t.projectRoot,d),f(`continuous-bundle-admission-${K[0]}`);const fe=await P(t.projectRoot,["rev-parse","HEAD"]);let Q;await e.beforeRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:fe});try{await X(t.projectRoot,y=>{const O=h(ye(y,t.epicId).branch_lease);if(O?.ownerStoryId!==t.storyId||O.sessionId!==t.dispatchId||O.idempotencyKey!==t.dispatchId||Date.parse(String(O.expiresAt))<=Date.now())throw new Error("continuous-checkpoint-writer-lease-lost")},{preCommit:async y=>{const O=await Ie(t.projectRoot,t.epicId,t.storyId,y);if(O.revision!==t.graphAuthorityRevision||O.epoch!==t.graphAuthorityEpoch||O.storyStatus!==t.graphAuthorityStoryStatus)throw new Error("continuous-graph-revision-stale");if(!await xe(i.path,i.owner))throw new Error("continuous-integration-lock-raced");const nt=await ee(t.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),it=await P(t.projectRoot,["rev-parse","HEAD"]);if(nt!==t.executionBranch||it!==fe)throw new Error("continuous-integration-head-raced");const at=L(await z(t.projectRoot,["diff","--cached","--name-only","-z"])),ct=new Set([...L(await z(t.projectRoot,["diff","--name-only","-z"])),...L(await z(t.projectRoot,["ls-files","--others","--exclude-standard","-z"]))]);if(at.length>0)throw new Error("continuous-integration-root-index-dirty");if(M.some(_=>ct.has(_)))throw new Error("continuous-integration-root-conflict");if(g=!0,M.length>0){const _=await ie(t,["diff","--cached","--binary",t.baseSha,"--",...M]);if(_.length>0&&!await _t(t.projectRoot,["apply","--index","--3way","--whitespace=nowarn"],_))throw new Error("continuous-integration-conflict")}for(const _ of t.contextSnapshots){if(!b.includes(_.path))continue;const qe=await Ce(D(t.projectRoot,_.path)),He=await Ot(t,_.path),Je=_.path===".neocortex/state.json"?qt(_.content,qe,Gt(_.content,He,t.storyId)):Wt(_.content,qe,He);if(!Je.ok)throw new Error(_.path===".neocortex/state.json"?"continuous-state-merge-conflict":"continuous-context-merge-conflict");await te(t.projectRoot,_.path,Je.value),await P(t.projectRoot,["add","-A","--",_.path])}if(b.includes(".neocortex/state.json")&&await P(t.projectRoot,["add","-A","--",".neocortex/state.json"]),await ae(t.projectRoot,["diff","--cached","--quiet"]))throw new Error("continuous-integration-empty-after-admission");Q=await Ie(t.projectRoot,t.epicId,t.storyId,y),await P(t.projectRoot,["commit","-m",`feat(yoloop): integrate ${t.storyId}`,"-m",`Neocortex-Story: ${t.storyId}`,"-m",`Neocortex-Epic: ${t.epicId}`,"-m",`Neocortex-Execution-Branch: ${t.executionBranch}`,"-m",`Neocortex-Prepared-Base: ${t.baseSha}`,"-m",`Neocortex-Dispatch: ${t.dispatchId}`,"-m",`Neocortex-Bundle: ${l.bundleId}`,"-m",`Neocortex-Bundle-Digest: ${l.bundleDigest}`,"-m",`Neocortex-Graph-Revision: ${t.graphRevision}`,"-m",`Neocortex-Claim-Revision: ${t.claimRevision}`,"-m",`Neocortex-Checkpoint-Authority: ${Q.revision}`,"-m",`Neocortex-Checkpoint-Epoch: ${Q.epoch??"null"}`,"-m",`Neocortex-Checkpoint-Story-Status: ${Q.storyStatus??"null"}`]),s=!0}})}catch(y){g&&!s&&await Ne(t.projectRoot,d);const O=y instanceof Error&&/^continuous-/.test(y.message)?y.message:"continuous-integration-failed";return f(O)}const Z=await P(t.projectRoot,["rev-parse","HEAD"]);if(!Q)return f("continuous-checkpoint-authority-missing");await e.afterRootCommit?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Z});const U=await Ye({lease:t,bundle:l,baseSha:fe,headSha:Z,receiptRefs:k,nowIso:u,qaRunner:e.storyQaRunner});if(!U.ok)return U;await e.beforeCheckpointPersist?.({projectRoot:t.projectRoot,storyId:t.storyId,headSha:Z});const pe=await Ue({lease:t,physicalLock:i,checkpointAuthority:Q,bundle:l,baseSha:fe,headSha:Z,receiptRefs:[...k,`bundle:${l.bundleId}`,U.value.qaReceipt.receiptRef,U.value.reviewReceipt.receiptRef],qaReceipt:U.value.qaReceipt,reviewReceipt:U.value.reviewReceipt,recordedAt:u,checkpointNow:e.checkpointNow,insideCheckpointPreCommit:e.insideCheckpointPreCommit,afterCheckpointPersist:e.afterCheckpointPersist});return pe.ok?(await We(R,v,Z,l,pe.value,e.beforeSandboxWriteCommit),{ok:!0,value:{headSha:Z,alreadyIntegrated:!1,bundle:l,checkpoint:pe.value}}):pe}catch{return g&&!s&&d.length>0&&await Ne(t.projectRoot,d),f("continuous-integration-failed")}finally{await Tt(t).catch(()=>{}),await It(i.path,i.owner).catch(()=>{})}},async release(t,o){o||await oe(t.workspacePath,C(t.workspacePath),async n=>{const a=await Ge(n,C(t.workspacePath)).catch(()=>{});return a?.workspaceOwnerNonce===t.workspaceOwnerNonce&&a.dispatchId===t.dispatchId&&a.storyId===t.storyId}),await oe(t.leasePath,C(t.leasePath),async n=>(await ue(n,C(t.leasePath)).catch(()=>{}))?.nonce===t.leaseOwnerNonce)}}}async function Et(e,r,t,o,n){const a=[...new Set([".neocortex/state.json",o,`docs/epics/epic-${Vt(t)}.md`])],c=[];for(const i of a){if(!ce(i))continue;const d=await Ce(D(e,i));c.push({path:i,...d!==void 0?{content:d}:{}}),d!==void 0&&await te(r,i,d,n)}return c}async function At(e){const r=await P(e,["rev-parse","--show-toplevel"]),[t,o]=await Promise.all([Y(r),Y(e)]);if(t!==o)throw new Error("project root mismatch");return t}async function jt(e,r,t,o){for(const n of["user.name","user.email"]){const a=await ee(e,["config","--get",n]);a&&await ne(r,t,o,["config",n,a])}}async function Dt(e,r){const t=await V(e);await X(r,o=>{for(const[n,a]of Object.entries(t.epics))o.epics[n]={...structuredClone(a),branch_lease:null};for(const[n,a]of Object.entries(t.stories))o.stories[n]=structuredClone(a)})}async function ne(e,r,t,o){return(await Ae(e,r,t,o)).toString("utf8").trim()}async function ie(e,r){return(await Ae(C(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,r)).toString("utf8")}async function De(e,r){return(await ie(e,r)).trim()}async function Ct(e,r){try{return await De(e,r),!0}catch{return!1}}async function Ot(e,r){try{return await Ae(C(e.workspacePath),$(e.workspacePath),e.workspaceIdentity,["show",`:${r}`])}catch{return}}async function Nt(e,r,t,o,n){const a=Date.now(),c=A=>({exitCode:null,timedOut:!1,durationMs:Date.now()-a,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0,...A});if(o.signal?.aborted)return c({signal:"SIGTERM",cancelled:!0});if(!r||r.length>4096||r.includes("\0")||t.length>512||t.some(A=>A.length>32768||A.includes("\0")))return c({exitCode:73,stderr:"continuous-child-invocation-invalid",stderrBytes:35});const i=C(e.workspacePath),d=await le(i,{bigint:!0}),s=await dt(i,{bigint:!0});if(!d.isDirectory()||d.isSymbolicLink()||!s.isDirectory()||d.dev!==s.dev||d.ino!==s.ino)return c({exitCode:73,stderr:"continuous-child-parent-invalid",stderrBytes:31});await n.beforeHandoff?.();const g=Buffer.from(JSON.stringify({command:r,args:[...t]})).toString("base64url"),S=o.maxOutputBytes??64e3,v=Math.max(1,Math.min(o.timeoutMs??600*1e3,1800*1e3));return await new Promise(A=>{const w=Me(process.execPath,["-e",xt,String(s.dev),String(s.ino),$(e.workspacePath),e.workspaceIdentity.dev,e.workspaceIdentity.ino,g,n.afterHandoff?"1":"0"],{cwd:i,env:o.env,stdio:["pipe","pipe","pipe"]});let j="",R="",p=0,I=0,b=!1,u=!1,k=!1,x=!n.afterHandoff;const m=(N,J)=>{b||(b=!0,clearTimeout(E),o.signal?.removeEventListener("abort",l),A({exitCode:N,...J?{signal:J}:{},timedOut:u,...k?{cancelled:!0}:{},durationMs:Date.now()-a,stdout:j,stderr:R,stdoutBytes:p,stderrBytes:I}))},l=()=>{k=!0,w.kill("SIGTERM")};o.signal?.addEventListener("abort",l,{once:!0});const E=setTimeout(()=>{u=!0,w.kill("SIGTERM")},v);w.stdout.on("data",N=>{p+=N.length,p+I>S?w.kill("SIGTERM"):j+=N.toString("utf8")}),w.stderr.on("data",N=>{I+=N.length,p+I>S?w.kill("SIGTERM"):R+=N.toString("utf8"),!x&&R.includes(`continuous-child-handoff-ready
51
+ `)&&(x=!0,Promise.resolve(n.afterHandoff?.()).then(()=>w.stdin.end()).catch(()=>w.kill("SIGTERM")))}),w.once("error",()=>m(null)),w.once("close",(N,J)=>m(N,J)),n.afterHandoff||w.stdin.end()})}async function P(e,r){return(await z(e,r)).trim()}async function z(e,r){const t=await je("git",r,{cwd:e,encoding:"utf8",maxBuffer:16777216});return String(t.stdout)}async function ee(e,r){try{return await P(e,r)}catch(t){if(q(t,"ENOENT"))return;throw t}}async function ae(e,r){try{return await P(e,r),!0}catch{return!1}}async function _t(e,r,t){return await new Promise(o=>{const n=Me("git",[...r],{cwd:e,stdio:["pipe","ignore","ignore"]});n.once("error",()=>o(!1)),n.once("close",a=>o(a===0)),n.stdin.end(t)})}async function fr(e,r,t){try{const o=await je("git",["show",`${r}:${t}`],{cwd:e,encoding:"buffer",maxBuffer:16777216});return Buffer.from(o.stdout)}catch(o){if(q(o,"ENOENT"))return;throw o}}async function Ce(e){try{return await B(e)}catch(r){if(q(r,"ENOENT"))return;throw r}}async function te(e,r,t,o){const n=se(r);if(!ce(n))throw new Error("continuous-sandbox-write-path-invalid");const a=await Y(e);if(a!==ht(e))throw new Error("continuous-sandbox-write-root-symlink");const c=C(n)==="."?"":C(n),i=await Bt(a,c),d=await Qe(i),s=D(i,$(n));if(await me(s,a,!0),t===void 0){await o?.({boundaryRoot:a,relativePath:n,destinationPath:s}),await Ze(i,a,d),await me(s,a,!0),await kt(i,$(n));return}await o?.({boundaryRoot:a,relativePath:n,destinationPath:s}),await Ze(i,a,d),await me(s,a,!0),await vt(i,$(n),t),await me(s,a,!1)}async function Bt(e,r){let t=e;for(const o of r.split("/").filter(Boolean)){t=D(t,o),await bt(C(t),$(t));const n=await le(t);if(!n.isDirectory()||n.isSymbolicLink()||await Y(t)!==t)throw new Error("continuous-sandbox-write-component-unsafe");Oe(e,t)}return t}async function me(e,r,t){Oe(r,e);try{const o=await le(e);if(o.isSymbolicLink()||!o.isFile())throw new Error("continuous-sandbox-write-destination-unsafe");if(await Y(e)!==e)throw new Error("continuous-sandbox-write-destination-symlink")}catch(o){if(t&&q(o,"ENOENT"))return;throw o}}function Oe(e,r){const t=ut(e,r);if(t===""||t.startsWith("..")||Fe(t))throw new Error("continuous-sandbox-write-containment-invalid")}async function Qe(e){const r=await le(e,{bigint:!0});if(!r.isDirectory()||r.isSymbolicLink())throw new Error("continuous-sandbox-write-parent-unsafe");return{dev:r.dev,ino:r.ino}}async function Pt(e,r,t){try{if(e!==r&&Oe(r,e),await Y(e)!==e)return!1;const o=await Qe(e);return o.dev===t.dev&&o.ino===t.ino}catch{return!1}}async function Ze(e,r,t){if(!await Pt(e,r,t))throw new Error("continuous-sandbox-write-parent-raced")}async function $t(e,r){return await Promise.all(r.map(async t=>{const o=await Ce(D(e,t));return{path:t,...o!==void 0?{content:o}:{}}}))}async function Ne(e,r){const t=r.map(o=>o.path);t.length>0&&await ae(e,["reset","--quiet","HEAD","--",...t]);for(const o of r)await te(e,o.path,o.content)}async function zt(e,r){try{const t=D(e.projectRoot,".neocortex/state.json"),o=T(JSON.parse((await B(t)).toString("utf8"))),n=h(h(o.epics)?.[e.epicId]),a=h(n?.branch_lease),c=Object.freeze({schemaVersion:1,ownerStoryId:e.storyId,sessionId:e.dispatchId,idempotencyKey:e.dispatchId,acquiredAt:r,expiresAt:new Date(Date.parse(r)+600*1e3).toISOString()});let i=!1;return await X(e.projectRoot,d=>{const s=ye(d,e.epicId),g=h(s.branch_lease)??a;if(g&&typeof g.expiresAt=="string"&&g.expiresAt>r&&(g.ownerStoryId!==e.storyId||g.idempotencyKey!==e.dispatchId)){i=!0;return}s.branch_mode="epic",s.execution_branch=e.executionBranch,s.branch_lease=c}),i?f("continuous-epic-checkout-writer-active"):{ok:!0,value:c}}catch{return f("continuous-writer-lease-persist-failed")}}async function Tt(e){await X(e.projectRoot,r=>{const t=ye(r,e.epicId),o=h(t.branch_lease);o?.ownerStoryId===e.storyId&&o.idempotencyKey===e.dispatchId&&(t.branch_lease=null)})}async function Ue(e){try{const r=D(e.lease.projectRoot,".neocortex/state.json"),t=Object.freeze({schemaVersion:1,storyId:e.lease.storyId,epicId:e.lease.epicId,branch:e.lease.executionBranch,baseSha:e.baseSha,headSha:e.headSha,commits:Object.freeze([e.headSha]),idempotencyKey:e.lease.dispatchId,dispatchId:e.lease.dispatchId,bundleId:e.bundle.bundleId,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,claimRevision:e.lease.claimRevision,receiptRefs:Object.freeze([...new Set(e.receiptRefs)]),qaVerdict:"passed",reviewVerdict:"approved",qaReceipt:e.qaReceipt,reviewReceipt:e.reviewReceipt,recordedAt:e.recordedAt}),o=T(JSON.parse((await B(r)).toString("utf8"))),n=h(h(o.stories)?.[e.lease.storyId]);let a="persisted",c,i,d,s,g=!1,S;const v=async(u,k,x)=>{const m=await ee(e.lease.projectRoot,["symbolic-ref","--quiet","--short","HEAD"]),l=await P(e.lease.projectRoot,["rev-parse","HEAD"]);if(m!==e.lease.executionBranch||l!==e.headSha)throw new Error("continuous-checkpoint-head-raced");if(u.graphRevision!==e.lease.graphRevision||u.claimRevision!==e.lease.claimRevision||u.bundleId!==e.bundle.bundleId||u.bundleDigest!==e.bundle.bundleDigest)throw new Error("continuous-checkpoint-graph-raced");const E=x??T(JSON.parse((await B(r)).toString("utf8"))),N=re(E,k??await V(e.lease.projectRoot)),J=h(h(N.epics)?.[e.lease.epicId]),ve=h(h(N.stories)?.[e.lease.storyId]),M=Array.isArray(ve?.depends_on)?ve.depends_on.filter(H=>typeof H=="string"):[],Re=h(N.stories);if(J?.execution_branch!==e.lease.executionBranch||M.some(H=>{const K=h(Re?.[H]);return!K||!["done","completed","merged"].includes(String(K.status))}))throw new Error("continuous-checkpoint-dependency-raced");const he=L(await z(e.lease.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",e.headSha]));if(he.length===0||he.some(H=>!e.lease.authorizedWriteSet.some(K=>Se(K,H))))throw new Error("continuous-checkpoint-write-set-raced");if(!await ke(e.lease.projectRoot,u,e.lease.storyId,e.lease.epicId,e.lease.executionBranch,void 0,e.lease.authorizedWriteSet))throw new Error("continuous-checkpoint-receipt-revalidation-failed")},A=await V(e.lease.projectRoot,{required:!0}),w=h(h(A.epics[e.lease.epicId])?.branch_lease);if(w?.ownerStoryId!==e.lease.storyId||w.idempotencyKey!==e.lease.dispatchId||w.sessionId!==e.lease.dispatchId||typeof w.expiresAt!="string"||Date.parse(w.expiresAt)<=(e.checkpointNow?.("before-mutation")??Date.now()))return f("continuous-checkpoint-writer-lease-lost");if(!await xe(e.physicalLock.path,e.physicalLock.owner))return f("continuous-checkpoint-integration-lock-raced");const j=await B(r),R=G("sha256").update(j).digest("hex");await v(t,A);const p=$e(T(JSON.parse(j.toString("utf8"))),A,e.lease.epicId,e.lease.storyId);if(p.revision!==e.checkpointAuthority.revision||p.epoch!==e.checkpointAuthority.epoch||p.storyStatus!==e.checkpointAuthority.storyStatus)return f("continuous-graph-revision-stale");const I=await X(e.lease.projectRoot,u=>{const k=ye(u,e.lease.epicId),x=h(k.branch_lease);i=x===void 0?void 0:structuredClone(x),d=structuredClone(u),g=u.stories[e.lease.storyId]!==void 0,s=structuredClone(u.stories[e.lease.storyId]??{}),S=structuredClone(k.branch_lease);const m=mt(u,e.lease.storyId),l=h(m.checkpoint)??h(n?.checkpoint);if(l?.idempotencyKey===e.lease.dispatchId){l.baseSha!==e.baseSha||l.headSha!==e.headSha||l.bundleId!==e.bundle.bundleId||l.bundleDigest!==e.bundle.bundleDigest||l.graphRevision!==e.lease.graphRevision||l.claimRevision!==e.lease.claimRevision?a="conflict":(a="reused",c=l,k.branch_lease=null);return}if(x?.ownerStoryId!==e.lease.storyId||x.idempotencyKey!==e.lease.dispatchId||x.sessionId!==e.lease.dispatchId){a="lease-lost";return}m.checkpoint=t,m.status="done",m.last_step=we;const E=Array.isArray(m.steps_completed)?m.steps_completed.filter(N=>typeof N=="string"):[];m.steps_completed=[...new Set([...E,Ve,we])],k.branch_lease=null},{expectedRevision:A.revision,preCommit:async u=>{if(i?.ownerStoryId!==e.lease.storyId||i.idempotencyKey!==e.lease.dispatchId||i.sessionId!==e.lease.dispatchId||typeof i.expiresAt!="string"||Date.parse(i.expiresAt)<=(e.checkpointNow?.("pre-commit")??Date.now()))throw new Error("continuous-checkpoint-writer-lease-lost");if(await e.insideCheckpointPreCommit?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),!await xe(e.physicalLock.path,e.physicalLock.owner))throw new Error("continuous-checkpoint-integration-lock-raced");await v(c??t,u);const k=await B(r);if(G("sha256").update(k).digest("hex")!==R)throw new Error("continuous-graph-revision-stale");if(!d)throw new Error("continuous-checkpoint-authority-missing");const x=T(JSON.parse(k.toString("utf8"))),m=$e(x,d,e.lease.epicId,e.lease.storyId);if(m.revision!==e.checkpointAuthority.revision||m.epoch!==e.checkpointAuthority.epoch||m.storyStatus!==e.checkpointAuthority.storyStatus)throw new Error("continuous-graph-revision-stale");if(a==="persisted"&&!ze(x,u,e.lease,t))throw new Error("continuous-checkpoint-projection-raced")}}),b=a;if(b==="conflict")return f("continuous-checkpoint-idempotency-conflict");if(b==="lease-lost")return f("continuous-checkpoint-writer-lease-lost");if(b==="reused"&&c)try{return await v(c),{ok:!0,value:c}}catch{return f("continuous-checkpoint-reused-evidence-invalid")}try{await e.afterCheckpointPersist?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha});const u=await V(e.lease.projectRoot,{required:!0});if(u.revision!==I.document.revision)throw new Error("continuous-checkpoint-post-persist-runtime-raced");await v(t,u);const k=await B(r);if(G("sha256").update(k).digest("hex")!==R)throw new Error("continuous-checkpoint-post-persist-authority-raced");const x=T(JSON.parse(k.toString("utf8")));if(!ze(x,u,e.lease,t))throw new Error("continuous-checkpoint-post-persist-projection-raced")}catch{const u=await B(r).catch(()=>{}),k=u===void 0||G("sha256").update(u).digest("hex")!==R;return await X(e.lease.projectRoot,x=>{const m=h(x.epics[e.lease.epicId]),l=h(x.stories[e.lease.storyId]),E=u===void 0?void 0:T(JSON.parse(u.toString("utf8")));if(!m||!l||!E||!ze(E,x,e.lease,t))throw new Error("continuous-checkpoint-cleanup-cas-conflict");if(k){g?Mt(l,s??{}):delete x.stories[e.lease.storyId],S===void 0?delete m.branch_lease:m.branch_lease=structuredClone(S);return}l.checkpoint=null,l.status="blocked",m.branch_lease=null},{expectedRevision:I.document.revision}).catch(()=>{}),f("continuous-checkpoint-post-persist-raced")}return{ok:!0,value:t}}catch(r){const t=r instanceof Error&&/^continuous-/.test(r.message)?r.message:"continuous-checkpoint-persist-failed";return f(t)}}async function Ye(e){try{if(await P(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return f("continuous-story-evidence-head-raced");const r=await B(D(e.lease.projectRoot,"config","release-gates.v2.json"),"utf8"),t=JSON.parse(r),o=Array.isArray(t.requiredCompleteClasses)?t.requiredCompleteClasses.filter(b=>typeof b=="string"&&/^[a-z0-9-]+$/.test(b)):[];if(t.contract!=="P205-CI-02"||o.length===0)return f("continuous-story-qa-manifest-invalid");const n=String((await je(process.execPath,["scripts/test-root.mjs","--gate","complete"],{cwd:e.lease.projectRoot,encoding:"utf8",maxBuffer:32*1024*1024})).stdout);if(await e.qaRunner?.({projectRoot:e.lease.projectRoot,storyId:e.lease.storyId,headSha:e.headSha}),await P(e.lease.projectRoot,["rev-parse","HEAD"])!==e.headSha)return f("continuous-story-qa-head-raced");const a=Xe(e.nowIso),c=await P(e.lease.projectRoot,["rev-list","--count",`${e.baseSha}..${e.headSha}`]),i=await z(e.lease.projectRoot,["show","--no-patch","--format=%H%n%P%n%B",e.headSha]),d=L(await z(e.lease.projectRoot,["diff","--name-only","-z",`${e.baseSha}..${e.headSha}`])),s=yt({storyId:e.lease.storyId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,commitBody:i,changedPaths:d}),g=G("sha256").update(r).digest("hex"),S=G("sha256").update(n).digest("hex"),v=wt({gitEvidenceDigest:s,headSha:e.headSha,graphRevision:e.lease.graphRevision,manifestDigest:g,gateIds:o,resultDigest:S}),A=`story-qa:${v}`,w=Object.freeze({schemaVersion:1,kind:"story_qa_evidence",producer:"local-yolo-tdd",evidenceVersion:"p205-execution-v2",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,contract:"P205-CI-02",command:St,manifestDigest:g,gateIds:Object.freeze(o),resultDigest:S,sourceEvidenceDigest:v,verdict:"passed",checkedAt:a,receiptRef:A}),j=[`Neocortex-Story: ${e.lease.storyId}`,`Neocortex-Epic: ${e.lease.epicId}`,`Neocortex-Bundle-Digest: ${e.bundle.bundleDigest}`,`Neocortex-Graph-Revision: ${e.lease.graphRevision}`];if(c!=="1"||!j.every(b=>i.includes(b))||d.length===0||d.some(b=>!e.lease.authorizedWriteSet.some(u=>Se(u,b))))return f("continuous-story-review-evidence-rejected");const R=G("sha256").update(["root-commit-range-review-v1",e.lease.storyId,e.baseSha,e.headSha,e.bundle.bundleDigest,e.lease.graphRevision,A,G("sha256").update(i).digest("hex"),[...d].sort().join(",")].join("\0")).digest("hex"),p=`story-review:${R}`,I=Object.freeze({schemaVersion:1,kind:"story_review_evidence",producer:"root-commit-range-review",storyId:e.lease.storyId,epicId:e.lease.epicId,baseSha:e.baseSha,headSha:e.headSha,bundleDigest:e.bundle.bundleDigest,graphRevision:e.lease.graphRevision,sourceEvidenceDigest:R,qaReceiptRef:A,verdict:"approved",reviewedAt:a,receiptRef:p});return{ok:!0,value:{qaReceipt:w,reviewReceipt:I}}}catch{return f("continuous-story-evidence-production-failed")}}function Xe(e){return Number.isFinite(Date.parse(e))?new Date(Date.parse(e)).toISOString():new Date().toISOString()}function Gt(e,r,t){if(r!==void 0)try{const o=e===void 0?{}:T(JSON.parse(e.toString("utf8"))),n=T(JSON.parse(r.toString("utf8"))),a=structuredClone(o),c=h(h(o.stories)?.[t]),i=h(h(n.stories)?.[t]),d=Lt(a,"stories"),s=structuredClone(c??{});for(const g of["status","last_step","steps_completed","last_updated","blocked_reason","blocked_at","implementation_evidence","validation_evidence","qa_gate"])i&&Object.prototype.hasOwnProperty.call(i,g)&&(s[g]=structuredClone(i[g]));return d[t]=s,Buffer.from(`${JSON.stringify(a,null,2)}
52
+ `)}catch{return Buffer.from("{invalid-child-state")}}function Lt(e,r){const t=h(e[r]);if(t)return t;const o={};return e[r]=o,o}function T(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("record expected");return e}function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Wt(e,r,t){return Pe(t,e)||Pe(r,t)?{ok:!0,value:r}:Pe(r,e)?{ok:!0,value:t}:f("continuous-context-merge-conflict")}function qt(e,r,t){try{const o=et(_e(e),_e(r),_e(t));return o.ok?{ok:!0,value:o.value===void 0?void 0:Buffer.from(`${JSON.stringify(o.value,null,2)}
53
+ `)}:o}catch{return f("continuous-state-merge-invalid")}}function _e(e){return e===void 0?void 0:JSON.parse(e.toString("utf8"))}function et(e,r,t){if(ge(t,e)||ge(r,t))return{ok:!0,value:r};if(ge(r,e))return{ok:!0,value:t};if(Be(e)&&Be(r)&&Be(t)){const o={};for(const n of[...new Set([...Object.keys(e),...Object.keys(r),...Object.keys(t)])].sort()){const a=et(e[n],r[n],t[n]);if(!a.ok)return a;a.value!==void 0&&(o[n]=a.value)}return{ok:!0,value:o}}if(Array.isArray(e)&&Array.isArray(r)&&Array.isArray(t)&&tt(e,r)&&tt(e,t)){const o=[...e,...r.slice(e.length),...t.slice(e.length)],n=new Set;return{ok:!0,value:o.filter(a=>{const c=JSON.stringify(a);return n.has(c)?!1:(n.add(c),!0)})}}return f("continuous-state-merge-conflict")}function Be(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function tt(e,r){return e.length<=r.length&&e.every((t,o)=>ge(t,r[o]))}function ge(e,r){return JSON.stringify(e)===JSON.stringify(r)}function Pe(e,r){return e===void 0||r===void 0?e===r:e.equals(r)}function L(e){return e.split("\0").filter(Boolean)}function ce(e){const r=se(e);return r.length>0&&r.length<=1024&&!Fe(r)&&!/^[A-Za-z]:\//.test(r)&&!r.split("/").includes("..")&&!r.includes("\0")&&!r.startsWith("/")}function se(e){return e.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/{2,}/g,"/")}function Ht(e){const r=e.map(se).filter(ce);return[...new Set(r)].sort()}function Se(e,r){const t=se(e),o=se(r);return t===o||t.endsWith("/")&&o.startsWith(t)}function Jt(e){return e.length>0&&e.length<=240&&!e.startsWith("-")&&!e.startsWith("/")&&!e.endsWith("/")&&!e.endsWith(".lock")&&!e.includes("..")&&!e.includes("\\")&&!e.includes("@{")&&!e.includes("//")&&/^[A-Za-z0-9._/-]+$/.test(e)}function rt(e,r){return e.length===r.length&&e.every((t,o)=>t===r[o])}async function Ie(e,r,t,o){const n=T(JSON.parse(await B(D(e,".neocortex/state.json"),"utf8")));return $e(n,o??await V(e),r,t)}function $e(e,r,t,o){const n=re(e,r),a=h(n.epics),c=h(n.stories),i=h(a?.[t])??{},d=(Array.isArray(i.stories)?i.stories:Array.isArray(i.story_ids)?i.story_ids:[]).filter(v=>typeof v=="string"),s=d.length>0?d:Object.entries(c??{}).filter(([v,A])=>h(A)?.epic_id===t||v.startsWith(`${t}.`)).map(([v])=>v).sort(),g=["status","depends_on","files_to_modify","contracts","contract_refs","shared_surfaces","steps_completed","last_step","branch_name","physicalMergeStatus","merged","checkpoint","planning","attempts","retry_count","rollback_receipt","cancelled_at"],S=Object.fromEntries(s.map(v=>{const A=h(c?.[v])??{};return[v,Object.fromEntries(g.filter(w=>Object.prototype.hasOwnProperty.call(A,w)).map(w=>[w,A[w]]))]}));return{revision:Te({epicId:t,epic:{stories:s,status:i.status??null,branch_mode:i.branch_mode??null,execution_branch:i.execution_branch??null,graph_revision:i.graph_revision??null,depends_on:i.depends_on??null,planning:i.planning??null,execution_plan:i.execution_plan??null,waves:i.waves??null,current_wave:i.current_wave??null,replan:i.replan??null,replan_revision:i.replan_revision??null,dependency_graph:i.dependency_graph??null,scheduler:i.scheduler??null,attempts:i.attempts??null,retry_count:i.retry_count??null},stories:S}),epoch:typeof i.graph_revision=="string"?i.graph_revision:null,storyStatus:typeof h(c?.[o])?.status=="string"?String(h(c?.[o])?.status):null}}function ze(e,r,t,o){const n=re(e,r),a=h(h(n.epics)?.[t.epicId]),c=h(h(n.stories)?.[t.storyId]),i=Array.isArray(c?.steps_completed)?c.steps_completed.filter(d=>typeof d=="string"):[];return!!(a&&c&&a.branch_lease===null&&c.status==="done"&&c.last_step===we&&i.includes(Ve)&&i.includes(we)&&de(c.checkpoint)===de(o))}function Mt(e,r){for(const t of Object.keys(e))delete e[t];Object.assign(e,structuredClone(r))}async function Kt(e,r){return(await Ie(e,r,"")).revision}function Te(e){return G("sha256").update(de(e)).digest("hex")}function de(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(de).join(",")}]`:`{${Object.entries(e).sort(([r],[t])=>r.localeCompare(t)).map(([r,t])=>`${JSON.stringify(r)}:${de(t)}`).join(",")}}`}function Ft(e,r){const t=(e??[]).filter(o=>/^[A-Za-z0-9._/:@#-]{1,200}$/.test(o)&&!o.includes(".."));return Object.freeze([...new Set(t.length>0?t:[`dispatch:${r}`])].sort())}function Vt(e){return e.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,80)}function f(e){return{ok:!1,reasonCode:e}}function q(e,r){return e instanceof Error&&"code"in e&&e.code===r}async function ue(e,r){try{await W(e,r);const t=D(e,"owner.json");await F(t,e);const o=JSON.parse(await B(t,"utf8"));if(!Number.isSafeInteger(o.pid)||Number(o.pid)<=0||typeof o.createdAt!="string"||!Number.isFinite(Date.parse(o.createdAt))||typeof o.nonce!="string"||!/^[a-f0-9]{32}$/.test(o.nonce))throw new Error("continuous-sandbox-lease-owner-invalid");return{pid:Number(o.pid),createdAt:o.createdAt,nonce:o.nonce}}catch(t){if(q(t,"ENOENT"))return;throw t}}function ot(e,r){return e?.pid===r.pid&&e.createdAt===r.createdAt&&e.nonce===r.nonce}function Qt(e){try{return process.kill(e,0),!0}catch(r){return q(r,"EPERM")}}async function Ge(e,r){try{await W(e,r);const t=D(e,".git");await W(t,e);const o=D(t,"neocortex-sandbox.json");await F(o,t);const n=JSON.parse(await B(o,"utf8"));if(n.schemaVersion!==1||typeof n.workspaceOwnerNonce!="string"||!/^[a-f0-9]{32}$/.test(n.workspaceOwnerNonce)||!/^[a-f0-9]{64}$/.test(n.graphAuthorityRevision)||!(n.graphAuthorityEpoch===null||/^[a-f0-9]{64}$/.test(n.graphAuthorityEpoch))||!(n.graphAuthorityStoryStatus===null||typeof n.graphAuthorityStoryStatus=="string"&&n.graphAuthorityStoryStatus.length<=80)||typeof n.workspaceIdentity?.dev!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.dev)||typeof n.workspaceIdentity?.ino!="string"||!/^[0-9]+$/.test(n.workspaceIdentity.ino))throw new Error("continuous-sandbox-metadata-invalid");return n}catch(t){if(q(t,"ENOENT"))return;throw t}}async function Zt(e,r,t,o){await W(e,r);const n=D(e,".git");await W(n,e);const a=D(n,"neocortex-sandbox.json");await te(e,".git/neocortex-sandbox.json",Buffer.from(`${JSON.stringify(t,null,2)}
54
+ `),o),await F(a,n)}async function Ut(e,r){try{await F(e,r);const t=JSON.parse(await B(e,"utf8"));return typeof t.childHeadSha=="string"&&typeof t.rootHeadSha=="string"&&/^[a-f0-9]{40,64}$/.test(t.childHeadSha)&&/^[a-f0-9]{40,64}$/.test(t.rootHeadSha)&&t.bundle?.schemaVersion===1&&t.checkpoint?.schemaVersion===1?t:void 0}catch(t){if(q(t,"ENOENT"))return;throw t}}async function Yt(e,r){try{const t=T(JSON.parse(await B(D(e.projectRoot,".neocortex/state.json"),"utf8"))),o=re(t,await V(e.projectRoot)),n=h(h(o.stories)?.[e.storyId]),a=h(n?.checkpoint);return a?.idempotencyKey===r.idempotencyKey&&a.headSha===r.headSha&&a.bundleDigest===r.bundleDigest&&h(h(o.epics)?.[e.epicId])?.branch_lease===null&&await ke(e.projectRoot,a,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)}catch{return!1}}async function Xt(e,r,t){try{const o=T(JSON.parse(await B(D(e.projectRoot,".neocortex/state.json"),"utf8"))),n=re(o,await V(e.projectRoot)),a=h(h(n.stories)?.[e.storyId]),c=h(a?.checkpoint);return c?.schemaVersion!==1||c.storyId!==e.storyId||c.epicId!==e.epicId||c.branch!==e.executionBranch||c.baseSha!==t.baseSha||c.headSha!==t.headSha||c.idempotencyKey!==e.dispatchId||c.dispatchId!==e.dispatchId||c.bundleId!==r.bundleId||c.bundleDigest!==r.bundleDigest||c.graphRevision!==e.graphRevision||c.claimRevision!==e.claimRevision||h(h(n.epics)?.[e.epicId])?.branch_lease!==null||!await ke(e.projectRoot,c,e.storyId,e.epicId,e.executionBranch,void 0,e.authorizedWriteSet)?void 0:c}catch{return}}async function er(e,r){const t=(await ee(e.projectRoot,["log","--format=%H","--fixed-strings",`--grep=Neocortex-Dispatch: ${e.dispatchId}`]))?.split(`
55
55
  `).filter(S=>/^[a-f0-9]{40,64}$/.test(S))??[];if(t.length!==1)return;const o=t[0];if(!await ae(e.projectRoot,["merge-base","--is-ancestor",o,"HEAD"]))return;const n=await P(e.projectRoot,["show","-s","--format=%B",o]),a=new Set(n.split(`
56
- `).map(S=>S.trim()));for(const S of[`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${e.epicId}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Prepared-Base: ${e.baseSha}`,`Neocortex-Dispatch: ${e.dispatchId}`,`Neocortex-Bundle: ${r.bundleId}`,`Neocortex-Bundle-Digest: ${r.bundleDigest}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Claim-Revision: ${e.claimRevision}`])if(!a.has(S))return;const c=Ge(n,"Neocortex-Checkpoint-Authority"),i=Ge(n,"Neocortex-Checkpoint-Epoch"),d=Ge(n,"Neocortex-Checkpoint-Story-Status");if(!c||!/^[a-f0-9]{64}$/.test(c)||!i||!(i==="null"||/^[a-f0-9]{64}$/.test(i))||!d||d.length>80)return;const s=await ee(e.projectRoot,["rev-parse",`${o}^`]);if(!s||!/^[a-f0-9]{40,64}$/.test(s))return;const g=L(await z(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!(g.length===0||g.some(S=>!r.authorizedWriteSet.some(v=>ge(v,S)))))return{baseSha:s,headSha:o,checkpointAuthority:{revision:c,epoch:i==="null"?null:i,storyStatus:d==="null"?null:d}}}function Ge(e,r){const t=`${r}: `,o=e.split(`
57
- `).map(n=>n.trim()).filter(n=>n.startsWith(t));return o.length===1?o[0].slice(t.length):void 0}async function Le(e,r,t,o,n,a){const c=O(e);await q(c,O(c));try{await V(e,c)}catch(i){if(!W(i,"ENOENT"))throw i}await te(c,$(e),Buffer.from(`${JSON.stringify({childHeadSha:r,rootHeadSha:t,bundle:o,checkpoint:n})}
58
- `),a),await V(e,c)}export{cr as createAnchoredContinuousStoryCommandRunner,sr as createBranchlessContinuousStoryWorkspaceManager};
56
+ `).map(S=>S.trim()));for(const S of[`Neocortex-Story: ${e.storyId}`,`Neocortex-Epic: ${e.epicId}`,`Neocortex-Execution-Branch: ${e.executionBranch}`,`Neocortex-Prepared-Base: ${e.baseSha}`,`Neocortex-Dispatch: ${e.dispatchId}`,`Neocortex-Bundle: ${r.bundleId}`,`Neocortex-Bundle-Digest: ${r.bundleDigest}`,`Neocortex-Graph-Revision: ${e.graphRevision}`,`Neocortex-Claim-Revision: ${e.claimRevision}`])if(!a.has(S))return;const c=Le(n,"Neocortex-Checkpoint-Authority"),i=Le(n,"Neocortex-Checkpoint-Epoch"),d=Le(n,"Neocortex-Checkpoint-Story-Status");if(!c||!/^[a-f0-9]{64}$/.test(c)||!i||!(i==="null"||/^[a-f0-9]{64}$/.test(i))||!d||d.length>80)return;const s=await ee(e.projectRoot,["rev-parse",`${o}^`]);if(!s||!/^[a-f0-9]{40,64}$/.test(s))return;const g=L(await z(e.projectRoot,["diff-tree","--no-commit-id","--name-only","-r","-z",o]));if(!(g.length===0||g.some(S=>!r.authorizedWriteSet.some(v=>Se(v,S)))))return{baseSha:s,headSha:o,checkpointAuthority:{revision:c,epoch:i==="null"?null:i,storyStatus:d==="null"?null:d}}}function Le(e,r){const t=`${r}: `,o=e.split(`
57
+ `).map(n=>n.trim()).filter(n=>n.startsWith(t));return o.length===1?o[0].slice(t.length):void 0}async function We(e,r,t,o,n,a){const c=C(e);await W(c,C(c));try{await F(e,c)}catch(i){if(!q(i,"ENOENT"))throw i}await te(c,$(e),Buffer.from(`${JSON.stringify({childHeadSha:r,rootHeadSha:t,bundle:o,checkpoint:n})}
58
+ `),a),await F(e,c)}export{ur as createAnchoredContinuousStoryCommandRunner,hr as createBranchlessContinuousStoryWorkspaceManager};
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.60.24 | OrNexus Team
1
+ # 🧠 Neocortex v4.60.26 | 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.60.24 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.60.26 | 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.60.24'
7
+ version: '4.60.26'
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.60.24 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.60.26 | 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.60.24
111
+ │ ### ######## v4.60.26
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.60.24'
7
+ version: '4.60.26'
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.60.24 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.60.26 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  permissionMode: bypassPermissions
@@ -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.60.24
107
+ │ ### ######## v4.60.26
108
108
  │ ######### ##### │
109
109
  │ ## ############## Development Orchestrator │
110
110
  │ ## ### ###### ## OrNexus Team │
@@ -28,7 +28,7 @@ Codex built-in commands or actions.
28
28
 
29
29
  <!-- END: Plugin Conflict Prevention -->
30
30
 
31
- # Neocortex v4.60.24 | OrNexus Team
31
+ # Neocortex v4.60.26 | OrNexus Team
32
32
 
33
33
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
34
34
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.60.24 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.60.26 | OrNexus Team"
4
4
  model: inherit
5
5
  readonly: false
6
6
  is_background: false
@@ -64,7 +64,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
64
64
  ┌────────────────────────────────────────────────────────────┐
65
65
  │ │
66
66
  │ ####### N E O C O R T E X │
67
- │ ### ######## v4.60.24
67
+ │ ### ######## v4.60.26
68
68
  │ ######### ##### │
69
69
  │ ## ############## Development Orchestrator │
70
70
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex v4.60.24 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.60.26 | 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.60.24
65
+ │ ### ######## v4.60.26
66
66
  │ ######### ##### │
67
67
  │ ## ############## Development Orchestrator │
68
68
  │ ## ### ###### ## OrNexus Team │
@@ -58,7 +58,7 @@ explicit server opt-in rather than a local assumption.
58
58
  ┌────────────────────────────────────────────────────────────┐
59
59
  │ │
60
60
  │ ####### N E O C O R T E X │
61
- │ ### ######## v4.60.24
61
+ │ ### ######## v4.60.26
62
62
  │ ######### ##### │
63
63
  │ ## ############## Development Orchestrator │
64
64
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: "neocortex"
3
- description: "Neocortex v4.60.24 | OrNexus Team"
3
+ description: "Neocortex v4.60.26 | OrNexus Team"
4
4
  tools:
5
5
  # Read / Edit (built-in tool sets)
6
6
  - read
@@ -68,7 +68,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
68
68
  ┌────────────────────────────────────────────────────────────┐
69
69
  │ │
70
70
  │ ####### N E O C O R T E X │
71
- │ ### ######## v4.60.24
71
+ │ ### ######## v4.60.26
72
72
  │ ######### ##### │
73
73
  │ ## ############## Development Orchestrator │
74
74
  │ ## ### ###### ## OrNexus Team │