@ornexus/neocortex 4.66.25 → 4.66.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.d.ts +25 -3
- package/packages/client/dist/commands/invoke.js +96 -96
- package/packages/client/dist/continuity/sqlite-store.d.ts +3 -1
- package/packages/client/dist/continuity/sqlite-store.js +26 -20
- package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +10 -0
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/git-lifecycle-store.d.ts +16 -0
- package/packages/client/dist/git/git-lifecycle-store.js +9 -9
- package/packages/client/dist/git/published-story-reconciliation.d.ts +7 -3
- package/packages/client/dist/git/published-story-reconciliation.js +5 -5
- package/packages/client/dist/git/secure-filesystem-boundary.d.ts +1 -1
- package/packages/client/dist/git/secure-filesystem-boundary.js +5 -5
- package/packages/client/dist/git/story-worktree-integration.d.ts +2 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-worktree-manager.d.ts +3 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/license/license-client.js +1 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +17 -0
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +3 -2
- package/packages/client/dist/runner/headless/run-yolo.d.ts +4 -0
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +79 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
- package/postinstall.js +6 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`).filter(Boolean),
|
|
3
|
-
`);if(
|
|
4
|
-
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!
|
|
5
|
-
`).filter(Boolean);if(
|
|
1
|
+
import{execFile as ye}from"node:child_process";import{createHash as we}from"node:crypto";import{realpath as W}from"node:fs/promises";import{isDeepStrictEqual as ve,promisify as me}from"node:util";import{parseYoloopInvocation as ge,parseYoloStoryInvocation as Se}from"../yoloop/target-normalization.js";import{resolveEpicExecutionCheckout as Y}from"./epic-execution-checkout.js";import{recoverLegacyDirectYoloStoryCheckpoint as xe,recoverReconciledDirectYoloStoryCheckpoint as be,resolveDirectYoloIntegrationAuthority as ke,verifyDirectYoloIntegrationCommit as Ie}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as _}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as Ae,isStoryWorktreeEvidenceReceiptRecord as Z,mutateGitLifecycleRuntime as Be,publishedStoryReconciliationId as G,readGitLifecycleRuntime as H,readStoryWorktreeEvidence as P}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as te}from"./governance-runtime-store.js";import{parseNeocortexTrailers as F,trailerValue as D}from"./neocortex-trailers.js";import{StoryWorktreeManager as re}from"./story-worktree-manager.js";const He=me(ye),C=/^[a-f0-9]{64}$/,O=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ie=16;function R(e){return we("sha256").update(e).digest("hex")}function g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ne(e,t){let n;try{n=g(JSON.parse(e))}catch{return}if(!(n?.schemaVersion!==2||n.storyId!==t||n.publicSafe!==!0||n.status!=="qa-passed"||n.safeToContinueYoloop!==!0||!Array.isArray(n.blockingChecks)||n.blockingChecks.length!==0))return R(e)}function oe(e){const t=ge(e)?.remainder;return t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase()}function ae(e){const t=Se(e)?.remainder,n=t?.match(/^@?(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+)\.story\.md(?:[ \t]+(story-worktree-phase-[12]))?$/)??t?.match(/^@?([A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z0-9_-]+)+)$/);return n?{storyId:n[1],phase:!!n[2]}:void 0}async function Ne(e,t){const n=oe(t);if(!n)return[];const r=await V(e,n,!0),o=await ue(e,n);return[...new Map([...r,...o].map(c=>[c.receiptId,c])).values()]}async function se(e,t,n,r,o){const c=await H(e,{required:!0});if(c.epics[t]?.execution_branch!==r.executionBranch)return;const u=P(c,t)?.receipts??[],h=u.flatMap(w=>w.kind==="published-story-reconciliation"&&Z(w)?[w]:[]),i=[...n,...h].flatMap(w=>{const{receiptId:I,syncBaseSha:x,syncIntegrationHeadSha:S,...N}=w,b=x&&S?{...N,syncBaseSha:x,syncIntegrationHeadSha:S}:N,A={...N,receiptId:G(N)};return I!==G(b)||!Z(A)||A.storyId!==r.storyId||A.commitSha!==r.headSha||A.executionBranch!==r.executionBranch?[]:[A]}),l=[...new Map(i.map(w=>[w.receiptId,w])).values()];if(l.length!==1||!C.test(l[0].historicalGraphRevision))return;const d=l[0],s=u.filter(w=>w.kind==="phase-one-receipt"&&w.receiptId===d.phaseOneReceiptId&&w.storyId===r.storyId&&w.graphRevision===d.graphRevision);if(s.length!==1)return;const y=s[0],v=(await o("rev-parse","HEAD")).trim(),a=async(w,I)=>{try{return await o("merge-base","--is-ancestor",w,I),!0}catch{return!1}};if(!await a(d.executionHeadSha,v)||!await a(r.headSha,v))return;const p=await _(o,d.originBranch);if(!p)return;try{await o("cat-file","-e",`${p}^{commit}`)}catch{await o("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",p)}if(!await a(d.originHeadSha,p)||!await a(r.headSha,p))return;const m=F(await o("show","-s","--format=%B",r.headSha),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Bundle-Digest","Neocortex-Graph-Revision"]);if(!m.ok||D(m.values,"Neocortex-Story")!==r.storyId||D(m.values,"Neocortex-Epic")!==t||D(m.values,"Neocortex-Execution-Branch")!==r.executionBranch||D(m.values,"Neocortex-Bundle-Digest")!==d.bundleDigest||D(m.values,"Neocortex-Graph-Revision")!==d.historicalGraphRevision)return;const k=String(y.specRef),E=`docs/stories/${r.storyId}.story.md`;if(!(R(await o("show",`${r.headSha}:${k}`))!==y.specDigest||R(await o("show",`${v}:${k}`))!==y.specDigest||await o("show",`${r.headSha}:${E}`)!==await o("show",`${v}:${E}`)||ne(await o("show",`${r.headSha}:.neocortex/stories/${r.storyId}/qa-gate-result.json`),r.storyId)!==d.historicalQaDigest))return{expectedGraphRevision:d.historicalGraphRevision}}async function $e(e,t,n,r={}){const o=oe(t);return o?ce(e,o,n,void 0,r):void 0}async function ce(e,t,n,r,o={}){const c=L(e);let u;try{const a=(await c("symbolic-ref","--quiet","--short","HEAD")).trim(),p=await H(e,{required:!0}),m=p.epics[t];if(m?.branch_mode!=="epic"||m.execution_branch!==a||await Y(e,t,p)!==await W(e))return;const k=(await c("log","--first-parent","--max-count=16","--format=%H","--fixed-strings",`--grep=Neocortex-Epic: ${t}`,"HEAD")).trim().split(`
|
|
2
|
+
`).filter(Boolean),E=te(e);if(!E.ok||!E.value)return;const w=g(g(JSON.parse(E.value.toString("utf8")))?.stories),I=[];for(const x of k){if(!O.test(x))continue;const[S,...N]=(await c("show","-s","--format=%P%n%B",x)).split(`
|
|
3
|
+
`);if(!S||!O.test(S))continue;const b=F(N.join(`
|
|
4
|
+
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!b.ok)continue;const A=q=>D(b.values,q),B=A("Neocortex-Story");!B||r&&B!==r||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(B)||A("Neocortex-Epic")!==t||A("Neocortex-Execution-Branch")!==a||A("Neocortex-Prepared-Base")!==S||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(q=>C.test(A(q)??""))||p.stories[B]?.checkpoint||g(w?.[B])?.epic_id!==t||I.push({storyId:B,headSha:x,executionBranch:a})}if(I.length!==1)return;u=I[0]}catch{return}const{storyId:h,headSha:i,executionBranch:l}=u;try{const a=await _(c,l);if(!a)return;try{await c("merge-base","--is-ancestor",i,a)}catch{return}}catch{return{status:"pending",storyId:h,headSha:i,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}let d;try{d=await se(e,t,n,u,c)}catch{d=void 0}let s;const y={projectRoot:e,storyId:h,commitSha:i,captureTransientAuthority:a=>{s=a}},v=d?await be(y,d.expectedGraphRevision):await xe(y);if(v.ok&&s)return o.captureTransientAuthority?.(h,s),{status:"recovered",storyId:h,headSha:i};if(v.ok)return{status:"pending",storyId:h,headSha:i,reasonCode:"direct-yolo-recovery-authority-missing"};if(v.reasonCode==="direct-yolo-checkpoint-conflict"){const a=await H(e,{required:!0});if(g(a.stories[h]?.checkpoint)?.headSha===i)return}return{status:"pending",storyId:h,headSha:i,reasonCode:v.reasonCode}}function L(e){return async(...t)=>(await He("git",[...t],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Q(e,t,n,r){try{await r("diff","--quiet","HEAD","--",".neocortex/state.json");return}catch{}const o=te(e);if(!o.ok||!o.value)throw new Error("published-story-governance-unavailable");const c=g(JSON.parse(await r("show","HEAD:.neocortex/state.json"))),u=g(JSON.parse(o.value.toString("utf8")));if(!c||!u)throw new Error("published-story-governance-invalid");const h=i=>{const l=g(i.epics),d=g(i.stories),s=g(i.inlineYolo);if(!l?.[t]||!d?.[n])throw new Error("published-story-governance-target-missing");return{root:Object.fromEntries(Object.entries(i).filter(([y])=>!["epics","stories","inlineYolo","last_updated"].includes(y))),epic:l[t],stories:Object.fromEntries(Object.entries(d).filter(([y,v])=>y.startsWith(`${t}.`)||g(v)?.epic_id===t)),inline:Object.fromEntries(Object.entries(s??{}).filter(([y,v])=>y===t||y.startsWith(`${t}.`)||g(v)?.epicId===t))}};if(!ve(h(c),h(u)))throw new Error("published-story-governance-target-dirty")}async function Me(e,t){return ae(t)?.phase!==!0?[]:(await De(e,t)).reconciliations}async function De(e,t,n={}){const r=ae(t);if(!r){const c=await Ne(e,t),u=await $e(e,t,c,n);return{reconciliations:c,checkpoint:u}}const o=r.storyId.split(".")[0];if(!r.phase){const c=await V(e,o,!0),u=await ce(e,o,c,r.storyId,n);return{reconciliations:c,checkpoint:u}}try{const c=await H(e,{required:!0}),u=await Y(e,o,c),h=await W(e),i=Object.values(c.storyWorktrees?.entries??{}).filter(l=>l.storyId===r.storyId&&l.state==="active"&&l.worktreePath===h);return{reconciliations:u&&i.length===1?await Ee(u,o):[]}}catch{return{reconciliations:[]}}}async function Ee(e,t){const n=await V(e,t,!1),r=await ue(e,t);return[...new Map([...n,...r].map(o=>[o.receiptId,o])).values()]}async function ue(e,t){const n=L(e),r=[];try{const o=(await n("symbolic-ref","--quiet","--short","HEAD")).trim(),c=(await n("rev-parse","--verify","HEAD^{commit}")).trim(),u=await H(e,{required:!0});if(u.epics[t]?.execution_branch!==o||await Y(e,t,u)!==await W(e))return[];const h=(P(u,t)?.receipts??[]).flatMap(i=>i.kind==="published-story-reconciliation"&&Z(i)?[i]:[]);if(h.length>ie)return[];for(const i of h)try{const l=g(u.stories[i.storyId]?.checkpoint);if(!l||i.epicId!==t||i.executionBranch!==o||l.headSha!==i.commitSha||l.branch!==o||l.graphRevision!==i.historicalGraphRevision)continue;const d=await _(n,i.originBranch);if(!d||(await se(e,t,[i],{storyId:i.storyId,headSha:i.commitSha,executionBranch:o},n))?.expectedGraphRevision!==i.historicalGraphRevision)continue;const y=(P(u,t)?.receipts??[]).find(k=>k.kind==="phase-one-receipt"&&k.receiptId===i.phaseOneReceiptId&&k.storyId===i.storyId&&k.graphRevision===i.graphRevision);if(!y)continue;const v=String(y.specRef),a=`docs/stories/${i.storyId}.story.md`;await Q(e,t,i.storyId,n),await n("diff","--quiet","HEAD","--",v,a);const p=await H(e,{required:!0}),m=g(p.stories[i.storyId]?.checkpoint);if(p.revision!==u.revision||(await n("symbolic-ref","--quiet","--short","HEAD")).trim()!==o||(await n("rev-parse","--verify","HEAD^{commit}")).trim()!==c||(await n("rev-parse","--verify",`refs/heads/${o}^{commit}`)).trim()!==c||await _(n,i.originBranch)!==d||m?.headSha!==i.commitSha||m?.graphRevision!==i.historicalGraphRevision)continue;r.push(i)}catch{}}catch{return[]}return r.length===0?r:he(e,t,r,n)}async function V(e,t,n){const r=L(e),o=async h=>(await r("rev-parse","--verify","--quiet",`${h}^{commit}`)).trim(),c=async(h,i)=>{try{return await r("merge-base","--is-ancestor",h,i),!0}catch{return!1}},u=[];try{const h=(await r("symbolic-ref","--quiet","--short","HEAD")).trim(),i=await o("HEAD"),l=await H(e,{required:!0});if(l.epics[t]?.execution_branch!==h||await Y(e,t,l)!==await W(e))return[];const d=Object.values(l.storyWorktrees?.entries??{}).filter(s=>s.epicId===t&&s.executionBranch===h&&s.state==="active");if(d.length>ie)return[];for(const s of d)try{const y=await H(e,{required:!0});if(y.stories[s.storyId]?.checkpoint||d.filter(f=>f.storyId===s.storyId).length!==1||Date.parse(s.expiresAt)>Date.now())continue;const v=g(y.epics[t]?.branch_lease);if(v&&Date.parse(String(v.expiresAt))>Date.now())continue;const a=P(y,t)?.receipts??[];if(a.some(f=>f.kind==="integration-receipt"&&f.storyId===s.storyId))continue;const p=a.filter(f=>f.kind==="phase-one-receipt"&&f.storyId===s.storyId&&f.leaseId===s.leaseId&&f.graphRevision===s.graphRevision);if(p.length!==1)continue;const m=p[0],k=String(m.graphRevision),E=String(m.receiptId);if(!C.test(k)||!O.test(String(m.headSha))||m.specRef!==`docs/stories/${s.storyId}.spec.md`)continue;const w=a.filter(f=>f.kind==="published-story-reconciliation"&&f.storyId===s.storyId&&f.graphRevision===k);if(w.length>1||!n&&w.length===0)continue;const I=await ke(e,s.storyId),x=I.originBinding;if(I.epicId!==t||I.executionBranch!==h||!x||x.originBranch===h||!await c(x.originHeadSha,i))continue;const S=await new re({projectRoot:e}).probe(s.leaseId);if(!S.ok||S.value.ownership!=="proven"||S.value.clean!==!0||!S.value.headSha||!O.test(S.value.headSha)||!await c(String(m.headSha),S.value.headSha))continue;const N=(await r("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${S.value.headSha}`,`${x.originHeadSha}..${i}`)).trim().split(`
|
|
5
|
+
`).filter(Boolean);if(N.length!==1||!O.test(N[0]))continue;const b=N[0],A=(await r("show","-s","--format=%P",b)).trim();if(!O.test(A))continue;const B=F(await r("show","-s","--format=%B",b),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!B.ok||D(B.values,"Neocortex-Story-Worktree-Tip")!==S.value.headSha)continue;const q=D(B.values,"Neocortex-Graph-Revision"),U=D(B.values,"Neocortex-Review-Artifact-Digest");if(!q||!C.test(q)||!U||!C.test(U))continue;const de=(await r("rev-parse",`${b}^{tree}`)).trim(),fe=(await r("rev-parse",`${S.value.headSha}^{tree}`)).trim();if(de!==fe)continue;const K=await Ie(I,s.storyId,b,{expectedGraphRevision:q});if(!K.ok)continue;const le=g(JSON.parse(await r("show",`${b}:.neocortex/state.json`))),X=g(g(le?.stories)?.[s.storyId]);if(X?.epic_id!==t||JSON.stringify(X.depends_on??[])!==JSON.stringify(I.story.depends_on??[]))continue;const T=String(m.specRef),z=`docs/stories/${s.storyId}.story.md`;if(R(await r("show",`${b}:${T}`))!==m.specDigest||R(await r("show",`${i}:${T}`))!==m.specDigest||await r("show",`${b}:${z}`)!==await r("show",`${i}:${z}`))continue;await Q(e,t,s.storyId,r),await r("diff","--quiet","HEAD","--",T,z);const j=ne(await r("show",`${b}:.neocortex/stories/${s.storyId}/qa-gate-result.json`),s.storyId);if(!j)continue;const $=await _(r,x.originBranch);if(!$)continue;try{await o($)}catch{if(!n||(await r("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",$),await o($)!==$))continue}if(!await c(x.originHeadSha,$)||!await c(b,$))continue;const M={schemaVersion:1,kind:"published-story-reconciliation",epicId:t,storyId:s.storyId,graphRevision:k,historicalGraphRevision:q,phaseOneReceiptId:E,executionBranch:h,executionHeadSha:i,originBranch:x.originBranch,originHeadSha:$,commitSha:b,bundleDigest:K.value.bundleDigest,historicalQaDigest:j},ee=async()=>{if(await o("HEAD")!==i||await o(`refs/heads/${h}`)!==i||await _(r,x.originBranch)!==$)throw new Error("published-story-reconciliation-ref-raced");const f=await new re({projectRoot:e}).probe(s.leaseId);if(!f.ok||f.value.ownership!=="proven"||f.value.clean!==!0||f.value.headSha!==S.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await Q(e,t,s.storyId,r),await r("diff","--quiet","HEAD","--",T,z)};if(w[0]){const f=w[0],pe={...M,executionHeadSha:f.executionHeadSha,originHeadSha:f.originHeadSha};if(f.receiptId!==G(pe)||!await c(f.executionHeadSha,i)||!await c(f.originHeadSha,$)||(await ee(),(await H(e,{required:!0})).revision!==y.revision))continue;u.push(f);continue}const J=Object.freeze({...M,receiptId:G(M)});if(!Z(J))continue;await Be(e,f=>{Ae(f,t,{receipts:[J]})},{expectedRevision:y.revision,preCommit:ee}),u.push(J)}catch{}}catch{}return u.length===0?u:he(e,t,u,r)}async function he(e,t,n,r){try{const o=await H(e,{required:!0}),c=(P(o,t)?.receipts??[]).filter(a=>a.kind==="integration-receipt"&&a.outcome==="integrated").sort((a,p)=>Number(p.integrationIndex)-Number(a.integrationIndex));if(c.length===0)return n;const u=String(c[0].epicHeadAfterSha),h=n[0].executionBranch;if(o.epics[t]?.execution_branch!==h)return n;const i=`refs/heads/${h}`,l=(await r("rev-parse","--verify",i)).trim(),d=async(a,p)=>{if(a===p)return!0;try{return await r("merge-base","--is-ancestor",a,p),!0}catch{return!1}},s=[...new Set([u,...n.map(a=>a.commitSha)])],y=[...s,...n.map(a=>a.executionHeadSha)];if(!(await Promise.all(y.map(a=>d(a,l)))).every(Boolean))return n;let v=l;for(const a of s)if((await Promise.all(s.map(p=>d(p,a)))).every(Boolean)){v=a;break}return(await r("rev-parse","--verify",i)).trim()!==l||(await H(e,{required:!0})).revision!==o.revision?n:n.map(a=>{const p={...a,syncBaseSha:v,syncIntegrationHeadSha:u};return Object.freeze({...p,receiptId:G(p)})})}catch{return n}}export{ne as historicalStoryQaDigest,Ne as reconcilePublishedStoriesForYoloop,De as reconcilePublishedWorkflowState,$e as recoverPublishedCheckpointForYoloop,Me as revalidatePublishedStoriesForYolo,Ee as revalidatePublishedStoryDependencies};
|
|
@@ -46,7 +46,7 @@ export declare function anchoredExecuteNode(parent: string, name: string, expect
|
|
|
46
46
|
* `secure-git-command-failed:<n>` carrying the tail via `anchoredGateStderrTail`.
|
|
47
47
|
*/
|
|
48
48
|
export declare function anchoredExecuteGate(parent: string, name: string, expectedChild: AnchoredDirectoryIdentity, args: readonly string[], gate: AnchoredGateExecutionOptions): Promise<Buffer>;
|
|
49
|
-
export declare function anchoredExecuteNpm(parent: string, name: string, expectedChild: AnchoredDirectoryIdentity, args: readonly string[]): Promise<Buffer>;
|
|
49
|
+
export declare function anchoredExecuteNpm(parent: string, name: string, expectedChild: AnchoredDirectoryIdentity, args: readonly string[], env?: NodeJS.ProcessEnv): Promise<Buffer>;
|
|
50
50
|
export declare function anchoredCreateOwnedDirectory(parent: string, name: string, owner: Buffer | string): Promise<void>;
|
|
51
51
|
export declare function anchoredRenameDirectory(parent: string, sourceName: string, destinationName: string, options?: AnchoredFilesystemTestOptions): Promise<void>;
|
|
52
52
|
export declare function anchoredRemoveDirectory(parent: string, name: string, options?: AnchoredFilesystemTestOptions): Promise<void>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{spawn as
|
|
1
|
+
import{spawn as F}from"node:child_process";import{randomBytes as M}from"node:crypto";import{lstat as I,stat as T}from"node:fs/promises";const $=String.raw`
|
|
2
2
|
const fs = require('node:fs');
|
|
3
3
|
const crypto = require('node:crypto');
|
|
4
4
|
const [op, expectedDev, expectedIno, name, temporary, expectedSha] = process.argv.slice(1);
|
|
@@ -93,7 +93,7 @@ if (op === 'mkdir' || op === 'mkdir-exclusive') {
|
|
|
93
93
|
if (safeExisting(name, 'directory')) fail('secure-filesystem-directory-remained');
|
|
94
94
|
} else fail('secure-filesystem-operation-invalid');
|
|
95
95
|
try { const parent = fs.openSync('.', fs.constants.O_RDONLY); fs.fsyncSync(parent); fs.closeSync(parent); } catch {}
|
|
96
|
-
|
|
96
|
+
`,Y=64*1024,P=Symbol.for("neocortex.p226.gateStderrTail"),b="secure-git-command-stderr:";function j(t){if(!(t instanceof Error))return;const e=t[P];return typeof e=="string"?e:void 0}const K=String.raw`
|
|
97
97
|
const fs = require('node:fs');
|
|
98
98
|
const cp = require('node:child_process');
|
|
99
99
|
const [expectedParentDev, expectedParentIno, name, expectedChildDev, expectedChildIno, encodedArgs, handshake, binary, captureStderr] = process.argv.slice(1);
|
|
@@ -156,6 +156,6 @@ if (result.status !== 0) {
|
|
|
156
156
|
}
|
|
157
157
|
if (result.stdout && result.stdout.length > maxOutputBytes) fail('secure-git-output-too-large');
|
|
158
158
|
if (result.stdout) process.stdout.write(result.stdout);
|
|
159
|
-
`;function
|
|
160
|
-
`))&&
|
|
161
|
-
`),
|
|
159
|
+
`;function N(t=process.platform){return t!=="win32"}async function z(t,e,r,s={}){const i=`.${e}.${process.pid}.${M(8).toString("hex")}.tmp`;await p(t,["write",e,i],Buffer.isBuffer(r)?r:Buffer.from(r),s)}async function Z(t,e,r,s,i={}){const c=`.${e}.${process.pid}.${M(8).toString("hex")}.tmp`;await p(t,["write-cas",e,c,s],Buffer.isBuffer(r)?r:Buffer.from(r),i)}async function Q(t,e,r={}){await p(t,["remove",e],void 0,r)}async function V(t,e,r={}){await p(t,["mkdir",e],void 0,r)}async function ee(t,e){const s=(await p(t,["mkdir-exclusive",e])).toString("utf8").match(/^secure-filesystem-identity:([0-9]+):([0-9]+)$/);if(!s)throw new Error("secure-filesystem-created-identity-missing");return Object.freeze({dev:s[1],ino:s[2]})}async function te(t){if(!N())throw new Error("secure-filesystem-platform-unsupported");const e=await I(t,{bigint:!0}),r=await T(t,{bigint:!0});if(e.isSymbolicLink()||!e.isDirectory()||!r.isDirectory()||e.dev!==r.dev||e.ino!==r.ino)throw new Error("secure-filesystem-directory-unsafe");return Object.freeze({dev:String(r.dev),ino:String(r.ino)})}async function re(t,e,r,s,i,c={}){return x("git",t,e,r,s,i,c)}async function ie(t,e,r,s,i,c={}){return x("node",t,e,r,s,i,c)}async function se(t,e,r,s,i){if(!Number.isSafeInteger(i.timeoutMs)||i.timeoutMs<=0||!Number.isSafeInteger(i.graceMs)||i.graceMs<=0)throw new Error("secure-git-gate-budget-invalid");return x("node",t,e,r,s,void 0,{},i)}async function ne(t,e,r,s,i){return x("npm",t,e,r,s,void 0,{},void 0,i)}async function x(t,e,r,s,i,c,l={},a,d){if(!N(l.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");if(i.length===0||i.length>512||i.some(o=>typeof o!="string"||o.length>4096||o.includes("\0")))throw new Error("secure-git-args-invalid");const u=await T(e,{bigint:!0}),m=await I(e,{bigint:!0});if(!u.isDirectory()||m.isSymbolicLink()||!m.isDirectory()||u.dev!==m.dev||u.ino!==m.ino)throw new Error("secure-filesystem-parent-invalid");await l.beforeHandoff?.();const g=t==="git"?16*1024*1024:64*1024*1024;return await new Promise((o,y)=>{const S=l.afterHandoff?"1":"0",E=Buffer.from(JSON.stringify([...i])).toString("base64url"),f=F(process.execPath,["-e",K,String(u.dev),String(u.ino),r,s.dev,s.ino,E,S,t,a?"1":"0"],{cwd:e,stdio:["pipe","pipe","pipe"],...a?{env:{...a.env},detached:!0}:d?{env:{...d}}:{}}),R=[],v=[];let w=0,D=!1;const O=[],_=n=>{try{f.pid!==void 0&&process.kill(-f.pid,n)}catch{f.kill(n)}};a&&O.push(setTimeout(()=>{D=!0,_("SIGTERM"),O.push(setTimeout(()=>_("SIGKILL"),a.graceMs))},a.timeoutMs));const k=()=>{for(const n of O)clearTimeout(n)};let B=!l.afterHandoff,L=!1;const A=async()=>{if(!L){L=!0;try{await l.afterHandoff?.(),B=!0,f.stdin.end(c===void 0?void 0:Buffer.isBuffer(c)?c:Buffer.from(c))}catch(n){f.kill(),y(n)}}};f.stdout.on("data",n=>{w+=n.length,w>g?f.kill():R.push(n)}),f.stderr.on("data",n=>{v.push(n),!B&&Buffer.concat(v).includes(Buffer.from(`secure-git-handoff-ready
|
|
160
|
+
`))&&A()}),f.once("error",n=>{k(),y(n)}),f.once("close",n=>{if(k(),D)return _("SIGKILL"),y(new Error("secure-git-command-timeout"));if(n===0&&w<=g)return o(Buffer.concat(R));const C=Buffer.concat(v).toString("utf8").split(`
|
|
161
|
+
`),W=C.find(h=>h.startsWith("secure-git-")&&h!=="secure-git-handoff-ready"&&!h.startsWith(b))??(w>g?"secure-git-output-too-large":"secure-git-helper-failed"),G=new Error(W);if(a){const h=C.find(X=>X.startsWith(b)),H=h===void 0?"":Buffer.from(h.slice(b.length),"base64url").subarray(-Y).toString("utf8");Object.defineProperty(G,P,{value:H,enumerable:!1})}y(G)}),l.afterHandoff||A()})}async function oe(t,e,r){await p(t,["create-owned-directory",e],Buffer.isBuffer(r)?r:Buffer.from(r))}async function ce(t,e,r,s={}){await p(t,["rename-directory",e,r],void 0,s)}async function ae(t,e,r={}){await p(t,["remove-directory",e],void 0,r)}async function p(t,e,r,s={}){if(!N(s.platform??process.platform))throw new Error("secure-filesystem-platform-unsupported");const i=await T(t,{bigint:!0});if(!i.isDirectory())throw new Error("secure-filesystem-parent-invalid");if((await I(t,{bigint:!0})).isSymbolicLink())throw new Error("secure-filesystem-parent-symlink");return await s.beforeHandoff?.(),await new Promise((l,a)=>{const d=F(process.execPath,["-e",$,...e.slice(0,1),String(i.dev),String(i.ino),...e.slice(1)],{cwd:t,stdio:["pipe","pipe","pipe"]}),u=[];let m=0;const g=[];d.stdout.on("data",o=>{m+=o.length,m>1024?d.kill():u.push(o)}),d.stderr.on("data",o=>g.push(o)),d.once("error",a),d.once("close",o=>{if(o===0&&m<=1024)return l(Buffer.concat(u));const y=Buffer.concat(g).toString("utf8")||"secure-filesystem-helper-failed",S=new Error(y),E=y.match(/^secure-filesystem-os:(E[A-Z0-9]+)$/)?.[1];E&&(S.code=E),y==="secure-filesystem-entry-exists"&&(S.code="EEXIST"),a(S)}),d.stdin.end(r)})}export{Y as ANCHORED_GATE_STDERR_TAIL_BYTES,z as anchoredAtomicWriteFile,Z as anchoredCompareAndSwapFile,ee as anchoredCreateDirectory,oe as anchoredCreateOwnedDirectory,te as anchoredDirectoryIdentity,V as anchoredEnsureDirectory,se as anchoredExecuteGate,re as anchoredExecuteGit,ie as anchoredExecuteNode,ne as anchoredExecuteNpm,j as anchoredGateStderrTail,ae as anchoredRemoveDirectory,Q as anchoredRemoveFile,ce as anchoredRenameDirectory,N as secureFilesystemBoundaryAvailable};
|
|
@@ -50,6 +50,8 @@ export interface IntegrateStoryWorktreeOptions {
|
|
|
50
50
|
}) => Promise<unknown>;
|
|
51
51
|
/** Test seam after the fast-forward and before finalize (crash-window reproduction). */
|
|
52
52
|
readonly afterFastForward?: () => Promise<void>;
|
|
53
|
+
/** Test seam after checkpoint persistence and before integration-receipt persistence. */
|
|
54
|
+
readonly afterCheckpointPersist?: () => Promise<void>;
|
|
53
55
|
}
|
|
54
56
|
export declare function digestStoryWorktreeIntegrationReceipt(receipt: IntegrationReceipt): string;
|
|
55
57
|
/** Integrate one story worktree into `epic/<ID>` (P225.07-ADR-1..6). */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`).map(o=>o.trim()).filter(o=>o.startsWith(a));return c.length===1?c[0].slice(a.length):void 0}function ze(e){return St(Lt,e)}function X(e,t){return(Me(e,t)?.receipts??[]).filter(Tt)}function me(e){const t=[...e].sort((a,c)=>a.integrationIndex-c.integrationIndex);t.forEach((a,c)=>{(a.integrationIndex!==c+1||c>0&&a.epicHeadBeforeSha!==t[c-1].epicHeadAfterSha)&&n("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((c,o)=>o.integrationIndex-c.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&n("story-worktree-integration-chain-invalid")}const Gt=new Set(["done","merged","completed","released"]);function ft(e,t,a,c,o,f,r=new Set){(Me(e,a)?.receipts??[]).some(y=>y.kind==="phase-one-receipt"&&y.storyId===c||y.kind==="spec-barrier-receipt"&&Array.isArray(y.storyIds)&&y.storyIds.includes(c))||n("story-worktree-integration-unbound");const g=new Set(X(e,a).filter(y=>y.outcome==="integrated").map(y=>y.storyId));for(const y of o){if(!y.startsWith(`${a}.`))continue;const b=t[y],k=!!e.stories[y]?.checkpoint||typeof b?.status=="string"&&Gt.has(b.status);!g.has(y)&&!r.has(y)&&!f.has(y)&&!k&&n("story-worktree-integration-dependency-waiting")}}async function lt(e,t,a){if(!(Me(t,a)?.receipts??[]).some(f=>f.kind==="published-story-reconciliation"))return new Set;const o=await Wt(e,a);return new Set(o.map(f=>f.storyId))}function qt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${fe(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function Le(e){return fe(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function De(e){let t;return await pe(e.projectRoot,a=>{const c=X(a,e.epicId);me(c);const o=[...c].sort((r,l)=>l.integrationIndex-r.integrationIndex)[0];o&&o.epicHeadAfterSha!==e.before&&n("story-worktree-integration-chain-invalid"),[...c].filter(r=>r.storyId===e.storyId).sort((r,l)=>l.integrationIndex-r.integrationIndex)[0]?.outcome==="integrated"&&n("story-worktree-integration-already-integrated"),t=qt({epicId:e.epicId,storyId:e.storyId,index:c.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Ct(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await w(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&n("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await _(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&n("story-worktree-integration-epic-head-raced")}}),t}function ke(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:ze(e.receipt)})}}async function Ft(e){let t,a,c="";const o=Re(e.projectRoot);try{if((typeof e.storyId!="string"||!_e.test(e.storyId))&&n("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!$t.test(e.leaseId)&&n("story-worktree-integration-lease-invalid"),!e.allowLinkedEpicCheckout){const h=await Ae(await w(o,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),A=await Ae(await w(o,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));h!==A&&n("story-worktree-integration-not-root")}let f;try{f=await rt(o,e.storyId)}catch(h){n(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:r,executionBranch:l,storyId:d}=f;c=r;const u=new Date(e.nowIso??Date.now()).toISOString(),g=`refs/heads/${l}`,y=await w(o,["rev-parse",g],"story-worktree-integration-epic-branch-missing");(await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y||e.allowLinkedEpicCheckout&&await w(o,["symbolic-ref","HEAD"],"story-worktree-integration-root-head-mismatch")!==g)&&n("story-worktree-integration-root-head-mismatch");const b=f.originBinding;(!b||!await _(o,["merge-base","--is-ancestor",b.originHeadSha,y]))&&n("story-worktree-integration-origin-binding-invalid");const k=await V(o,{required:!0}),S=X(k,r);me(S);const D=S.filter(h=>h.storyId===d).sort((h,A)=>A.integrationIndex-h.integrationIndex),R=k.stories[d]?.checkpoint;if(D[0]?.outcome==="integrated")return ke({storyId:d,epicId:r,outcome:"already-integrated",receipt:D[0],...R?.headSha?{checkpointHeadSha:R.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(h=>typeof h=="string"):[],E=await yt(o,k),B=await lt(o,k,r);ft(k,E,r,d,G,B);const T=Object.values(k.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===r&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(R&&typeof R.headSha=="string"){const h=R.headSha,A=await w(o,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(M(A,"Neocortex-Story")!==d||!M(A,ue))&&n("story-worktree-integration-checkpoint-not-worktree"),h!==y&&n("story-worktree-integration-epic-head-raced"),le(S,R.baseSha);const te=await wt(o,d,`recover-${h.slice(0,40)}`,()=>De({projectRoot:o,epicId:r,storyId:d,executionBranch:l,before:R.baseSha,after:h,checkpointDigest:Le(R),outcome:"integrated",integratedAt:u})),ne=T.length===1?await qe(o,T[0].leaseId,h):!1;return ke({storyId:d,epicId:r,outcome:"integrated",receipt:te,checkpointHeadSha:h,worktreeRealigned:ne})}const C=Object.values(k.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===r&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));C.length===0&&n("story-worktree-integration-lease-missing"),C.length>1&&n("story-worktree-integration-lease-ambiguous");const x=C[0];x.executionBranch!==l&&n("story-worktree-integration-lease-invalid");const F=await new xe({projectRoot:o}).probe(x.leaseId);(!F.ok||F.value.ownership!=="proven")&&n("story-worktree-integration-ownership-unproven"),F.value.clean!==!0&&n("story-worktree-integration-worktree-dirty");const v=await w(o,["rev-parse",`refs/heads/${x.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");F.value.headSha!==v&&n("story-worktree-integration-worktree-dirty");const H=await w(o,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed"),z=M(H,ue)===v&&M(H,"Neocortex-Story")===d;let j,N,m,U=!1;if(z){j=await w(o,["rev-parse",`${y}^`],"story-worktree-integration-git-failed"),N=y;const h=M(H,"Neocortex-Bundle-Digest")??"",A=M(H,"Neocortex-Claim-Revision")??"";m=tt({storyId:d,epicId:r,executionBranch:l,baseSha:j,bundleDigest:h,graphRevision:f.graphRevision,claimRevision:A}),le(S,j)}else{le(S,y);const h=await ht(o,f,d,y,v);if(h.kind==="conflict")return await Fe({projectRoot:o,epicId:r,storyId:d,executionBranch:l,epicHead:y,tip:v,conflictPaths:h.conflictPaths,integratedAt:u,chain:D});const A=h.changedPaths;N=h.commitSha,m=h.idempotencyKey,j=y,U=!0,(!await _(o,["diff","--cached","--quiet"])||!await _(o,["diff","--quiet","HEAD","--",...A]))&&n("story-worktree-integration-root-dirty")}const Q=await ot(f,d,N);Q.ok||n(Q.reasonCode);const Z=await V(o,{required:!0}),$=Z.epics[r]?.branch_lease,oe=$&&$.ownerStoryId===d&&$.sessionId===m&&$.idempotencyKey===m&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!oe&&Date.parse(String($.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:m,idempotencyKey:m,acquiredAt:u,expiresAt:new Date(Date.parse(u)+et).toISOString()};t=await Ne(o,{kind:"direct",storyId:d,sessionId:m,idempotencyKey:m,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||n(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await pe(o,h=>{const A=Ee(h,r),te=A.branch_lease;te&&Date.parse(String(te.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active"),JSON.stringify(A.origin_binding)!==JSON.stringify(b)&&n("story-worktree-integration-origin-binding-invalid"),A.graph_revision!==f.graphRevision&&n("story-worktree-integration-graph-revision-raced"),A.branch_lease=K},{expectedRevision:Z.revision,preCommit:async h=>{await it(Y.path,Y.owner)||n("story-worktree-integration-lock-raced");const A=X(h,r);me(A),le(A,j),await w(o,["rev-parse",g],"story-worktree-integration-epic-branch-missing")!==y&&n("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y||await w(o,["rev-parse",g],"story-worktree-integration-git-failed")!==y)&&n("story-worktree-integration-epic-head-raced"),await _(o,["merge","--ff-only","--no-edit",N])||n("story-worktree-integration-ff-refused"),await w(o,["rev-parse",g],"story-worktree-integration-git-failed")!==N&&n("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let ee;const ie=await At({projectRoot:o,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:f.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await V(o,{required:!0})).stories[d]?.checkpoint;(!h||h.headSha!==N||h.baseSha!==j)&&n("story-worktree-integration-checkpoint-mismatch"),ee=await De({projectRoot:o,epicId:r,storyId:d,executionBranch:l,before:j,after:N,checkpointDigest:Le(h),outcome:"integrated",integratedAt:u})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==N||L.baseSha!==j||!ee)&&n("story-worktree-integration-checkpoint-mismatch");const ge=await qe(o,x.leaseId,N);return ke({storyId:d,epicId:r,outcome:"integrated",receipt:ee,checkpointHeadSha:N,worktreeRealigned:ge})}catch(f){if(f instanceof Ce)return{ok:!1,reasonCode:f.reasonCode};const r=f instanceof Error?f.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(r)?{ok:!1,reasonCode:r}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const f=a;await pe(o,r=>{const l=Ee(r,c),d=l.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(l.branch_lease=null)}).catch(()=>{})}}}const je=".neocortex/state.json",Te=".neocortex",Oe="state.json",W="story-worktree-integration-state-merge-git-failed";function Pe(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const c=a.indexOf(" "),[o,f,r]=a.slice(0,c).split(" ");(c<0||!o||!f||!r)&&n(W),t.push({mode:o,type:f,oid:r,name:a.slice(c+1)})}return t}function Kt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function gt(e,t,a,c){const o=await P(e,["ls-tree","-z",t]);o.code!==0&&n(W);const f=Pe(o.stdout).filter(d=>d.name!==a),r=await ct(e,["mktree","-z"],Kt([...f,c])),l=r.stdout.trim();return(r.code!==0||!de.test(l))&&n(W),l}async function $e(e,t){const a=await P(e,["ls-tree","-z",t,"--",je]);a.code!==0&&n(W);const c=Pe(a.stdout).find(o=>o.name===je);return c?((c.type!=="blob"||c.mode!=="100644"&&c.mode!=="100755")&&n("state-merge-input-invalid"),de.test(c.oid)||n(W),c.oid):null}async function Ge(e,t){t===null&&n("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),c=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(c)||c<0||c>Bt)&&n(W);const o=await P(e,["cat-file","blob",t]);return o.code!==0&&n(W),o.stdout}async function Yt(e){try{const{projectRoot:t,mergeBase:a,epicHead:c,tip:o,tree:f,storyId:r,epicId:l}=e,d={ok:!0,tree:f,conflictPaths:[...e.conflictPaths],merged:!1},u=await $e(t,a),g=await $e(t,o);if(u===g)return d;const y=await Ge(t,u),b=await Ge(t,await $e(t,c)),k=await Ge(t,g),S=await w(t,["show","--no-patch","--format=%cI",o],W),D=Ht({base:y,epic:b,story:k,storyId:r,epicId:l,aggregateTimestamp:S});if(!D.ok)return{ok:!1,reasonCode:D.reasonCode};const R=e.conflictPaths.filter(v=>v!==je),G=await P(t,["ls-tree","-z",f,"--",Te]);G.code!==0&&n(W);const E=Pe(G.stdout).find(v=>v.name===Te);if(!E||E.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const B=await P(t,["ls-tree","-z",E.oid,"--",Oe]);B.code!==0&&n(W);const T=Pe(B.stdout).find(v=>v.name===Oe);if(T&&(T.type!=="blob"||T.mode!=="100644"&&T.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const C=await ct(t,["hash-object","-w","--stdin"],D.bytes),x=C.stdout.trim();if((C.code!==0||!de.test(x))&&n(W),T?.oid===x)return{ok:!0,tree:f,conflictPaths:R,merged:!0};const q=await gt(t,E.oid,Oe,{mode:T?.mode??"100644",type:"blob",oid:x,name:Oe});return{ok:!0,tree:await gt(t,f,Te,{mode:E.mode,type:"tree",oid:q,name:Te}),conflictPaths:R,merged:!0}}catch(t){return t instanceof Ce?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function ht(e,t,a,c,o){const{epicId:f,executionBranch:r}=t;await _(e,["merge-base","--is-ancestor",o,c])&&n("story-worktree-integration-range-empty");const l=await w(e,["merge-base",c,o],"story-worktree-integration-unrelated-history"),d=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${l}`,c,o]);d.code!==0&&d.code!==1&&n("story-worktree-integration-git-unsupported");const u=d.stdout.split("\0"),g=u[0]?.trim()??"";de.test(g)||n("story-worktree-integration-git-unsupported");const y=d.code===1?[...new Set(u.slice(1).filter(dt))].sort():[];d.code===1&&y.length===0&&n("story-worktree-integration-git-failed");const b=await Yt({projectRoot:e,mergeBase:l,epicHead:c,tip:o,tree:g,storyId:a,epicId:f,conflictPaths:y});b.ok||n(b.reasonCode);const k=b.tree;if(b.conflictPaths.length>0)return{kind:"conflict",conflictPaths:b.conflictPaths.slice(0,jt)};const S=(await w(e,["diff","--name-only","-z",c,k],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),D=_t(S,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);D.ok||n(D.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":D.reasonCode===ce.WRITE_SET_FORBIDDEN?ce.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const R=t.governanceMode==="runtime-store"?await Jt(e,f,a,o):void 0,G=R?R.review:Pt(e,a,k);G?.verdict!=="approved"&&n("story-worktree-integration-review-not-approved");const E=await P(e,["diff","--binary","--full-index",c,k]);E.code!==0&&n("story-worktree-integration-git-failed");const B=E.stdout;B||n("story-worktree-integration-range-empty");const T=fe(B),C=fe([...t.authorizedWriteSet].sort().join("\0")),x=tt({storyId:a,epicId:f,executionBranch:r,baseSha:c,bundleDigest:T,graphRevision:t.graphRevision,claimRevision:C}),q=(await w(e,["show","--no-patch","--format=%s",o],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,F=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${f}`,`Neocortex-Execution-Branch: ${r}`,`Neocortex-Prepared-Base: ${c}`,`Neocortex-Bundle-Digest: ${T}`,`Neocortex-Review-Artifact-Digest: ${G.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${C}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${zt(t.rootMemoryEffect)}`]:[],...R?[`${nt}: ${R.governanceDigest}`]:[],`${ue}: ${o}`],v=(await w(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",o],"story-worktree-integration-git-failed")).split("\0");v.length!==6&&n("story-worktree-integration-git-failed");const H=await w(e,["commit-tree",k,"-p",c,"-m",q,"-m",`Story: ${a}`,"-m",F.join(`
|
|
3
|
-
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:v[0],GIT_AUTHOR_EMAIL:v[1],GIT_AUTHOR_DATE:v[2],GIT_COMMITTER_NAME:v[3],GIT_COMMITTER_EMAIL:v[4],GIT_COMMITTER_DATE:v[5]});return de.test(H)||n("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:H,changedPaths:S,idempotencyKey:x}}async function Jt(e,t,a,c){const o=await w(e,["show","--no-patch","--format=%B",c],"story-worktree-integration-git-failed"),f=M(o,nt);f===void 0&&n("story-worktree-integration-governance-trailer-missing");const r=Nt({projectRoot:e,epicId:t,storyId:a});r.ok||n(r.reasonCode===ce.UNSAFE?r.reasonCode:ce.MISMATCH);const l=r.value.receipt.governanceDigest;f!==l&&n(ce.MISMATCH);const d=r.value.files.get(Mt(a));return d||n(ce.MISMATCH),{governanceDigest:l,review:Ot(a,d)}}async function yt(e,t){const a=JSON.parse(await It(vt(e,".neocortex","state.json"),"utf8")),o=Dt(a,t).stories;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}async function wt(e,t,a,c){const o=await Ne(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});o.ok||n(o.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await c()}finally{await We(o.path,o.owner).catch(()=>{})}}async function qe(e,t,a){const c=await new xe({projectRoot:e}).probe(t);return!c.ok||c.value.ownership!=="proven"||c.value.clean!==!0?!1:_(c.value.entry.worktreePath,["reset","--keep",a])}async function Fe(e){const t=fe(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const c=()=>De({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),o=e.lockHeld?await c():await wt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,c);return ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:o,conflictPaths:Object.freeze([...e.conflictPaths])})}const Ut=64,Vt="@ornexus/neocortex",Ke=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ke)if(!dt(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Xt(e){return _(e,["clean","-X","-f","-q","--",...Ke])}async function Qt(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Vt?Ke:[]}catch{return[]}}function Zt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function gr(e){let t,a,c="",o=0,f;const r=Re(e.projectRoot);try{const l=e.storyIds;if((!Array.isArray(l)||l.length===0||l.length>Ut||new Set(l).size!==l.length||l.some(i=>typeof i!="string"||!_e.test(i)))&&n("story-worktree-wave-stories-invalid"),!e.allowLinkedEpicCheckout){const i=await Ae(await w(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),s=await Ae(await w(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));i!==s&&n("story-worktree-integration-not-root")}const d=new Map;for(const i of l)try{d.set(i,await rt(r,i))}catch(s){n(s instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(s.message)?s.message:"story-worktree-integration-authority-invalid")}const u=d.get(l[0]),{epicId:g,executionBranch:y}=u;for(const i of d.values())(i.epicId!==g||i.executionBranch!==y||i.graphRevision!==u.graphRevision||JSON.stringify(i.originBinding)!==JSON.stringify(u.originBinding))&&n("story-worktree-wave-epic-mixed");c=g;const b=new Date(e.nowIso??Date.now()).toISOString(),k=`refs/heads/${y}`,S=await w(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing");(await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await w(r,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==y)&&n("story-worktree-integration-root-head-mismatch");const D=u.originBinding;(!D||!await _(r,["merge-base","--is-ancestor",D.originHeadSha,S]))&&n("story-worktree-integration-origin-binding-invalid");const R=i=>{const s=d.get(i).story;return Array.isArray(s.depends_on)?s.depends_on.filter(p=>typeof p=="string"):[]},G=new Map(l.map((i,s)=>[i,s]));l.forEach((i,s)=>{for(const p of R(i)){const I=G.get(p);I!==void 0&&I>=s&&n("story-worktree-wave-order-invalid")}});const E=await V(r,{required:!0}),B=X(E,g);me(B);const T=i=>B.filter(s=>s.storyId===i).sort((s,p)=>p.integrationIndex-s.integrationIndex)[0],C=l.filter(i=>T(i)?.outcome!=="integrated"),x=new Map(l.filter(i=>!C.includes(i)).map(i=>{const s=T(i),p=E.stories[i]?.checkpoint;return[i,Object.freeze({storyId:i,outcome:"already-integrated",receiptDigest:ze(s),...p?.headSha?{checkpointHeadSha:p.headSha}:{}})]})),q=i=>({ok:!0,value:Object.freeze({epicId:g,...i,gateRuns:o,stories:Object.freeze(l.map(s=>x.get(s)??Object.freeze({storyId:s,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return q({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const F=new Set(C),v=[];let H=S;for(let i=0;i<C.length;i++){const s=await w(r,["show","--no-patch","--format=%B",H],"story-worktree-integration-git-failed"),p=M(s,"Neocortex-Story");if(!p||!F.has(p)||!M(s,ue))break;v.unshift(H),H=await w(r,["rev-parse",`${H}^`],"story-worktree-integration-git-failed")}const z=H;le(B,z);const j=await yt(r,E),N=await lt(r,E,g),m=[];let U,Q=z;for(const[i,s]of C.entries()){const p=d.get(s);ft(E,j,g,s,R(s),N,new Set(C.slice(0,i)));const I=Object.values(E.storyWorktrees?.entries??{}).filter(J=>J.storyId===s&&J.epicId===g&&J.state==="active"),O=E.stories[s]?.checkpoint;if(O&&typeof O.headSha=="string"){const J=O.headSha,Qe=await w(r,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");(M(Qe,"Neocortex-Story")!==s||!M(Qe,ue))&&n("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==Q||v[i]!==J)&&n("story-worktree-integration-checkpoint-mismatch");const mt=(await w(r,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);m.push({storyId:s,sha:J,changedPaths:mt,...I.length===1?{leaseId:I[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),Q=J;continue}I.length===0&&n("story-worktree-integration-lease-missing"),I.length>1&&n("story-worktree-integration-lease-ambiguous");const Se=I[0];Se.executionBranch!==y&&n("story-worktree-integration-lease-invalid");const be=await new xe({projectRoot:r}).probe(Se.leaseId);(!be.ok||be.value.ownership!=="proven")&&n("story-worktree-integration-ownership-unproven"),be.value.clean!==!0&&n("story-worktree-integration-worktree-dirty");const Be=await w(r,["rev-parse",`refs/heads/${Se.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");be.value.headSha!==Be&&n("story-worktree-integration-worktree-dirty");const se=await ht(r,p,s,Q,Be);if(se.kind==="conflict"){i<v.length&&n("story-worktree-wave-resume-mismatch"),U={storyId:s,tip:Be,conflictPaths:se.conflictPaths};break}i<v.length&&v[i]!==se.commitSha&&n("story-worktree-wave-resume-mismatch"),m.push({storyId:s,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:Se.leaseId}),Q=se.commitSha}if(m.length<v.length&&n("story-worktree-wave-resume-mismatch"),m.length===0){const i=U,s=await Fe({projectRoot:r,epicId:g,storyId:i.storyId,executionBranch:y,epicHead:S,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:b,chain:B.filter(p=>p.storyId===i.storyId).sort((p,I)=>I.integrationIndex-p.integrationIndex)});return s.ok?(x.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:s.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])})),q({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:s.reasonCode,gateRuns:o}}const Z=new Map;for(const i of m){if(i.checkpointGraphRevision!==void 0){const p=await w(r,["show","--no-patch","--format=%B",i.sha],"story-worktree-integration-git-failed"),I=M(p,"Neocortex-Graph-Revision");I===void 0&&n("direct-yolo-trailer-missing:neocortex-graph-revision"),I!==i.checkpointGraphRevision&&n("direct-yolo-trailer-mismatch:neocortex-graph-revision"),Z.set(i.sha,I);continue}const s=await ot(d.get(i.storyId),i.storyId,i.sha);s.ok||n(s.reasonCode),Z.set(i.sha,s.value.graphRevision)}const $=m[m.length-1].sha,oe=[...new Set(m.flatMap(i=>i.changedPaths))].sort();(!await _(r,["diff","--cached","--quiet"])||!await _(r,["diff","--quiet","HEAD","--",...oe]))&&n("story-worktree-integration-root-dirty");const K=Zt(m.length),Y=fe(["p205-wave-lease-v1",g,y,z,...m.map(i=>i.sha)].join("\0")),ee=m[0].storyId,ie=await V(r,{required:!0}),L=ie.epics[g]?.branch_lease,ge=L&&L.ownerStoryId===ee&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!ge&&Date.parse(String(L.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active");const h=ge??{schemaVersion:1,ownerStoryId:ee,sessionId:Y,idempotencyKey:Y,acquiredAt:b,expiresAt:new Date(Date.parse(b)+et*K).toISOString()};t=await Ne(r,{kind:"direct",storyId:ee,sessionId:Y,idempotencyKey:Y,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||n(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const A=t;ge||await pe(r,i=>{const s=Ee(i,g),p=s.branch_lease;p&&Date.parse(String(p.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active"),JSON.stringify(s.origin_binding)!==JSON.stringify(D)&&n("story-worktree-integration-origin-binding-invalid"),s.graph_revision!==u.graphRevision&&n("story-worktree-integration-graph-revision-raced"),s.branch_lease=h},{expectedRevision:ie.revision,preCommit:async i=>{await it(A.path,A.owner)||n("story-worktree-integration-lock-raced");const s=X(i,g);me(s),le(s,z),await w(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing")!==S&&n("story-worktree-integration-epic-head-raced")}}),a=h;const te=new Set(m.map(i=>i.sha));let ne=!0;if(e.push&&v.length>0){const i=(await P(r,["ls-remote","--heads",e.remote??"origin",k])).stdout.split(/\s+/)[0]??"";de.test(i)&&await _(r,["merge-base","--is-ancestor",v[0],i])&&(ne=!1)}let ae=S;const Ie=async i=>{if((await w(r,["rev-parse",k],"story-worktree-integration-git-failed")!==ae||await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await w(r,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==y)&&n("story-worktree-integration-epic-head-raced"),ae===i)return;const s=await _(r,["merge-base","--is-ancestor",ae,i]);!s&&(!ne||!te.has(ae))&&n("story-worktree-wave-pushed-immovable"),(!(s?await _(r,["merge","--ff-only","--no-edit",i]):await _(r,["reset","--keep",i]))||await w(r,["rev-parse",k],"story-worktree-integration-git-failed")!==i||await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==i)&&n("story-worktree-integration-ff-refused"),ae=i};f=ne?{epicRef:k,base:z,owned:te}:void 0,await Ie($),await e.afterWaveFastForward?.();const pt=[...new Set(m.map(i=>Z.get(i.sha)))],ut=await Qt(r,z),He=async()=>{ut.length!==0&&(await(e.cleanBuildOutputs??Xt)(r)||n("story-worktree-wave-clean-failed"))},Ye=async i=>{const s=m[i];await Ie(s.sha),o>=K&&n("story-worktree-wave-gate-cap-exceeded"),o>0&&await He(),o++;const p=await xt({projectRoot:r,headSha:s.sha,storyId:s.storyId,graphRevisions:pt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==s.sha||await w(r,["rev-parse",k],"story-worktree-integration-git-failed")!==s.sha||!await _(r,["diff","--cached","--quiet"])||!await _(r,["diff","--quiet","HEAD","--",...oe]))&&n("story-worktree-integration-epic-head-raced"),!p.ok&&p.kind==="infrastructure"&&n(p.reasonCode),p},ve=await Ye(m.length-1);let Je=m.length-1,Ue=ve.ok?ve.authorities:void 0,he,ye;if(!ve.ok){ne||n("story-worktree-wave-gate-failed-pushed");let i=-1,s=m.length-1;for(ye=ve.reasonCode;s-i>1;){const I=Math.floor((i+s)/2),O=await Ye(I);O.ok?(i=I,Ue=O.authorities):(s=I,ye=O.reasonCode)}he=s,Je=i;const p=m[s].storyId;if(x.set(p,Object.freeze({storyId:p,outcome:"gate-failed",reasonCode:ye})),i<0)return await Ie(z),await He(),f=void 0,q({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:p,failureReasonCode:ye,epicHeadBeforeSha:S,epicHeadAfterSha:z,gateRunCap:K});await Ie(m[i].sha),await He()}const re=m.slice(0,Je+1),we=re[re.length-1].sha,Ve=bt({epicId:g,executionBranch:y,waveHeadSha:we,waveStoryIds:re.map(i=>i.storyId),waveCommitShas:re.map(i=>i.sha)});e.push&&(f=void 0,await Et(r,e.remote??"origin",y,we)||n("story-worktree-wave-remote-head-mismatch")),f=void 0;const Xe=[];for(const[i,s]of re.entries()){const p=i===0?z:re[i-1].sha,I=await Rt({projectRoot:r,storyId:s.storyId,headSha:s.sha,coverage:Ve,authorities:Ue,expectedLease:h,physicalLock:A,authorizedWriteSet:d.get(s.storyId).authorizedWriteSet,expectedGraphRevision:Z.get(s.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||n(I.reasonCode),(I.value.headSha!==s.sha||I.value.baseSha!==p)&&n("story-worktree-integration-checkpoint-mismatch");const O=await De({projectRoot:r,epicId:g,storyId:s.storyId,executionBranch:y,before:p,after:s.sha,checkpointDigest:Le(I.value),outcome:"integrated",integratedAt:b,expectedEpicHead:we});Xe.push(s.storyId),x.set(s.storyId,Object.freeze({storyId:s.storyId,outcome:"integrated",checkpointHeadSha:s.sha,receiptDigest:ze(O)})),await e.afterWaveStoryPersist?.(s.storyId)}if(U&&he===void 0){const i=U,s=await V(r,{required:!0}),p=await Fe({projectRoot:r,epicId:g,storyId:i.storyId,executionBranch:y,epicHead:we,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:b,chain:X(s,g).filter(I=>I.storyId===i.storyId).sort((I,O)=>O.integrationIndex-I.integrationIndex),lockHeld:!0});p.ok||n(p.reasonCode),x.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:p.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])}))}for(const i of re){if(!i.leaseId)continue;const s=await qe(r,i.leaseId,i.sha);x.set(i.storyId,Object.freeze({...x.get(i.storyId),worktreeRealigned:s}))}return q({outcome:he!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Xe),...he!==void 0?{failedStoryId:m[he].storyId,failureReasonCode:ye}:{},epicHeadBeforeSha:S,epicHeadAfterSha:we,qaCoverage:Ve,gateRunCap:K})}catch(l){let d=l instanceof Ce?l.reasonCode:l instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(l.message)?l.message:"story-worktree-integration-failed";if(f){const u=f,g=(await P(r,["rev-parse",u.epicRef])).stdout.trim(),y=(await P(r,["rev-parse","HEAD"])).stdout.trim();g!==u.base&&(g!==y||!u.owned.has(g)||!await _(r,["reset","--keep",u.base]))&&(d="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:d,gateRuns:o}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const l=a;await pe(r,d=>{const u=Ee(d,c),g=u.branch_lease;g&&g.sessionId===l.sessionId&&g.idempotencyKey===l.idempotencyKey&&g.acquiredAt===l.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function hr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(d=>typeof d!="string"||!_e.test(d)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??Ft,c=new Set(e.readyStoryIds),o=Re(e.projectRoot);let f;try{const d=await V(o,{required:!0}),u=new Set(t.map(g=>g.split(".")[0]));f=new Set([...u].flatMap(g=>X(d,g)).filter(g=>g.outcome==="integrated").map(g=>g.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const r=[],l=[];for(const d of t){if(f.has(d))continue;if(!c.has(d))return{results:r,integratedStoryIds:l,stoppedAt:d,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:g,integrate:y,...b}=e,k=await a({...b,projectRoot:o,storyId:d});if(r.push({storyId:d,result:k}),!k.ok)return{results:r,integratedStoryIds:l,stoppedAt:d,reasonCode:k.reasonCode};if(k.value.outcome==="conflict-reopened")return{results:r,integratedStoryIds:l,stoppedAt:d,reasonCode:"integration-conflict-reopened"};l.push(d),f.add(d)}return{results:r,integratedStoryIds:l}}async function yr(e){const t=Re(e.projectRoot),a=e.manager??new xe({projectRoot:t});let c;try{c=await V(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const o=[];for(const f of e.directives){const r=f&&typeof f=="object"&&!Array.isArray(f)?f:void 0,l=typeof r?.storyId=="string"&&_e.test(r.storyId)?r.storyId:"";if(!l){o.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const d=Object.values(c.storyWorktrees?.entries??{}).filter(g=>g.storyId===l&&g.state==="active");if(d.length!==1){o.push({storyId:l,ok:!1,reasonCode:d.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await a.sync({leaseId:d[0].leaseId,directive:f});o.push(u.ok?{storyId:l,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:l,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return o}export{jt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Lt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,je as STORY_WORKTREE_STATE_JSON_PATH,Ke as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Vt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Ut as STORY_WORKTREE_WAVE_MAX_STORIES,ze as digestStoryWorktreeIntegrationReceipt,Ft as integrateStoryWorktree,gr as integrateStoryWorktreeWave,hr as integrateStoryWorktreesInOrder,Yt as resolveStoryWorktreeStateJsonMerge,Qt as storyWorktreeWaveBuildOutputPaths,Zt as storyWorktreeWaveGateRunCap,yr as syncReleasedDependents};
|
|
1
|
+
import{execFile as tt}from"node:child_process";import{createHash as kt}from"node:crypto";import{readFile as It,realpath as Re}from"node:fs/promises";import{join as vt,resolve as Ee}from"node:path";import{yoloopDomainHash as St}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as rt,directYoloCommitIdempotencyKey as ot,directYoloWaveQaCoverage as bt,finalizeDirectYoloStoryCheckpoint as At,persistDirectYoloWaveStoryCheckpoint as Rt,pushDirectYoloWaveHead as Et,resolveDirectYoloIntegrationAuthority as it,runDirectYoloWaveP205 as xt,validateDirectYoloWriteSet as Ct,verifyDirectYoloIntegrationCommit as nt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as We,appendStoryWorktreeEvidence as _t,applyGitLifecycleRuntimeOverlay as Dt,ensureRuntimeEpic as xe,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as ue,publicStoryReviewArtifactFromBytes as Ot,publicStoryReviewArtifactFromGit as Pt,readGitLifecycleRuntime as Z,readStoryWorktreeEvidence as ze,releaseGitLifecyclePhysicalIntegrationLock as Le,verifyAcceptedGitLifecycleStoryCheckpoint as Ht,verifyGitLifecyclePhysicalIntegrationLock as at}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Bt,STATE_JSON_FIELD_MERGE_MAX_BYTES as Nt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as st,GOVERNANCE_REASON_CODES as ce,readStoryGovernanceSync as Mt,storyReviewGovernancePath as Wt}from"./governance-runtime-store.js";import{StoryWorktreeManager as me}from"./story-worktree-manager.js";import{revalidatePublishedStoryDependencies as zt}from"./published-story-reconciliation.js";import{rootMemoryEffectDigest as Lt}from"../private-execution/root-memory-git-evidence.js";const $t="neocortex.p225.story-worktree-receipt.v1",jt=200,ke="Neocortex-Story-Worktree-Tip",ct=3e4,de=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Gt=/^swt-[a-f0-9]{24}$/,Ce=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function n(e){throw new _e(e)}const dt=32*1024*1024;function P(e,t,a){return new Promise(c=>{tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,f)=>{const o=r?typeof r.code=="number"?r.code:128:0;c({code:o,stdout:String(f??"")})})})}function ft(e,t,a){return new Promise(c=>{const r=tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(f,o)=>{const l=f?typeof f.code=="number"?f.code:128:0;c({code:l,stdout:String(o??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(a)})}async function w(e,t,a,c){const r=await P(e,t,c);return r.code!==0&&n(a),r.stdout.trim()}async function E(e,t){return(await P(e,t)).code===0}function fe(e){return kt("sha256").update(e).digest("hex")}function lt(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function M(e,t){const a=`${t}: `,c=e.split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r.startsWith(a));return c.length===1?c[0].slice(a.length):void 0}function $e(e){return St($t,e)}function ee(e,t){return(ze(e,t)?.receipts??[]).filter(Tt)}function Ie(e){const t=[...e].sort((a,c)=>a.integrationIndex-c.integrationIndex);t.forEach((a,c)=>{(a.integrationIndex!==c+1||c>0&&a.epicHeadBeforeSha!==t[c-1].epicHeadAfterSha)&&n("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((c,r)=>r.integrationIndex-c.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&n("story-worktree-integration-chain-invalid")}const qt=new Set(["done","merged","completed","released"]);function gt(e,t,a,c,r,f,o=new Set){(ze(e,a)?.receipts??[]).some(g=>g.kind==="phase-one-receipt"&&g.storyId===c||g.kind==="spec-barrier-receipt"&&Array.isArray(g.storyIds)&&g.storyIds.includes(c))||n("story-worktree-integration-unbound");const y=new Set(ee(e,a).filter(g=>g.outcome==="integrated").map(g=>g.storyId));for(const g of r){if(!g.startsWith(`${a}.`))continue;const b=t[g],k=!!e.stories[g]?.checkpoint||typeof b?.status=="string"&&qt.has(b.status);!y.has(g)&&!o.has(g)&&!f.has(g)&&!k&&n("story-worktree-integration-dependency-waiting")}}async function ht(e,t,a){if(!(ze(t,a)?.receipts??[]).some(f=>f.kind==="published-story-reconciliation"))return new Set;const r=await zt(e,a);return new Set(r.map(f=>f.storyId))}function Ft(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${fe(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function je(e){return fe(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function De(e){let t;return await ue(e.projectRoot,a=>{const c=ee(a,e.epicId);Ie(c);const r=[...c].sort((o,l)=>l.integrationIndex-o.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&n("story-worktree-integration-chain-invalid"),[...c].filter(o=>o.storyId===e.storyId).sort((o,l)=>l.integrationIndex-o.integrationIndex)[0]?.outcome==="integrated"&&n("story-worktree-integration-already-integrated"),t=Ft({epicId:e.epicId,storyId:e.storyId,index:c.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),_t(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await w(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&n("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await E(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&n("story-worktree-integration-epic-head-raced")}}),t}function ve(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:$e(e.receipt)})}}async function Kt(e){let t,a,c="";const r=Ee(e.projectRoot);try{if((typeof e.storyId!="string"||!Ce.test(e.storyId))&&n("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Gt.test(e.leaseId)&&n("story-worktree-integration-lease-invalid"),!e.allowLinkedEpicCheckout){const h=await Re(await w(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),A=await Re(await w(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));h!==A&&n("story-worktree-integration-not-root")}let f;try{f=await it(r,e.storyId)}catch(h){n(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:o,executionBranch:l,storyId:d}=f;c=o;const u=new Date(e.nowIso??Date.now()).toISOString(),y=`refs/heads/${l}`,g=await w(r,["rev-parse",y],"story-worktree-integration-epic-branch-missing");(await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==g||e.allowLinkedEpicCheckout&&await w(r,["symbolic-ref","HEAD"],"story-worktree-integration-root-head-mismatch")!==y)&&n("story-worktree-integration-root-head-mismatch");const b=f.originBinding;(!b||!await E(r,["merge-base","--is-ancestor",b.originHeadSha,g]))&&n("story-worktree-integration-origin-binding-invalid");const k=await Z(r,{required:!0}),S=ee(k,o);Ie(S);const T=S.filter(h=>h.storyId===d).sort((h,A)=>A.integrationIndex-h.integrationIndex),R=k.stories[d]?.checkpoint;if(T[0]?.outcome==="integrated")return ve({storyId:d,epicId:o,outcome:"already-integrated",receipt:T[0],...R?.headSha?{checkpointHeadSha:R.headSha}:{}});const F=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(h=>typeof h=="string"):[],x=await pt(r,k),B=await ht(r,k,o);gt(k,x,o,d,F,B);const _=Object.values(k.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===o&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(R&&typeof R.headSha=="string"){const h=R.headSha,A=await w(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed"),G=M(A,ke);(M(A,"Neocortex-Story")!==d||!G)&&n("story-worktree-integration-checkpoint-not-worktree"),await Ht(r,R,d,o,l,void 0,f.authorizedWriteSet,"scheduling")||n("story-worktree-integration-checkpoint-unverified"),await E(r,["merge-base","--is-ancestor",h,g])||n("story-worktree-integration-epic-head-raced"),_.length!==1&&n(_.length===0?"story-worktree-integration-lease-missing":"story-worktree-integration-lease-ambiguous");const Q=_[0],q=await new me({projectRoot:r}).probe(Q.leaseId);(!q.ok||q.value.ownership!=="proven")&&n("story-worktree-integration-ownership-unproven"),(await w(r,["rev-parse",`refs/heads/${Q.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing")!==G||q.value.headSha!==G||await w(r,["rev-parse",`${h}^{tree}`],"story-worktree-integration-git-failed")!==await w(r,["rev-parse",`${G}^{tree}`],"story-worktree-integration-git-failed"))&&n("story-worktree-integration-checkpoint-mismatch"),le(S,R.baseSha);const He=await ut(r,d,`recover-${h.slice(0,40)}`,()=>De({projectRoot:r,epicId:o,storyId:d,executionBranch:l,before:R.baseSha,after:g,checkpointDigest:je(R),outcome:"integrated",integratedAt:u})),Be=h===g?await Ke(r,Q.leaseId,h):!1;return ve({storyId:d,epicId:o,outcome:"integrated",receipt:He,checkpointHeadSha:h,worktreeRealigned:Be})}const D=Object.values(k.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===o&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));D.length===0&&n("story-worktree-integration-lease-missing"),D.length>1&&n("story-worktree-integration-lease-ambiguous");const C=D[0];C.executionBranch!==l&&n("story-worktree-integration-lease-invalid");const Y=await new me({projectRoot:r}).probe(C.leaseId);(!Y.ok||Y.value.ownership!=="proven")&&n("story-worktree-integration-ownership-unproven"),Y.value.clean!==!0&&n("story-worktree-integration-worktree-dirty");const v=await w(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Y.value.headSha!==v&&n("story-worktree-integration-worktree-dirty");const H=await w(r,["show","--no-patch","--format=%B",g],"story-worktree-integration-git-failed"),z=M(H,ke)===v&&M(H,"Neocortex-Story")===d;let $,N,m,X=!1;if(z){$=await w(r,["rev-parse",`${g}^`],"story-worktree-integration-git-failed"),N=g;const h=M(H,"Neocortex-Bundle-Digest")??"",A=M(H,"Neocortex-Claim-Revision")??"";m=ot({storyId:d,epicId:o,executionBranch:l,baseSha:$,bundleDigest:h,graphRevision:f.graphRevision,claimRevision:A}),le(S,$)}else{le(S,g);const h=await wt(r,f,d,g,v);if(h.kind==="conflict")return await Ye({projectRoot:r,epicId:o,storyId:d,executionBranch:l,epicHead:g,tip:v,conflictPaths:h.conflictPaths,integratedAt:u,chain:T});const A=h.changedPaths;N=h.commitSha,m=h.idempotencyKey,$=g,X=!0,(!await E(r,["diff","--cached","--quiet"])||!await E(r,["diff","--quiet","HEAD","--",...A]))&&n("story-worktree-integration-root-dirty")}const te=await nt(f,d,N);te.ok||n(te.reasonCode);const re=await Z(r,{required:!0}),j=re.epics[o]?.branch_lease,ne=j&&j.ownerStoryId===d&&j.sessionId===m&&j.idempotencyKey===m&&Date.parse(String(j.expiresAt))>Date.now()?j:void 0;j&&!ne&&Date.parse(String(j.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active");const J=ne??{schemaVersion:1,ownerStoryId:d,sessionId:m,idempotencyKey:m,acquiredAt:u,expiresAt:new Date(Date.parse(u)+rt).toISOString()};t=await We(r,{kind:"direct",storyId:d,sessionId:m,idempotencyKey:m,expiresAt:String(J.expiresAt),persistent:!0,createdAt:String(J.acquiredAt)}),t.ok||n(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const U=t;ne||(await ue(r,h=>{const A=xe(h,o),G=A.branch_lease;G&&Date.parse(String(G.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active"),JSON.stringify(A.origin_binding)!==JSON.stringify(b)&&n("story-worktree-integration-origin-binding-invalid"),A.graph_revision!==f.graphRevision&&n("story-worktree-integration-graph-revision-raced"),A.branch_lease=J},{expectedRevision:re.revision,preCommit:async h=>{await at(U.path,U.owner)||n("story-worktree-integration-lock-raced");const A=ee(h,o);Ie(A),le(A,$),await w(r,["rev-parse",y],"story-worktree-integration-epic-branch-missing")!==g&&n("story-worktree-integration-epic-head-raced")}}),a=J),X&&((await w(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==g||await w(r,["rev-parse",y],"story-worktree-integration-git-failed")!==g)&&n("story-worktree-integration-epic-head-raced"),await E(r,["merge","--ff-only","--no-edit",N])||n("story-worktree-integration-ff-refused"),await w(r,["rev-parse",y],"story-worktree-integration-git-failed")!==N&&n("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let oe;const ae=await At({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:f.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await Z(r,{required:!0})).stories[d]?.checkpoint;(!h||h.headSha!==N||h.baseSha!==$)&&n("story-worktree-integration-checkpoint-mismatch"),await e.afterCheckpointPersist?.(),oe=await De({projectRoot:r,epicId:o,storyId:d,executionBranch:l,before:$,after:N,checkpointDigest:je(h),outcome:"integrated",integratedAt:u})}});if(!ae.ok)return{ok:!1,reasonCode:ae.reasonCode};const L=ae.value;(L.headSha!==N||L.baseSha!==$||!oe)&&n("story-worktree-integration-checkpoint-mismatch");const ge=await Ke(r,C.leaseId,N);return ve({storyId:d,epicId:o,outcome:"integrated",receipt:oe,checkpointHeadSha:N,worktreeRealigned:ge})}catch(f){if(f instanceof _e)return{ok:!1,reasonCode:f.reasonCode};const o=f instanceof Error?f.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(o)?{ok:!1,reasonCode:o}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await Le(t.path,t.owner).catch(()=>{}),a&&c){const f=a;await ue(r,o=>{const l=xe(o,c),d=l.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(l.branch_lease=null)}).catch(()=>{})}}}const Ge=".neocortex/state.json",Te=".neocortex",Oe="state.json",W="story-worktree-integration-state-merge-git-failed";function Pe(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const c=a.indexOf(" "),[r,f,o]=a.slice(0,c).split(" ");(c<0||!r||!f||!o)&&n(W),t.push({mode:r,type:f,oid:o,name:a.slice(c+1)})}return t}function Yt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function yt(e,t,a,c){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&n(W);const f=Pe(r.stdout).filter(d=>d.name!==a),o=await ft(e,["mktree","-z"],Yt([...f,c])),l=o.stdout.trim();return(o.code!==0||!de.test(l))&&n(W),l}async function qe(e,t){const a=await P(e,["ls-tree","-z",t,"--",Ge]);a.code!==0&&n(W);const c=Pe(a.stdout).find(r=>r.name===Ge);return c?((c.type!=="blob"||c.mode!=="100644"&&c.mode!=="100755")&&n("state-merge-input-invalid"),de.test(c.oid)||n(W),c.oid):null}async function Fe(e,t){t===null&&n("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),c=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(c)||c<0||c>Nt)&&n(W);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&n(W),r.stdout}async function Jt(e){try{const{projectRoot:t,mergeBase:a,epicHead:c,tip:r,tree:f,storyId:o,epicId:l}=e,d={ok:!0,tree:f,conflictPaths:[...e.conflictPaths],merged:!1},u=await qe(t,a),y=await qe(t,r);if(u===y)return d;const g=await Fe(t,u),b=await Fe(t,await qe(t,c)),k=await Fe(t,y),S=await w(t,["show","--no-patch","--format=%cI",r],W),T=Bt({base:g,epic:b,story:k,storyId:o,epicId:l,aggregateTimestamp:S});if(!T.ok)return{ok:!1,reasonCode:T.reasonCode};const R=e.conflictPaths.filter(v=>v!==Ge),F=await P(t,["ls-tree","-z",f,"--",Te]);F.code!==0&&n(W);const x=Pe(F.stdout).find(v=>v.name===Te);if(!x||x.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const B=await P(t,["ls-tree","-z",x.oid,"--",Oe]);B.code!==0&&n(W);const _=Pe(B.stdout).find(v=>v.name===Oe);if(_&&(_.type!=="blob"||_.mode!=="100644"&&_.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const D=await ft(t,["hash-object","-w","--stdin"],T.bytes),C=D.stdout.trim();if((D.code!==0||!de.test(C))&&n(W),_?.oid===C)return{ok:!0,tree:f,conflictPaths:R,merged:!0};const K=await yt(t,x.oid,Oe,{mode:_?.mode??"100644",type:"blob",oid:C,name:Oe});return{ok:!0,tree:await yt(t,f,Te,{mode:x.mode,type:"tree",oid:K,name:Te}),conflictPaths:R,merged:!0}}catch(t){return t instanceof _e?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function wt(e,t,a,c,r){const{epicId:f,executionBranch:o}=t;await E(e,["merge-base","--is-ancestor",r,c])&&n("story-worktree-integration-range-empty");const l=await w(e,["merge-base",c,r],"story-worktree-integration-unrelated-history"),d=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${l}`,c,r]);d.code!==0&&d.code!==1&&n("story-worktree-integration-git-unsupported");const u=d.stdout.split("\0"),y=u[0]?.trim()??"";de.test(y)||n("story-worktree-integration-git-unsupported");const g=d.code===1?[...new Set(u.slice(1).filter(lt))].sort():[];d.code===1&&g.length===0&&n("story-worktree-integration-git-failed");const b=await Jt({projectRoot:e,mergeBase:l,epicHead:c,tip:r,tree:y,storyId:a,epicId:f,conflictPaths:g});b.ok||n(b.reasonCode);const k=b.tree;if(b.conflictPaths.length>0)return{kind:"conflict",conflictPaths:b.conflictPaths.slice(0,jt)};const S=(await w(e,["diff","--name-only","-z",c,k],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),T=Ct(S,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);T.ok||n(T.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":T.reasonCode===ce.WRITE_SET_FORBIDDEN?ce.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const R=t.governanceMode==="runtime-store"?await Ut(e,f,a,r):void 0,F=R?R.review:Pt(e,a,k);F?.verdict!=="approved"&&n("story-worktree-integration-review-not-approved");const x=await P(e,["diff","--binary","--full-index",c,k]);x.code!==0&&n("story-worktree-integration-git-failed");const B=x.stdout;B||n("story-worktree-integration-range-empty");const _=fe(B),D=fe([...t.authorizedWriteSet].sort().join("\0")),C=ot({storyId:a,epicId:f,executionBranch:o,baseSha:c,bundleDigest:_,graphRevision:t.graphRevision,claimRevision:D}),K=(await w(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,Y=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${f}`,`Neocortex-Execution-Branch: ${o}`,`Neocortex-Prepared-Base: ${c}`,`Neocortex-Bundle-Digest: ${_}`,`Neocortex-Review-Artifact-Digest: ${F.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${D}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Lt(t.rootMemoryEffect)}`]:[],...R?[`${st}: ${R.governanceDigest}`]:[],`${ke}: ${r}`],v=(await w(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");v.length!==6&&n("story-worktree-integration-git-failed");const H=await w(e,["commit-tree",k,"-p",c,"-m",K,"-m",`Story: ${a}`,"-m",Y.join(`
|
|
3
|
+
`)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:v[0],GIT_AUTHOR_EMAIL:v[1],GIT_AUTHOR_DATE:v[2],GIT_COMMITTER_NAME:v[3],GIT_COMMITTER_EMAIL:v[4],GIT_COMMITTER_DATE:v[5]});return de.test(H)||n("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:H,changedPaths:S,idempotencyKey:C}}async function Ut(e,t,a,c){const r=await w(e,["show","--no-patch","--format=%B",c],"story-worktree-integration-git-failed"),f=M(r,st);f===void 0&&n("story-worktree-integration-governance-trailer-missing");const o=Mt({projectRoot:e,epicId:t,storyId:a});o.ok||n(o.reasonCode===ce.UNSAFE?o.reasonCode:ce.MISMATCH);const l=o.value.receipt.governanceDigest;f!==l&&n(ce.MISMATCH);const d=o.value.files.get(Wt(a));return d||n(ce.MISMATCH),{governanceDigest:l,review:Ot(a,d)}}async function pt(e,t){const a=JSON.parse(await It(vt(e,".neocortex","state.json"),"utf8")),r=Dt(a,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function ut(e,t,a,c){const r=await We(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||n(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await c()}finally{await Le(r.path,r.owner).catch(()=>{})}}async function Ke(e,t,a){const c=await new me({projectRoot:e}).probe(t);return!c.ok||c.value.ownership!=="proven"||c.value.clean!==!0?!1:E(c.value.entry.worktreePath,["reset","--keep",a])}async function Ye(e){const t=fe(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return ve({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const c=()=>De({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await c():await ut(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,c);return ve({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Vt=64,Xt="@ornexus/neocortex",Je=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Je)if(!lt(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Qt(e){return E(e,["clean","-X","-f","-q","--",...Je])}async function Zt(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Xt?Je:[]}catch{return[]}}function er(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function hr(e){let t,a,c="",r=0,f;const o=Ee(e.projectRoot);try{const l=e.storyIds;if((!Array.isArray(l)||l.length===0||l.length>Vt||new Set(l).size!==l.length||l.some(i=>typeof i!="string"||!Ce.test(i)))&&n("story-worktree-wave-stories-invalid"),!e.allowLinkedEpicCheckout){const i=await Re(await w(o,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),s=await Re(await w(o,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));i!==s&&n("story-worktree-integration-not-root")}const d=new Map;for(const i of l)try{d.set(i,await it(o,i))}catch(s){n(s instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(s.message)?s.message:"story-worktree-integration-authority-invalid")}const u=d.get(l[0]),{epicId:y,executionBranch:g}=u;for(const i of d.values())(i.epicId!==y||i.executionBranch!==g||i.graphRevision!==u.graphRevision||JSON.stringify(i.originBinding)!==JSON.stringify(u.originBinding))&&n("story-worktree-wave-epic-mixed");c=y;const b=new Date(e.nowIso??Date.now()).toISOString(),k=`refs/heads/${g}`,S=await w(o,["rev-parse",k],"story-worktree-integration-epic-branch-missing");(await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await w(o,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==g)&&n("story-worktree-integration-root-head-mismatch");const T=u.originBinding;(!T||!await E(o,["merge-base","--is-ancestor",T.originHeadSha,S]))&&n("story-worktree-integration-origin-binding-invalid");const R=i=>{const s=d.get(i).story;return Array.isArray(s.depends_on)?s.depends_on.filter(p=>typeof p=="string"):[]},F=new Map(l.map((i,s)=>[i,s]));l.forEach((i,s)=>{for(const p of R(i)){const I=F.get(p);I!==void 0&&I>=s&&n("story-worktree-wave-order-invalid")}});const x=await Z(o,{required:!0}),B=ee(x,y);Ie(B);const _=i=>B.filter(s=>s.storyId===i).sort((s,p)=>p.integrationIndex-s.integrationIndex)[0],D=l.filter(i=>_(i)?.outcome!=="integrated"),C=new Map(l.filter(i=>!D.includes(i)).map(i=>{const s=_(i),p=x.stories[i]?.checkpoint;return[i,Object.freeze({storyId:i,outcome:"already-integrated",receiptDigest:$e(s),...p?.headSha?{checkpointHeadSha:p.headSha}:{}})]})),K=i=>({ok:!0,value:Object.freeze({epicId:y,...i,gateRuns:r,stories:Object.freeze(l.map(s=>C.get(s)??Object.freeze({storyId:s,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(D.length===0)return K({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const Y=new Set(D),v=[];let H=S;for(let i=0;i<D.length;i++){const s=await w(o,["show","--no-patch","--format=%B",H],"story-worktree-integration-git-failed"),p=M(s,"Neocortex-Story");if(!p||!Y.has(p)||!M(s,ke))break;v.unshift(H),H=await w(o,["rev-parse",`${H}^`],"story-worktree-integration-git-failed")}const z=H;le(B,z);const $=await pt(o,x),N=await ht(o,x,y),m=[];let X,te=z;for(const[i,s]of D.entries()){const p=d.get(s);gt(x,$,y,s,R(s),N,new Set(D.slice(0,i)));const I=Object.values(x.storyWorktrees?.entries??{}).filter(V=>V.storyId===s&&V.epicId===y&&V.state==="active"),O=x.stories[s]?.checkpoint;if(O&&typeof O.headSha=="string"){const V=O.headSha,et=await w(o,["show","--no-patch","--format=%B",V],"story-worktree-integration-git-failed");(M(et,"Neocortex-Story")!==s||!M(et,ke))&&n("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==te||v[i]!==V)&&n("story-worktree-integration-checkpoint-mismatch");const mt=(await w(o,["diff-tree","--no-commit-id","--name-only","-r","-z",V],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);m.push({storyId:s,sha:V,changedPaths:mt,...I.length===1?{leaseId:I[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),te=V;continue}I.length===0&&n("story-worktree-integration-lease-missing"),I.length>1&&n("story-worktree-integration-lease-ambiguous");const be=I[0];be.executionBranch!==g&&n("story-worktree-integration-lease-invalid");const Ae=await new me({projectRoot:o}).probe(be.leaseId);(!Ae.ok||Ae.value.ownership!=="proven")&&n("story-worktree-integration-ownership-unproven"),Ae.value.clean!==!0&&n("story-worktree-integration-worktree-dirty");const Me=await w(o,["rev-parse",`refs/heads/${be.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ae.value.headSha!==Me&&n("story-worktree-integration-worktree-dirty");const se=await wt(o,p,s,te,Me);if(se.kind==="conflict"){i<v.length&&n("story-worktree-wave-resume-mismatch"),X={storyId:s,tip:Me,conflictPaths:se.conflictPaths};break}i<v.length&&v[i]!==se.commitSha&&n("story-worktree-wave-resume-mismatch"),m.push({storyId:s,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:be.leaseId}),te=se.commitSha}if(m.length<v.length&&n("story-worktree-wave-resume-mismatch"),m.length===0){const i=X,s=await Ye({projectRoot:o,epicId:y,storyId:i.storyId,executionBranch:g,epicHead:S,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:b,chain:B.filter(p=>p.storyId===i.storyId).sort((p,I)=>I.integrationIndex-p.integrationIndex)});return s.ok?(C.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:s.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])})),K({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:s.reasonCode,gateRuns:r}}const re=new Map;for(const i of m){if(i.checkpointGraphRevision!==void 0){const p=await w(o,["show","--no-patch","--format=%B",i.sha],"story-worktree-integration-git-failed"),I=M(p,"Neocortex-Graph-Revision");I===void 0&&n("direct-yolo-trailer-missing:neocortex-graph-revision"),I!==i.checkpointGraphRevision&&n("direct-yolo-trailer-mismatch:neocortex-graph-revision"),re.set(i.sha,I);continue}const s=await nt(d.get(i.storyId),i.storyId,i.sha);s.ok||n(s.reasonCode),re.set(i.sha,s.value.graphRevision)}const j=m[m.length-1].sha,ne=[...new Set(m.flatMap(i=>i.changedPaths))].sort();(!await E(o,["diff","--cached","--quiet"])||!await E(o,["diff","--quiet","HEAD","--",...ne]))&&n("story-worktree-integration-root-dirty");const J=er(m.length),U=fe(["p205-wave-lease-v1",y,g,z,...m.map(i=>i.sha)].join("\0")),oe=m[0].storyId,ae=await Z(o,{required:!0}),L=ae.epics[y]?.branch_lease,ge=L&&L.ownerStoryId===oe&&L.sessionId===U&&L.idempotencyKey===U&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!ge&&Date.parse(String(L.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active");const h=ge??{schemaVersion:1,ownerStoryId:oe,sessionId:U,idempotencyKey:U,acquiredAt:b,expiresAt:new Date(Date.parse(b)+rt*J).toISOString()};t=await We(o,{kind:"direct",storyId:oe,sessionId:U,idempotencyKey:U,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||n(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const A=t;ge||await ue(o,i=>{const s=xe(i,y),p=s.branch_lease;p&&Date.parse(String(p.expiresAt))>Date.now()&&n("story-worktree-integration-writer-active"),JSON.stringify(s.origin_binding)!==JSON.stringify(T)&&n("story-worktree-integration-origin-binding-invalid"),s.graph_revision!==u.graphRevision&&n("story-worktree-integration-graph-revision-raced"),s.branch_lease=h},{expectedRevision:ae.revision,preCommit:async i=>{await at(A.path,A.owner)||n("story-worktree-integration-lock-raced");const s=ee(i,y);Ie(s),le(s,z),await w(o,["rev-parse",k],"story-worktree-integration-epic-branch-missing")!==S&&n("story-worktree-integration-epic-head-raced")}}),a=h;const G=new Set(m.map(i=>i.sha));let Q=!0;if(e.push&&v.length>0){const i=(await P(o,["ls-remote","--heads",e.remote??"origin",k])).stdout.split(/\s+/)[0]??"";de.test(i)&&await E(o,["merge-base","--is-ancestor",v[0],i])&&(Q=!1)}let q=S;const he=async i=>{if((await w(o,["rev-parse",k],"story-worktree-integration-git-failed")!==q||await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==q||await w(o,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==g)&&n("story-worktree-integration-epic-head-raced"),q===i)return;const s=await E(o,["merge-base","--is-ancestor",q,i]);!s&&(!Q||!G.has(q))&&n("story-worktree-wave-pushed-immovable"),(!(s?await E(o,["merge","--ff-only","--no-edit",i]):await E(o,["reset","--keep",i]))||await w(o,["rev-parse",k],"story-worktree-integration-git-failed")!==i||await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==i)&&n("story-worktree-integration-ff-refused"),q=i};f=Q?{epicRef:k,base:z,owned:G}:void 0,await he(j),await e.afterWaveFastForward?.();const He=[...new Set(m.map(i=>re.get(i.sha)))],Be=await Zt(o,z),Ne=async()=>{Be.length!==0&&(await(e.cleanBuildOutputs??Qt)(o)||n("story-worktree-wave-clean-failed"))},Ue=async i=>{const s=m[i];await he(s.sha),r>=J&&n("story-worktree-wave-gate-cap-exceeded"),r>0&&await Ne(),r++;const p=await xt({projectRoot:o,headSha:s.sha,storyId:s.storyId,graphRevisions:He,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==s.sha||await w(o,["rev-parse",k],"story-worktree-integration-git-failed")!==s.sha||!await E(o,["diff","--cached","--quiet"])||!await E(o,["diff","--quiet","HEAD","--",...ne]))&&n("story-worktree-integration-epic-head-raced"),!p.ok&&p.kind==="infrastructure"&&n(p.reasonCode),p},Se=await Ue(m.length-1);let Ve=m.length-1,Xe=Se.ok?Se.authorities:void 0,ye,we;if(!Se.ok){Q||n("story-worktree-wave-gate-failed-pushed");let i=-1,s=m.length-1;for(we=Se.reasonCode;s-i>1;){const I=Math.floor((i+s)/2),O=await Ue(I);O.ok?(i=I,Xe=O.authorities):(s=I,we=O.reasonCode)}ye=s,Ve=i;const p=m[s].storyId;if(C.set(p,Object.freeze({storyId:p,outcome:"gate-failed",reasonCode:we})),i<0)return await he(z),await Ne(),f=void 0,K({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:p,failureReasonCode:we,epicHeadBeforeSha:S,epicHeadAfterSha:z,gateRunCap:J});await he(m[i].sha),await Ne()}const ie=m.slice(0,Ve+1),pe=ie[ie.length-1].sha,Qe=bt({epicId:y,executionBranch:g,waveHeadSha:pe,waveStoryIds:ie.map(i=>i.storyId),waveCommitShas:ie.map(i=>i.sha)});e.push&&(f=void 0,await Et(o,e.remote??"origin",g,pe)||n("story-worktree-wave-remote-head-mismatch")),f=void 0;const Ze=[];for(const[i,s]of ie.entries()){const p=i===0?z:ie[i-1].sha,I=await Rt({projectRoot:o,storyId:s.storyId,headSha:s.sha,coverage:Qe,authorities:Xe,expectedLease:h,physicalLock:A,authorizedWriteSet:d.get(s.storyId).authorizedWriteSet,expectedGraphRevision:re.get(s.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||n(I.reasonCode),(I.value.headSha!==s.sha||I.value.baseSha!==p)&&n("story-worktree-integration-checkpoint-mismatch");const O=await De({projectRoot:o,epicId:y,storyId:s.storyId,executionBranch:g,before:p,after:s.sha,checkpointDigest:je(I.value),outcome:"integrated",integratedAt:b,expectedEpicHead:pe});Ze.push(s.storyId),C.set(s.storyId,Object.freeze({storyId:s.storyId,outcome:"integrated",checkpointHeadSha:s.sha,receiptDigest:$e(O)})),await e.afterWaveStoryPersist?.(s.storyId)}if(X&&ye===void 0){const i=X,s=await Z(o,{required:!0}),p=await Ye({projectRoot:o,epicId:y,storyId:i.storyId,executionBranch:g,epicHead:pe,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:b,chain:ee(s,y).filter(I=>I.storyId===i.storyId).sort((I,O)=>O.integrationIndex-I.integrationIndex),lockHeld:!0});p.ok||n(p.reasonCode),C.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:p.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])}))}for(const i of ie){if(!i.leaseId)continue;const s=await Ke(o,i.leaseId,i.sha);C.set(i.storyId,Object.freeze({...C.get(i.storyId),worktreeRealigned:s}))}return K({outcome:ye!==void 0?"gate-failed":X?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ze),...ye!==void 0?{failedStoryId:m[ye].storyId,failureReasonCode:we}:{},epicHeadBeforeSha:S,epicHeadAfterSha:pe,qaCoverage:Qe,gateRunCap:J})}catch(l){let d=l instanceof _e?l.reasonCode:l instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(l.message)?l.message:"story-worktree-integration-failed";if(f){const u=f,y=(await P(o,["rev-parse",u.epicRef])).stdout.trim(),g=(await P(o,["rev-parse","HEAD"])).stdout.trim();y!==u.base&&(y!==g||!u.owned.has(y)||!await E(o,["reset","--keep",u.base]))&&(d="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:d,gateRuns:r}}finally{if(t?.ok&&await Le(t.path,t.owner).catch(()=>{}),a&&c){const l=a;await ue(o,d=>{const u=xe(d,c),y=u.branch_lease;y&&y.sessionId===l.sessionId&&y.idempotencyKey===l.idempotencyKey&&y.acquiredAt===l.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function yr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(d=>typeof d!="string"||!Ce.test(d)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??Kt,c=new Set(e.readyStoryIds),r=Ee(e.projectRoot);let f;try{const d=await Z(r,{required:!0}),u=new Set(t.map(y=>y.split(".")[0]));f=new Set([...u].flatMap(y=>ee(d,y)).filter(y=>y.outcome==="integrated").map(y=>y.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const o=[],l=[];for(const d of t){if(f.has(d))continue;if(!c.has(d))return{results:o,integratedStoryIds:l,stoppedAt:d,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:y,integrate:g,...b}=e,k=await a({...b,projectRoot:r,storyId:d});if(o.push({storyId:d,result:k}),!k.ok)return{results:o,integratedStoryIds:l,stoppedAt:d,reasonCode:k.reasonCode};if(k.value.outcome==="conflict-reopened")return{results:o,integratedStoryIds:l,stoppedAt:d,reasonCode:"integration-conflict-reopened"};l.push(d),f.add(d)}return{results:o,integratedStoryIds:l}}async function wr(e){const t=Ee(e.projectRoot),a=e.manager??new me({projectRoot:t});let c;try{c=await Z(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const f of e.directives){const o=f&&typeof f=="object"&&!Array.isArray(f)?f:void 0,l=typeof o?.storyId=="string"&&Ce.test(o.storyId)?o.storyId:"";if(!l){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const d=Object.values(c.storyWorktrees?.entries??{}).filter(y=>y.storyId===l&&y.state==="active");if(d.length!==1){r.push({storyId:l,ok:!1,reasonCode:d.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await a.sync({leaseId:d[0].leaseId,directive:f});r.push(u.ok?{storyId:l,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:l,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{jt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,$t as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,Ge as STORY_WORKTREE_STATE_JSON_PATH,Je as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Xt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Vt as STORY_WORKTREE_WAVE_MAX_STORIES,$e as digestStoryWorktreeIntegrationReceipt,Kt as integrateStoryWorktree,hr as integrateStoryWorktreeWave,yr as integrateStoryWorktreesInOrder,Jt as resolveStoryWorktreeStateJsonMerge,Zt as storyWorktreeWaveBuildOutputPaths,er as storyWorktreeWaveGateRunCap,wr as syncReleasedDependents};
|
|
@@ -148,6 +148,8 @@ export interface RepositoryFacts {
|
|
|
148
148
|
}
|
|
149
149
|
/** Bounded Git execution shared with the P225.06 cleanup module (exit code + stdout only). */
|
|
150
150
|
export declare function runStoryWorktreeGit(cwd: string, args: readonly string[]): Promise<GitOutcome>;
|
|
151
|
+
/** Use Git's three-way result so an unreadable history cannot look divergent. */
|
|
152
|
+
export declare function storyWorktreeBaseAncestry(cwd: string, baseSha: string, headSha: string): Promise<'contained' | 'divergent' | 'unverified'>;
|
|
151
153
|
/** P227.07: `lstat`-based absence classification (never follows symlinks). */
|
|
152
154
|
export declare function storyWorktreePathAbsence(path: string): Promise<StoryWorktreePathAbsence>;
|
|
153
155
|
export interface PorcelainWorktree {
|
|
@@ -239,6 +241,7 @@ export declare class StoryWorktreeManager {
|
|
|
239
241
|
private ownerId;
|
|
240
242
|
private repository;
|
|
241
243
|
private assertAuthorizedBase;
|
|
244
|
+
private assertReusableBase;
|
|
242
245
|
private epicHead;
|
|
243
246
|
private worktreeGitDir;
|
|
244
247
|
private enableWindowsLongPaths;
|