@ornexus/neocortex 4.66.15 → 4.66.17

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.
Files changed (46) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/invoke.d.ts +1 -1
  7. package/packages/client/dist/commands/invoke.js +70 -69
  8. package/packages/client/dist/continuity/sqlite-store.d.ts +2 -0
  9. package/packages/client/dist/continuity/sqlite-store.js +39 -29
  10. package/packages/client/dist/git/git-lifecycle-store.d.ts +1 -1
  11. package/packages/client/dist/git/git-lifecycle-store.js +9 -9
  12. package/packages/client/dist/git/governance-runtime-store.d.ts +1 -0
  13. package/packages/client/dist/git/governance-runtime-store.js +2 -2
  14. package/packages/client/dist/git/story-worktree-integration.d.ts +2 -0
  15. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  16. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  17. package/packages/client/dist/runner/headless/managed-profile.d.ts +6 -1
  18. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  19. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  20. package/packages/client/dist/runner/headless/run-yoloop.d.ts +2 -0
  21. package/packages/client/dist/runner/headless/run-yoloop.js +6 -2
  22. package/packages/client/dist/runner/headless/story-worktree-review.d.ts +18 -0
  23. package/packages/client/dist/runner/headless/story-worktree-review.js +2 -0
  24. package/packages/client/dist/runner/headless/types.d.ts +2 -0
  25. package/packages/client/dist/yoloop/runner-first-use.d.ts +8 -0
  26. package/packages/client/dist/yoloop/runner-first-use.js +5 -0
  27. package/targets-stubs/antigravity/gemini.md +1 -1
  28. package/targets-stubs/antigravity/neocortex.md +1 -1
  29. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  30. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  31. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  32. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  33. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  34. package/targets-stubs/claude-code/neocortex.md +2 -2
  35. package/targets-stubs/codex/AGENTS.md +1 -1
  36. package/targets-stubs/codex/neocortex.toml +1 -1
  37. package/targets-stubs/cursor/agent.md +2 -2
  38. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  39. package/targets-stubs/gemini-cli/agent.md +2 -2
  40. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  41. package/targets-stubs/grok/SKILL.md +1 -1
  42. package/targets-stubs/kimi/neocortex.md +1 -1
  43. package/targets-stubs/openclaw/SKILL.md +1 -1
  44. package/targets-stubs/opencode/neocortex-root.md +2 -2
  45. package/targets-stubs/opencode/neocortex.md +2 -2
  46. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,3 +1,3 @@
1
- import{execFileSync as P}from"node:child_process";import{createHash as ce,randomBytes as J}from"node:crypto";import{closeSync as M,existsSync as l,fsyncSync as x,lstatSync as N,mkdirSync as Y,openSync as b,readFileSync as E,readdirSync as ae,realpathSync as G,renameSync as fe,unlinkSync as D,writeSync as K}from"node:fs";import{isAbsolute as U,join as u,relative as de,resolve as g}from"node:path";import{STORY_CHECKPOINT_TRAILER_KEYS as ue}from"./neocortex-trailers.js";const X="neocortex-governance",Z="v1",W="story-governance-runtime-store",F="project-state.json",R=1024*1024,ye=4*1024*1024,q=4,_=32*1024*1024,I=".neocortex/state.json",le="Neocortex-Governance-Digest",ke=Object.freeze([...ue,le]),k="governance-runtime:",Se="governance-runtime-revision:",n=Object.freeze({AMBIGUOUS:"governance-tracking-ambiguous",UNAVAILABLE:"governance-mode-unavailable",UNSAFE:"governance-runtime-store-unsafe",CONFLICT:"governance-runtime-store-conflict",OVER_LIMIT:"governance-runtime-store-over-limit",MISMATCH:"governance-runtime-evidence-mismatch",EVIDENCE_MISSING:"governance-runtime-evidence-missing",WRITE_SET_FORBIDDEN:"direct-yolo-write-set-governance-forbidden"}),w=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,L=/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/,C=/^[a-f0-9]{64}$/,Ee=".lock",Ie=6e4,Ae=40,ge=25;class O extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new O(e)}function T(e){return Object.freeze([I,`.neocortex/stories/${e}/qa-gate-result.json`,`.neocortex/stories/${e}/validation-evidence.md`,`.neocortex/stories/${e}/review.md`])}function we(e){return`.neocortex/stories/${e}/review.md`}function Le(e){return/^\.neocortex(?:\/|$)/i.test(e)}function p(e,t){return String(P("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:4*1024*1024}))}function Ne(e,t){try{return P("git",[...t],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}function Q(e){try{if(e.storyId!==void 0&&!L.test(e.storyId))return{ok:!1,reasonCode:n.UNAVAILABLE};if(p(e.projectRoot,["rev-parse","--is-inside-work-tree"]).trim()!=="true")return{ok:!1,reasonCode:n.UNAVAILABLE};const t=Ne(e.projectRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]),r=e.storyId?T(e.storyId):[I],o=new Set(p(e.projectRoot,["ls-files","-z","--",...r]).split("\0").filter(Boolean)),c=t?new Set(p(e.projectRoot,["ls-tree","-r","-z","--name-only","HEAD","--",...r]).split("\0").filter(Boolean)):new Set,a=o.has(I),s=c.has(I);return a&&(s||!t)?{ok:!0,mode:"tracked"}:a!==s?{ok:!1,reasonCode:n.AMBIGUOUS}:o.size>0||c.size>0?{ok:!1,reasonCode:n.AMBIGUOUS}:{ok:!0,mode:"runtime-store"}}catch{return{ok:!1,reasonCode:n.UNAVAILABLE}}}async function Ve(e){return Q(e)}function ee(){return process.platform!=="win32"&&typeof process.getuid=="function"}function y(e,t){const r=N(e);r.isSymbolicLink()&&i(n.UNSAFE),(t==="file"?!r.isFile():!r.isDirectory())&&i(n.UNSAFE),ee()&&r.uid!==process.getuid()&&i(n.UNSAFE),ee()&&(r.mode&63)!==0&&i(n.UNSAFE)}function te(e){let t,r;try{r=G(e),t=p(r,["rev-parse","--git-common-dir"]).trim()}catch{i(n.UNAVAILABLE)}const o=U(t)?g(t):g(r,t);let c;try{c=G(o);const s=N(c);(s.isSymbolicLink()||!s.isDirectory())&&i(n.UNSAFE)}catch(s){if(s instanceof O)throw s;i(n.UNAVAILABLE)}c!==o&&i(n.UNSAFE);const a=p(r,["rev-parse","--git-common-dir"]).trim();return(U(a)?g(a):g(r,a))!==o&&i(n.UNSAFE),c}function v(e,t,r){const o=te(e);let c=o;for(const a of[X,Z,...t]){w.test(a)||i(n.UNSAFE);const s=u(c,a);if(!l(s)){let d=!1;try{d=N(s).isSymbolicLink()}catch{}if(d&&i(n.UNSAFE),!r)return;try{Y(s,{mode:448})}catch(S){S.code!=="EEXIST"&&i(n.UNSAFE)}}y(s,"directory"),G(s)!==s&&i(n.UNSAFE);const f=de(o,s);(!f||f.startsWith("..")||U(f))&&i(n.UNSAFE),c=s}return c}function pe(e){if(process.platform==="win32")return;const t=b(e,"r");try{x(t)}finally{M(t)}}function V(e,t,r){const o=u(e,t);(l(o)||h(o))&&y(o,"file");const c=u(e,`.${t}.${process.pid}.${J(6).toString("hex")}.tmp`),a=b(c,"wx",384);try{let s=0;for(;s<r.length;)s+=K(a,r,s,r.length-s);x(a)}finally{M(a)}try{fe(c,o)}catch{try{D(c)}catch{}i(n.UNSAFE)}y(o,"file"),pe(e)}function h(e){try{return N(e).isSymbolicLink()}catch{return!1}}function ve(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function he(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function re(e,t){const r=u(e,Ee),o=J(12).toString("hex");let c;for(let a=0;a<Ae&&c===void 0;a+=1)try{c=b(r,"wx",384),K(c,JSON.stringify({pid:process.pid,token:o,at:Date.now()})),x(c)}catch(s){s.code!=="EEXIST"&&i(n.UNSAFE);try{y(r,"file");const f=JSON.parse(E(r,"utf8"));if(typeof f.pid=="number"&&typeof f.at=="number"&&Date.now()-f.at>Ie&&!he(f.pid)){D(r);continue}}catch(f){if(f instanceof O)throw f}ve(ge)}c===void 0&&i(n.CONFLICT);try{return t()}finally{M(c);try{JSON.parse(E(r,"utf8")).token===o&&D(r)}catch{}}}function m(e){return ce("sha256").update(e).digest("hex")}function oe(e){const t=[...e].sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0).map(r=>({path:r.path,sha256:r.sha256,bytes:r.bytes}));return m(JSON.stringify({domain:"neocortex.p228.governance-runtime-store.v1",entries:t}))}function me(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;const o=e,c=new Set(T(r));return o.schemaVersion===1&&o.kind===W&&o.epicId===t&&o.storyId===r&&Number.isSafeInteger(o.revision)&&o.revision>=1&&typeof o.governanceDigest=="string"&&C.test(o.governanceDigest)&&Array.isArray(o.entries)&&o.entries.length>=1&&o.entries.length<=q&&new Set(o.entries.map(a=>a?.path)).size===o.entries.length&&o.entries.every(a=>{const s=a;return s&&typeof s.path=="string"&&c.has(s.path)&&typeof s.sha256=="string"&&C.test(s.sha256)&&Number.isSafeInteger(s.bytes)&&s.bytes>=0&&s.bytes<=R})}function j(e,t,r){const o=u(e,"governance.json");if(!l(o)&&!h(o))return;y(o,"file");const c=E(o);c.length>R&&i(n.MISMATCH);let a;try{a=JSON.parse(c.toString("utf8"))}catch{i(n.MISMATCH)}return me(a,t,r)||i(n.MISMATCH),a}function ne(e,t){oe(t.entries)!==t.governanceDigest&&i(n.MISMATCH);const r=u(e,"blobs"),o=new Map;try{y(r,"directory")}catch{i(n.MISMATCH)}for(const c of t.entries){const a=u(r,c.sha256);try{y(a,"file")}catch{i(n.MISMATCH)}const s=E(a);(s.length!==c.bytes||m(s)!==c.sha256)&&i(n.MISMATCH),o.set(c.path,s)}return o}function B(e,t){return Object.freeze({schemaVersion:1,mode:"runtime-store",storyId:e.storyId,epicId:e.epicId,revision:e.revision,governanceDigest:e.governanceDigest,entryCount:e.entries.length,...t?{commitSha:t}:{}})}function A(e){try{return{ok:!0,value:e()}}catch(t){return t instanceof O?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:n.UNSAFE}}}function H(e,t){(!w.test(e)||!L.test(t)||!w.test(t))&&i(n.UNSAFE)}function Re(e){return A(()=>{H(e.epicId,e.storyId);const t=T(e.storyId),r=Object.keys(e.files).sort();(r.length===0||r.length>q||r.some(f=>!t.includes(f)))&&i(n.UNSAFE);const o=r.map(f=>{const d=e.files[f];return Buffer.isBuffer(d)?d:Buffer.from(d,"utf8")});(o.some(f=>f.length>R)||o.reduce((f,d)=>f+d.length,0)>ye)&&i(n.OVER_LIMIT);const c=r.map((f,d)=>Object.freeze({path:f,sha256:m(o[d]),bytes:o[d].length})),a=oe(c),s=v(e.projectRoot,[e.epicId,e.storyId],!0);return re(s,()=>{const f=j(s,e.epicId,e.storyId),d=f?.revision??0;if(d!==e.expectedRevision&&i(n.CONFLICT),f&&f.governanceDigest===a)return ne(s,f),B(f);const S=u(s,"blobs");l(S)||(h(S)&&i(n.UNSAFE),Y(S,{mode:448})),y(S,"directory"),c.forEach((se,ie)=>V(S,se.sha256,o[ie]));const $=Object.freeze({...f??{},schemaVersion:1,kind:W,epicId:e.epicId,storyId:e.storyId,revision:d+1,entries:Object.freeze(c),governanceDigest:a});return V(s,"governance.json",Buffer.from(`${JSON.stringify($,null,2)}
1
+ import{execFileSync as P}from"node:child_process";import{createHash as ce,randomBytes as J}from"node:crypto";import{closeSync as M,existsSync as S,fsyncSync as x,lstatSync as N,mkdirSync as Y,openSync as b,readFileSync as E,readdirSync as ae,realpathSync as G,renameSync as fe,unlinkSync as D,writeSync as K}from"node:fs";import{isAbsolute as U,join as u,relative as de,resolve as g}from"node:path";import{STORY_CHECKPOINT_TRAILER_KEYS as ue}from"./neocortex-trailers.js";const X="neocortex-governance",Z="v1",W="story-governance-runtime-store",w="project-state.json",R=1024*1024,ye=4*1024*1024,q=4,_=32*1024*1024,I=".neocortex/state.json",le="Neocortex-Governance-Digest",Fe=Object.freeze([...ue,le]),F="governance-runtime:",Se="governance-runtime-revision:",n=Object.freeze({AMBIGUOUS:"governance-tracking-ambiguous",UNAVAILABLE:"governance-mode-unavailable",UNSAFE:"governance-runtime-store-unsafe",CONFLICT:"governance-runtime-store-conflict",OVER_LIMIT:"governance-runtime-store-over-limit",MISMATCH:"governance-runtime-evidence-mismatch",EVIDENCE_MISSING:"governance-runtime-evidence-missing",WRITE_SET_FORBIDDEN:"direct-yolo-write-set-governance-forbidden"}),k=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,L=/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/,C=/^[a-f0-9]{64}$/,Ee=".lock",Ie=6e4,Ae=40,ge=25;class O extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new O(e)}function T(e){return Object.freeze([I,`.neocortex/stories/${e}/qa-gate-result.json`,`.neocortex/stories/${e}/validation-evidence.md`,`.neocortex/stories/${e}/review.md`])}function ke(e){return`.neocortex/stories/${e}/review.md`}function Le(e){return/^\.neocortex(?:\/|$)/i.test(e)}function p(e,t){return String(P("git",[...t],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:1e4,maxBuffer:4*1024*1024}))}function Ne(e,t){try{return P("git",[...t],{cwd:e,stdio:"ignore",timeout:1e4}),!0}catch{return!1}}function Q(e){try{if(e.storyId!==void 0&&!L.test(e.storyId))return{ok:!1,reasonCode:n.UNAVAILABLE};if(p(e.projectRoot,["rev-parse","--is-inside-work-tree"]).trim()!=="true")return{ok:!1,reasonCode:n.UNAVAILABLE};const t=Ne(e.projectRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]),r=e.storyId?T(e.storyId):[I],o=new Set(p(e.projectRoot,["ls-files","-z","--",...r]).split("\0").filter(Boolean)),c=t?new Set(p(e.projectRoot,["ls-tree","-r","-z","--name-only","HEAD","--",...r]).split("\0").filter(Boolean)):new Set,a=o.has(I),s=c.has(I);return a&&(s||!t)?{ok:!0,mode:"tracked"}:a!==s?{ok:!1,reasonCode:n.AMBIGUOUS}:o.size>0||c.size>0?{ok:!1,reasonCode:n.AMBIGUOUS}:{ok:!0,mode:"runtime-store"}}catch{return{ok:!1,reasonCode:n.UNAVAILABLE}}}async function Ve(e){return Q(e)}function ee(){return process.platform!=="win32"&&typeof process.getuid=="function"}function l(e,t){const r=N(e);r.isSymbolicLink()&&i(n.UNSAFE),(t==="file"?!r.isFile():!r.isDirectory())&&i(n.UNSAFE),ee()&&r.uid!==process.getuid()&&i(n.UNSAFE),ee()&&(r.mode&63)!==0&&i(n.UNSAFE)}function te(e){let t,r;try{r=G(e),t=p(r,["rev-parse","--git-common-dir"]).trim()}catch{i(n.UNAVAILABLE)}const o=U(t)?g(t):g(r,t);let c;try{c=G(o);const s=N(c);(s.isSymbolicLink()||!s.isDirectory())&&i(n.UNSAFE)}catch(s){if(s instanceof O)throw s;i(n.UNAVAILABLE)}c!==o&&i(n.UNSAFE);const a=p(r,["rev-parse","--git-common-dir"]).trim();return(U(a)?g(a):g(r,a))!==o&&i(n.UNSAFE),c}function v(e,t,r){const o=te(e);let c=o;for(const a of[X,Z,...t]){k.test(a)||i(n.UNSAFE);const s=u(c,a);if(!S(s)){let d=!1;try{d=N(s).isSymbolicLink()}catch{}if(d&&i(n.UNSAFE),!r)return;try{Y(s,{mode:448})}catch(y){y.code!=="EEXIST"&&i(n.UNSAFE)}}l(s,"directory"),G(s)!==s&&i(n.UNSAFE);const f=de(o,s);(!f||f.startsWith("..")||U(f))&&i(n.UNSAFE),c=s}return c}function pe(e){if(process.platform==="win32")return;const t=b(e,"r");try{x(t)}finally{M(t)}}function V(e,t,r){const o=u(e,t);(S(o)||h(o))&&l(o,"file");const c=u(e,`.${t}.${process.pid}.${J(6).toString("hex")}.tmp`),a=b(c,"wx",384);try{let s=0;for(;s<r.length;)s+=K(a,r,s,r.length-s);x(a)}finally{M(a)}try{fe(c,o)}catch{try{D(c)}catch{}i(n.UNSAFE)}l(o,"file"),pe(e)}function h(e){try{return N(e).isSymbolicLink()}catch{return!1}}function ve(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function he(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function re(e,t){const r=u(e,Ee),o=J(12).toString("hex");let c;for(let a=0;a<Ae&&c===void 0;a+=1)try{c=b(r,"wx",384),K(c,JSON.stringify({pid:process.pid,token:o,at:Date.now()})),x(c)}catch(s){s.code!=="EEXIST"&&i(n.UNSAFE);try{l(r,"file");const f=JSON.parse(E(r,"utf8"));if(typeof f.pid=="number"&&typeof f.at=="number"&&Date.now()-f.at>Ie&&!he(f.pid)){D(r);continue}}catch(f){if(f instanceof O)throw f}ve(ge)}c===void 0&&i(n.CONFLICT);try{return t()}finally{M(c);try{JSON.parse(E(r,"utf8")).token===o&&D(r)}catch{}}}function m(e){return ce("sha256").update(e).digest("hex")}function oe(e){const t=[...e].sort((r,o)=>r.path<o.path?-1:r.path>o.path?1:0).map(r=>({path:r.path,sha256:r.sha256,bytes:r.bytes}));return m(JSON.stringify({domain:"neocortex.p228.governance-runtime-store.v1",entries:t}))}function me(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;const o=e,c=new Set(T(r));return o.schemaVersion===1&&o.kind===W&&o.epicId===t&&o.storyId===r&&Number.isSafeInteger(o.revision)&&o.revision>=1&&typeof o.governanceDigest=="string"&&C.test(o.governanceDigest)&&Array.isArray(o.entries)&&o.entries.length>=1&&o.entries.length<=q&&new Set(o.entries.map(a=>a?.path)).size===o.entries.length&&o.entries.every(a=>{const s=a;return s&&typeof s.path=="string"&&c.has(s.path)&&typeof s.sha256=="string"&&C.test(s.sha256)&&Number.isSafeInteger(s.bytes)&&s.bytes>=0&&s.bytes<=R})}function j(e,t,r){const o=u(e,"governance.json");if(!S(o)&&!h(o))return;l(o,"file");const c=E(o);c.length>R&&i(n.MISMATCH);let a;try{a=JSON.parse(c.toString("utf8"))}catch{i(n.MISMATCH)}return me(a,t,r)||i(n.MISMATCH),a}function ne(e,t){oe(t.entries)!==t.governanceDigest&&i(n.MISMATCH);const r=u(e,"blobs"),o=new Map;try{l(r,"directory")}catch{i(n.MISMATCH)}for(const c of t.entries){const a=u(r,c.sha256);try{l(a,"file")}catch{i(n.MISMATCH)}const s=E(a);(s.length!==c.bytes||m(s)!==c.sha256)&&i(n.MISMATCH),o.set(c.path,s)}return o}function B(e,t){return Object.freeze({schemaVersion:1,mode:"runtime-store",storyId:e.storyId,epicId:e.epicId,revision:e.revision,governanceDigest:e.governanceDigest,entryCount:e.entries.length,...t?{commitSha:t}:{}})}function A(e){try{return{ok:!0,value:e()}}catch(t){return t instanceof O?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:n.UNSAFE}}}function H(e,t){(!k.test(e)||!L.test(t)||!k.test(t))&&i(n.UNSAFE)}function Re(e){return A(()=>{H(e.epicId,e.storyId);const t=T(e.storyId),r=Object.keys(e.files).sort();(r.length===0||r.length>q||r.some(f=>!t.includes(f)))&&i(n.UNSAFE);const o=r.map(f=>{const d=e.files[f];return Buffer.isBuffer(d)?d:Buffer.from(d,"utf8")});(o.some(f=>f.length>R)||o.reduce((f,d)=>f+d.length,0)>ye)&&i(n.OVER_LIMIT);const c=r.map((f,d)=>Object.freeze({path:f,sha256:m(o[d]),bytes:o[d].length})),a=oe(c),s=v(e.projectRoot,[e.epicId,e.storyId],!0);return re(s,()=>{const f=j(s,e.epicId,e.storyId),d=f?.revision??0;if(d!==e.expectedRevision&&i(n.CONFLICT),f&&f.governanceDigest===a)return ne(s,f),B(f);const y=u(s,"blobs");S(y)||(h(y)&&i(n.UNSAFE),Y(y,{mode:448})),l(y,"directory"),c.forEach((se,ie)=>V(y,se.sha256,o[ie]));const $=Object.freeze({...f??{},schemaVersion:1,kind:W,epicId:e.epicId,storyId:e.storyId,revision:d+1,entries:Object.freeze(c),governanceDigest:a});return V(s,"governance.json",Buffer.from(`${JSON.stringify($,null,2)}
2
2
  `,"utf8")),B($)})})}function _e(e){return A(()=>{H(e.epicId,e.storyId);const t=v(e.projectRoot,[e.epicId,e.storyId],!1);t||i(n.EVIDENCE_MISSING);const r=j(t,e.epicId,e.storyId);r||i(n.EVIDENCE_MISSING);const o=ne(t,r);return Object.freeze({receipt:B(r),files:o})})}function Ce(e){return A(()=>{H(e.epicId,e.storyId);const t=v(e.projectRoot,[e.epicId,e.storyId],!1);return t?j(t,e.epicId,e.storyId)?.revision??0:0})}function je(e){if(typeof e.expectedGovernanceDigest!="string"||!C.test(e.expectedGovernanceDigest))return{ok:!1,reasonCode:n.MISMATCH};const t=_e(e);return t.ok?t.value.receipt.governanceDigest!==e.expectedGovernanceDigest?{ok:!1,reasonCode:n.MISMATCH}:t:{ok:!1,reasonCode:t.reasonCode===n.UNSAFE?t.reasonCode:n.MISMATCH}}function Oe(e,t){return Buffer.from(`${JSON.stringify({storyId:e,entry:t},null,2)}
3
- `,"utf8")}function z(e,t){if(!l(e)&&!h(e))return;const r=N(e);return(r.isSymbolicLink()||!r.isFile())&&i(n.UNSAFE),r.size>t&&i(n.OVER_LIMIT),E(e)}function Te(e){return A(()=>{L.test(e.storyId)||i(n.UNSAFE);const t=g(e.projectRoot),r=z(u(t,I),_);r||i(n.EVIDENCE_MISSING);let o;try{o=JSON.parse(r.toString("utf8"))}catch{i(n.MISMATCH)}const c=o?.stories,a=c&&typeof c=="object"&&!Array.isArray(c)?c[e.storyId]:void 0;(!a||typeof a!="object"||Array.isArray(a))&&i(n.EVIDENCE_MISSING);const s={[I]:Oe(e.storyId,a)};for(const f of T(e.storyId).slice(1)){const d=z(u(t,f),R);d||i(n.EVIDENCE_MISSING),s[f]=d}return Object.freeze(s)})}function Be(e){const t=Te(e);if(!t.ok)return t;const r=Ce(e);return r.ok?Re({...e,expectedRevision:r.value,files:t.value}):r}function He(e){return A(()=>{e.bytes.length>_&&i(n.OVER_LIMIT);try{JSON.parse(e.bytes.toString("utf8"))}catch{i(n.MISMATCH)}const t=v(e.projectRoot,[],!0);return re(t,()=>{const r=u(t,F);return l(r)&&(y(r,"file"),E(r).equals(e.bytes))||V(t,F,e.bytes),m(e.bytes)})})}function Me(e){return A(()=>{const t=v(e,[],!1);if(!t)return;const r=u(t,F);if(!l(r)&&!h(r))return;y(r,"file");const o=E(r);o.length>_&&i(n.OVER_LIMIT);try{JSON.parse(o.toString("utf8"))}catch{i(n.MISMATCH)}return o})}function ze(e){return A(()=>{const t=z(u(g(e),I),_);if(t)return t;const r=Q({projectRoot:e});if(!r.ok||r.mode!=="runtime-store")return;const o=Me(e);return o.ok||i(o.reasonCode),o.value})}function xe(e,t,r){return u(te(e),X,Z,t,r)}function $e(e,t,r){const o=xe(e,t,r);return l(o)?ae(o).sort():[]}function Pe(e){return Object.freeze([`${k}${e.governanceDigest}`,`${Se}${e.revision}`])}function Je(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string"&&r.startsWith(k)).map(r=>r.slice(k.length));return t.length!==1||!C.test(t[0])?t.length===0?void 0:"invalid":t[0]}export{ke as GOVERNANCE_CHECKPOINT_TRAILER_KEYS,le as GOVERNANCE_DIGEST_TRAILER,n as GOVERNANCE_REASON_CODES,k as GOVERNANCE_RECEIPT_REF_PREFIX,Se as GOVERNANCE_REVISION_REF_PREFIX,q as GOVERNANCE_RUNTIME_MAX_ENTRIES,R as GOVERNANCE_RUNTIME_MAX_FILE_BYTES,_ as GOVERNANCE_RUNTIME_MAX_PROJECT_STATE_BYTES,ye as GOVERNANCE_RUNTIME_MAX_STORY_BYTES,F as GOVERNANCE_RUNTIME_PROJECT_STATE_FILE,X as GOVERNANCE_RUNTIME_STORE_DIRECTORY,W as GOVERNANCE_RUNTIME_STORE_KIND,Z as GOVERNANCE_RUNTIME_STORE_VERSION,I as GOVERNANCE_STATE_PATH,Be as captureStoryGovernanceSync,oe as computeGovernanceDigest,Ve as detectGovernanceMode,Q as detectGovernanceModeSync,Je as governanceDigestFromReceiptRefs,Pe as governanceReceiptRefs,xe as governanceStoreDirectoryForTests,Le as isGovernanceRepositoryPath,$e as listGovernanceStoreEntriesForTests,ze as readGovernanceStateSourceSync,Te as readLocalStoryGovernanceSync,Me as readProjectStateMirrorSync,_e as readStoryGovernanceSync,T as storyGovernancePaths,Ce as storyGovernanceRevisionSync,we as storyReviewGovernancePath,Oe as storyStateEntryBytes,je as verifyStoryGovernanceBinding,He as writeProjectStateMirrorSync,Re as writeStoryGovernance};
3
+ `,"utf8")}function z(e,t){if(!S(e)&&!h(e))return;const r=N(e);return(r.isSymbolicLink()||!r.isFile())&&i(n.UNSAFE),r.size>t&&i(n.OVER_LIMIT),E(e)}function Te(e){return A(()=>{L.test(e.storyId)||i(n.UNSAFE);const t=g(e.projectRoot),r=z(u(t,I),_);r||i(n.EVIDENCE_MISSING);let o;try{o=JSON.parse(r.toString("utf8"))}catch{i(n.MISMATCH)}const c=o?.stories,a=c&&typeof c=="object"&&!Array.isArray(c)?c[e.storyId]:void 0;(!a||typeof a!="object"||Array.isArray(a))&&i(n.EVIDENCE_MISSING);const s={[I]:Oe(e.storyId,a)},f=T(e.storyId);for(const d of f.slice(1,e.beforeReview?-1:void 0)){const y=z(u(t,d),R);y||i(n.EVIDENCE_MISSING),s[d]=y}return Object.freeze(s)})}function Be(e){const t=Te(e);if(!t.ok)return t;const r=Ce(e);return r.ok?Re({...e,expectedRevision:r.value,files:t.value}):r}function He(e){return A(()=>{e.bytes.length>_&&i(n.OVER_LIMIT);try{JSON.parse(e.bytes.toString("utf8"))}catch{i(n.MISMATCH)}const t=v(e.projectRoot,[],!0);return re(t,()=>{const r=u(t,w);return S(r)&&(l(r,"file"),E(r).equals(e.bytes))||V(t,w,e.bytes),m(e.bytes)})})}function Me(e){return A(()=>{const t=v(e,[],!1);if(!t)return;const r=u(t,w);if(!S(r)&&!h(r))return;l(r,"file");const o=E(r);o.length>_&&i(n.OVER_LIMIT);try{JSON.parse(o.toString("utf8"))}catch{i(n.MISMATCH)}return o})}function ze(e){return A(()=>{const t=z(u(g(e),I),_);if(t)return t;const r=Q({projectRoot:e});if(!r.ok||r.mode!=="runtime-store")return;const o=Me(e);return o.ok||i(o.reasonCode),o.value})}function xe(e,t,r){return u(te(e),X,Z,t,r)}function $e(e,t,r){const o=xe(e,t,r);return S(o)?ae(o).sort():[]}function Pe(e){return Object.freeze([`${F}${e.governanceDigest}`,`${Se}${e.revision}`])}function Je(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string"&&r.startsWith(F)).map(r=>r.slice(F.length));return t.length!==1||!C.test(t[0])?t.length===0?void 0:"invalid":t[0]}export{Fe as GOVERNANCE_CHECKPOINT_TRAILER_KEYS,le as GOVERNANCE_DIGEST_TRAILER,n as GOVERNANCE_REASON_CODES,F as GOVERNANCE_RECEIPT_REF_PREFIX,Se as GOVERNANCE_REVISION_REF_PREFIX,q as GOVERNANCE_RUNTIME_MAX_ENTRIES,R as GOVERNANCE_RUNTIME_MAX_FILE_BYTES,_ as GOVERNANCE_RUNTIME_MAX_PROJECT_STATE_BYTES,ye as GOVERNANCE_RUNTIME_MAX_STORY_BYTES,w as GOVERNANCE_RUNTIME_PROJECT_STATE_FILE,X as GOVERNANCE_RUNTIME_STORE_DIRECTORY,W as GOVERNANCE_RUNTIME_STORE_KIND,Z as GOVERNANCE_RUNTIME_STORE_VERSION,I as GOVERNANCE_STATE_PATH,Be as captureStoryGovernanceSync,oe as computeGovernanceDigest,Ve as detectGovernanceMode,Q as detectGovernanceModeSync,Je as governanceDigestFromReceiptRefs,Pe as governanceReceiptRefs,xe as governanceStoreDirectoryForTests,Le as isGovernanceRepositoryPath,$e as listGovernanceStoreEntriesForTests,ze as readGovernanceStateSourceSync,Te as readLocalStoryGovernanceSync,Me as readProjectStateMirrorSync,_e as readStoryGovernanceSync,T as storyGovernancePaths,Ce as storyGovernanceRevisionSync,ke as storyReviewGovernancePath,Oe as storyStateEntryBytes,je as verifyStoryGovernanceBinding,He as writeProjectStateMirrorSync,Re as writeStoryGovernance};
@@ -38,6 +38,7 @@ export interface IntegrateStoryWorktreeOptions {
38
38
  readonly projectRoot: string;
39
39
  readonly storyId: string;
40
40
  readonly leaseId?: string;
41
+ readonly allowLinkedEpicCheckout?: boolean;
41
42
  readonly push?: boolean;
42
43
  readonly remote?: string;
43
44
  readonly nowIso?: string;
@@ -136,6 +137,7 @@ export type StoryWorktreeWaveResult = {
136
137
  export interface IntegrateStoryWorktreeWaveOptions {
137
138
  /** Root (main) checkout on `epic/<ID>`. */
138
139
  readonly projectRoot: string;
140
+ readonly allowLinkedEpicCheckout?: boolean;
139
141
  /** Ordered ready stories; dependencies must precede their dependents. */
140
142
  readonly storyIds: readonly string[];
141
143
  readonly push?: boolean;
@@ -1,3 +1,3 @@
1
- import{execFile as tt}from"node:child_process";import{createHash as vt}from"node:crypto";import{readFile as St,realpath as xe}from"node:fs/promises";import{join as bt,resolve as Ee}from"node:path";import{yoloopDomainHash as At}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as rt,directYoloCommitIdempotencyKey as ot,directYoloWaveQaCoverage as Rt,finalizeDirectYoloStoryCheckpoint as xt,persistDirectYoloWaveStoryCheckpoint as Et,pushDirectYoloWaveHead as _t,resolveDirectYoloIntegrationAuthority as it,runDirectYoloWaveP205 as Dt,validateDirectYoloWriteSet as Ct,verifyDirectYoloIntegrationCommit as nt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as We,appendStoryWorktreeEvidence as Tt,applyGitLifecycleRuntimeOverlay as Ot,ensureRuntimeEpic as _e,isStoryWorktreeIntegrationReceiptRecord as Pt,mutateGitLifecycleRuntime as me,publicStoryReviewArtifactFromBytes as Ht,publicStoryReviewArtifactFromGit as Bt,readGitLifecycleRuntime as Q,readStoryWorktreeEvidence as ze,releaseGitLifecyclePhysicalIntegrationLock as je,verifyGitLifecyclePhysicalIntegrationLock as at}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Nt,STATE_JSON_FIELD_MERGE_MAX_BYTES as Mt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as st,GOVERNANCE_REASON_CODES as fe,readStoryGovernanceSync as Wt,storyReviewGovernancePath as zt}from"./governance-runtime-store.js";import{StoryWorktreeManager as De}from"./story-worktree-manager.js";import{revalidatePublishedStoryDependencies as jt}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",Gt=200,ke="Neocortex-Story-Worktree-Tip",ct=3e4,le=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,qt=/^swt-[a-f0-9]{24}$/,Ce=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class Te extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new Te(e)}const dt=32*1024*1024;function P(e,t,a){return new Promise(s=>{tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;s({code:n,stdout:String(g??"")})})})}function ft(e,t,a){return new Promise(s=>{const r=tt("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:dt,timeout:ct,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const d=g?typeof g.code=="number"?g.code:128:0;s({code:d,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(a)})}async function p(e,t,a,s){const r=await P(e,t,s);return r.code!==0&&i(a),r.stdout.trim()}async function _(e,t){return(await P(e,t)).code===0}function ge(e){return vt("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 W(e,t){const a=`${t}: `,s=e.split(`
2
- `).map(r=>r.trim()).filter(r=>r.startsWith(a));return s.length===1?s[0].slice(a.length):void 0}function Le(e){return At($t,e)}function Z(e,t){return(ze(e,t)?.receipts??[]).filter(Pt)}function Ie(e){const t=[...e].sort((a,s)=>a.integrationIndex-s.integrationIndex);t.forEach((a,s)=>{(a.integrationIndex!==s+1||s>0&&a.epicHeadBeforeSha!==t[s-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function he(e,t){const a=[...e].sort((s,r)=>r.integrationIndex-s.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const Ft=new Set(["done","merged","completed","released"]);function gt(e,t,a,s,r,g,n=new Set){(ze(e,a)?.receipts??[]).some(u=>u.kind==="phase-one-receipt"&&u.storyId===s||u.kind==="spec-barrier-receipt"&&Array.isArray(u.storyIds)&&u.storyIds.includes(s))||i("story-worktree-integration-unbound");const l=new Set(Z(e,a).filter(u=>u.outcome==="integrated").map(u=>u.storyId));for(const u of r){if(!u.startsWith(`${a}.`))continue;const m=t[u],y=!!e.stories[u]?.checkpoint||typeof m?.status=="string"&&Ft.has(m.status);!l.has(u)&&!n.has(u)&&!g.has(u)&&!y&&i("story-worktree-integration-dependency-waiting")}}async function ht(e,t,a){if(!(ze(t,a)?.receipts??[]).some(g=>g.kind==="published-story-reconciliation"))return new Set;const r=await jt(e,a);return new Set(r.map(g=>g.storyId))}function Kt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${ge(["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 $e(e){return ge(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Oe(e){let t;return await me(e.projectRoot,a=>{const s=Z(a,e.epicId);Ie(s);const r=[...s].sort((n,d)=>d.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...s].filter(n=>n.storyId===e.storyId).sort((n,d)=>d.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=Kt({epicId:e.epicId,storyId:e.storyId,index:s.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Tt(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await p(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("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])&&i("story-worktree-integration-epic-head-raced")}}),t}function ve(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:Le(e.receipt)})}}async function Yt(e){let t,a,s="";const r=Ee(e.projectRoot);try{(typeof e.storyId!="string"||!Ce.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!qt.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const g=await xe(await p(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await xe(await p(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&i("story-worktree-integration-not-root");let d;try{d=await it(r,e.storyId)}catch(h){i(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:f,executionBranch:k,storyId:l}=d;s=f;const u=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${k}`,y=await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y&&i("story-worktree-integration-root-head-mismatch");const C=d.originBinding;(!C||!await _(r,["merge-base","--is-ancestor",C.originHeadSha,y]))&&i("story-worktree-integration-origin-binding-invalid");const b=await Q(r,{required:!0}),S=Z(b,f);Ie(S);const H=S.filter(h=>h.storyId===l).sort((h,R)=>R.integrationIndex-h.integrationIndex),A=b.stories[l]?.checkpoint;if(H[0]?.outcome==="integrated")return ve({storyId:l,epicId:f,outcome:"already-integrated",receipt:H[0],...A?.headSha?{checkpointHeadSha:A.headSha}:{}});const K=Array.isArray(d.story.depends_on)?d.story.depends_on.filter(h=>typeof h=="string"):[],x=await pt(r,b),N=await ht(r,b,f);gt(b,x,f,l,K,N);const j=Object.values(b.storyWorktrees?.entries??{}).filter(h=>h.storyId===l&&h.epicId===f&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(A&&typeof A.headSha=="string"){const h=A.headSha,R=await p(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(W(R,"Neocortex-Story")!==l||!W(R,ke))&&i("story-worktree-integration-checkpoint-not-worktree"),h!==y&&i("story-worktree-integration-epic-head-raced"),he(S,A.baseSha);const oe=await ut(r,l,`recover-${h.slice(0,40)}`,()=>Oe({projectRoot:r,epicId:f,storyId:l,executionBranch:k,before:A.baseSha,after:h,checkpointDigest:$e(A),outcome:"integrated",integratedAt:u})),se=j.length===1?await Ke(r,j[0].leaseId,h):!1;return ve({storyId:l,epicId:f,outcome:"integrated",receipt:oe,checkpointHeadSha:h,worktreeRealigned:se})}const T=Object.values(b.storyWorktrees?.entries??{}).filter(h=>h.storyId===l&&h.epicId===f&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));T.length===0&&i("story-worktree-integration-lease-missing"),T.length>1&&i("story-worktree-integration-lease-ambiguous");const D=T[0];D.executionBranch!==k&&i("story-worktree-integration-lease-invalid");const Y=await new De({projectRoot:r}).probe(D.leaseId);(!Y.ok||Y.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Y.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const B=await p(r,["rev-parse",`refs/heads/${D.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Y.value.headSha!==B&&i("story-worktree-integration-worktree-dirty");const G=await p(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed"),L=W(G,ke)===B&&W(G,"Neocortex-Story")===l;let q,M,I,X=!1;if(L){q=await p(r,["rev-parse",`${y}^`],"story-worktree-integration-git-failed"),M=y;const h=W(G,"Neocortex-Bundle-Digest")??"",R=W(G,"Neocortex-Claim-Revision")??"";I=ot({storyId:l,epicId:f,executionBranch:k,baseSha:q,bundleDigest:h,graphRevision:d.graphRevision,claimRevision:R}),he(S,q)}else{he(S,y);const h=await wt(r,d,l,y,B);if(h.kind==="conflict")return await Ye({projectRoot:r,epicId:f,storyId:l,executionBranch:k,epicHead:y,tip:B,conflictPaths:h.conflictPaths,integratedAt:u,chain:H});const R=h.changedPaths;M=h.commitSha,I=h.idempotencyKey,q=y,X=!0,(!await _(r,["diff","--cached","--quiet"])||!await _(r,["diff","--quiet","HEAD","--",...R]))&&i("story-worktree-integration-root-dirty")}const ee=await nt(d,l,M);ee.ok||i(ee.reasonCode);const te=await Q(r,{required:!0}),F=te.epics[f]?.branch_lease,ne=F&&F.ownerStoryId===l&&F.sessionId===I&&F.idempotencyKey===I&&Date.parse(String(F.expiresAt))>Date.now()?F:void 0;F&&!ne&&Date.parse(String(F.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const J=ne??{schemaVersion:1,ownerStoryId:l,sessionId:I,idempotencyKey:I,acquiredAt:u,expiresAt:new Date(Date.parse(u)+rt).toISOString()};t=await We(r,{kind:"direct",storyId:l,sessionId:I,idempotencyKey:I,expiresAt:String(J.expiresAt),persistent:!0,createdAt:String(J.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const U=t;ne||(await me(r,h=>{const R=_e(h,f),oe=R.branch_lease;oe&&Date.parse(String(oe.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(R.origin_binding)!==JSON.stringify(C)&&i("story-worktree-integration-origin-binding-invalid"),R.graph_revision!==d.graphRevision&&i("story-worktree-integration-graph-revision-raced"),R.branch_lease=J},{expectedRevision:te.revision,preCommit:async h=>{await at(U.path,U.owner)||i("story-worktree-integration-lock-raced");const R=Z(h,f);Ie(R),he(R,q),await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==y&&i("story-worktree-integration-epic-head-raced")}}),a=J),X&&((await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==y||await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==y)&&i("story-worktree-integration-epic-head-raced"),await _(r,["merge","--ff-only","--no-edit",M])||i("story-worktree-integration-ff-refused"),await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==M&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let re;const ae=await xt({projectRoot:r,storyId:l,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:d.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await Q(r,{required:!0})).stories[l]?.checkpoint;(!h||h.headSha!==M||h.baseSha!==q)&&i("story-worktree-integration-checkpoint-mismatch"),re=await Oe({projectRoot:r,epicId:f,storyId:l,executionBranch:k,before:q,after:M,checkpointDigest:$e(h),outcome:"integrated",integratedAt:u})}});if(!ae.ok)return{ok:!1,reasonCode:ae.reasonCode};const $=ae.value;($.headSha!==M||$.baseSha!==q||!re)&&i("story-worktree-integration-checkpoint-mismatch");const ye=await Ke(r,D.leaseId,M);return ve({storyId:l,epicId:f,outcome:"integrated",receipt:re,checkpointHeadSha:M,worktreeRealigned:ye})}catch(g){if(g instanceof Te)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),a&&s){const g=a;await me(r,n=>{const d=_e(n,s),f=d.branch_lease;f&&f.sessionId===g.sessionId&&f.idempotencyKey===g.idempotencyKey&&f.acquiredAt===g.acquiredAt&&(d.branch_lease=null)}).catch(()=>{})}}}const Ge=".neocortex/state.json",Pe=".neocortex",He="state.json",z="story-worktree-integration-state-merge-git-failed";function Be(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const s=a.indexOf(" "),[r,g,n]=a.slice(0,s).split(" ");(s<0||!r||!g||!n)&&i(z),t.push({mode:r,type:g,oid:n,name:a.slice(s+1)})}return t}function Jt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function yt(e,t,a,s){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&i(z);const g=Be(r.stdout).filter(f=>f.name!==a),n=await ft(e,["mktree","-z"],Jt([...g,s])),d=n.stdout.trim();return(n.code!==0||!le.test(d))&&i(z),d}async function qe(e,t){const a=await P(e,["ls-tree","-z",t,"--",Ge]);a.code!==0&&i(z);const s=Be(a.stdout).find(r=>r.name===Ge);return s?((s.type!=="blob"||s.mode!=="100644"&&s.mode!=="100755")&&i("state-merge-input-invalid"),le.test(s.oid)||i(z),s.oid):null}async function Fe(e,t){t===null&&i("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),s=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(s)||s<0||s>Mt)&&i(z);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&i(z),r.stdout}async function Ut(e){try{const{projectRoot:t,mergeBase:a,epicHead:s,tip:r,tree:g,storyId:n,epicId:d}=e,f={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},k=await qe(t,a),l=await qe(t,r);if(k===l)return f;const u=await Fe(t,k),m=await Fe(t,await qe(t,s)),y=await Fe(t,l),C=await p(t,["show","--no-patch","--format=%cI",r],z),b=Nt({base:u,epic:m,story:y,storyId:n,epicId:d,aggregateTimestamp:C});if(!b.ok)return{ok:!1,reasonCode:b.reasonCode};const S=e.conflictPaths.filter(E=>E!==Ge),H=await P(t,["ls-tree","-z",g,"--",Pe]);H.code!==0&&i(z);const A=Be(H.stdout).find(E=>E.name===Pe);if(!A||A.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const K=await P(t,["ls-tree","-z",A.oid,"--",He]);K.code!==0&&i(z);const x=Be(K.stdout).find(E=>E.name===He);if(x&&(x.type!=="blob"||x.mode!=="100644"&&x.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const N=await ft(t,["hash-object","-w","--stdin"],b.bytes),j=N.stdout.trim();if((N.code!==0||!le.test(j))&&i(z),x?.oid===j)return{ok:!0,tree:g,conflictPaths:S,merged:!0};const T=await yt(t,A.oid,He,{mode:x?.mode??"100644",type:"blob",oid:j,name:He});return{ok:!0,tree:await yt(t,g,Pe,{mode:A.mode,type:"tree",oid:T,name:Pe}),conflictPaths:S,merged:!0}}catch(t){return t instanceof Te?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:z}}}async function wt(e,t,a,s,r){const{epicId:g,executionBranch:n}=t;await _(e,["merge-base","--is-ancestor",r,s])&&i("story-worktree-integration-range-empty");const d=await p(e,["merge-base",s,r],"story-worktree-integration-unrelated-history"),f=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${d}`,s,r]);f.code!==0&&f.code!==1&&i("story-worktree-integration-git-unsupported");const k=f.stdout.split("\0"),l=k[0]?.trim()??"";le.test(l)||i("story-worktree-integration-git-unsupported");const u=f.code===1?[...new Set(k.slice(1).filter(lt))].sort():[];f.code===1&&u.length===0&&i("story-worktree-integration-git-failed");const m=await Ut({projectRoot:e,mergeBase:d,epicHead:s,tip:r,tree:l,storyId:a,epicId:g,conflictPaths:u});m.ok||i(m.reasonCode);const y=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Gt)};const C=(await p(e,["diff","--name-only","-z",s,y],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),b=Ct(C,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);b.ok||i(b.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":b.reasonCode===fe.WRITE_SET_FORBIDDEN?fe.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const S=t.governanceMode==="runtime-store"?await Vt(e,g,a,r):void 0,H=S?S.review:Bt(e,a,y);H?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const A=await P(e,["diff","--binary","--full-index",s,y]);A.code!==0&&i("story-worktree-integration-git-failed");const K=A.stdout;K||i("story-worktree-integration-range-empty");const x=ge(K),N=ge([...t.authorizedWriteSet].sort().join("\0")),j=ot({storyId:a,epicId:g,executionBranch:n,baseSha:s,bundleDigest:x,graphRevision:t.graphRevision,claimRevision:N}),T=(await p(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,D=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${s}`,`Neocortex-Bundle-Digest: ${x}`,`Neocortex-Review-Artifact-Digest: ${H.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${N}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Lt(t.rootMemoryEffect)}`]:[],...S?[`${st}: ${S.governanceDigest}`]:[],`${ke}: ${r}`],E=(await p(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");E.length!==6&&i("story-worktree-integration-git-failed");const Y=await p(e,["commit-tree",y,"-p",s,"-m",T,"-m",`Story: ${a}`,"-m",D.join(`
3
- `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:E[0],GIT_AUTHOR_EMAIL:E[1],GIT_AUTHOR_DATE:E[2],GIT_COMMITTER_NAME:E[3],GIT_COMMITTER_EMAIL:E[4],GIT_COMMITTER_DATE:E[5]});return le.test(Y)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:Y,changedPaths:C,idempotencyKey:j}}async function Vt(e,t,a,s){const r=await p(e,["show","--no-patch","--format=%B",s],"story-worktree-integration-git-failed"),g=W(r,st);g===void 0&&i("story-worktree-integration-governance-trailer-missing");const n=Wt({projectRoot:e,epicId:t,storyId:a});n.ok||i(n.reasonCode===fe.UNSAFE?n.reasonCode:fe.MISMATCH);const d=n.value.receipt.governanceDigest;g!==d&&i(fe.MISMATCH);const f=n.value.files.get(zt(a));return f||i(fe.MISMATCH),{governanceDigest:d,review:Ht(a,f)}}async function pt(e,t){const a=JSON.parse(await St(bt(e,".neocortex","state.json"),"utf8")),r=Ot(a,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function ut(e,t,a,s){const r=await We(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||i(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await s()}finally{await je(r.path,r.owner).catch(()=>{})}}async function Ke(e,t,a){const s=await new De({projectRoot:e}).probe(t);return!s.ok||s.value.ownership!=="proven"||s.value.clean!==!0?!1:_(s.value.entry.worktreePath,["reset","--keep",a])}async function Ye(e){const t=ge(["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 s=()=>Oe({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 s():await ut(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,s);return ve({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Xt=64,Qt="@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 Zt(e){return _(e,["clean","-X","-f","-q","--",...Je])}async function er(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Qt?Je:[]}catch{return[]}}function tr(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function yr(e){let t,a,s="",r=0,g;const n=Ee(e.projectRoot);try{const d=e.storyIds;(!Array.isArray(d)||d.length===0||d.length>Xt||new Set(d).size!==d.length||d.some(o=>typeof o!="string"||!Ce.test(o)))&&i("story-worktree-wave-stories-invalid");const f=await xe(await p(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),k=await xe(await p(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));f!==k&&i("story-worktree-integration-not-root");const l=new Map;for(const o of d)try{l.set(o,await it(n,o))}catch(c){i(c instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(c.message)?c.message:"story-worktree-integration-authority-invalid")}const u=l.get(d[0]),{epicId:m,executionBranch:y}=u;for(const o of l.values())(o.epicId!==m||o.executionBranch!==y||o.graphRevision!==u.graphRevision||JSON.stringify(o.originBinding)!==JSON.stringify(u.originBinding))&&i("story-worktree-wave-epic-mixed");s=m;const C=new Date(e.nowIso??Date.now()).toISOString(),b=`refs/heads/${y}`,S=await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing");(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==y)&&i("story-worktree-integration-root-head-mismatch");const H=u.originBinding;(!H||!await _(n,["merge-base","--is-ancestor",H.originHeadSha,S]))&&i("story-worktree-integration-origin-binding-invalid");const A=o=>{const c=l.get(o).story;return Array.isArray(c.depends_on)?c.depends_on.filter(w=>typeof w=="string"):[]},K=new Map(d.map((o,c)=>[o,c]));d.forEach((o,c)=>{for(const w of A(o)){const v=K.get(w);v!==void 0&&v>=c&&i("story-worktree-wave-order-invalid")}});const x=await Q(n,{required:!0}),N=Z(x,m);Ie(N);const j=o=>N.filter(c=>c.storyId===o).sort((c,w)=>w.integrationIndex-c.integrationIndex)[0],T=d.filter(o=>j(o)?.outcome!=="integrated"),D=new Map(d.filter(o=>!T.includes(o)).map(o=>{const c=j(o),w=x.stories[o]?.checkpoint;return[o,Object.freeze({storyId:o,outcome:"already-integrated",receiptDigest:Le(c),...w?.headSha?{checkpointHeadSha:w.headSha}:{}})]})),E=o=>({ok:!0,value:Object.freeze({epicId:m,...o,gateRuns:r,stories:Object.freeze(d.map(c=>D.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(T.length===0)return E({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const Y=new Set(T),B=[];let G=S;for(let o=0;o<T.length;o++){const c=await p(n,["show","--no-patch","--format=%B",G],"story-worktree-integration-git-failed"),w=W(c,"Neocortex-Story");if(!w||!Y.has(w)||!W(c,ke))break;B.unshift(G),G=await p(n,["rev-parse",`${G}^`],"story-worktree-integration-git-failed")}const L=G;he(N,L);const q=await pt(n,x),M=await ht(n,x,m),I=[];let X,ee=L;for(const[o,c]of T.entries()){const w=l.get(c);gt(x,q,m,c,A(c),M,new Set(T.slice(0,o)));const v=Object.values(x.storyWorktrees?.entries??{}).filter(V=>V.storyId===c&&V.epicId===m&&V.state==="active"),O=x.stories[c]?.checkpoint;if(O&&typeof O.headSha=="string"){const V=O.headSha,et=await p(n,["show","--no-patch","--format=%B",V],"story-worktree-integration-git-failed");(W(et,"Neocortex-Story")!==c||!W(et,ke))&&i("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==ee||B[o]!==V)&&i("story-worktree-integration-checkpoint-mismatch");const It=(await p(n,["diff-tree","--no-commit-id","--name-only","-r","-z",V],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);I.push({storyId:c,sha:V,changedPaths:It,...v.length===1?{leaseId:v[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),ee=V;continue}v.length===0&&i("story-worktree-integration-lease-missing"),v.length>1&&i("story-worktree-integration-lease-ambiguous");const Ae=v[0];Ae.executionBranch!==y&&i("story-worktree-integration-lease-invalid");const Re=await new De({projectRoot:n}).probe(Ae.leaseId);(!Re.ok||Re.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Re.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const Me=await p(n,["rev-parse",`refs/heads/${Ae.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Re.value.headSha!==Me&&i("story-worktree-integration-worktree-dirty");const de=await wt(n,w,c,ee,Me);if(de.kind==="conflict"){o<B.length&&i("story-worktree-wave-resume-mismatch"),X={storyId:c,tip:Me,conflictPaths:de.conflictPaths};break}o<B.length&&B[o]!==de.commitSha&&i("story-worktree-wave-resume-mismatch"),I.push({storyId:c,sha:de.commitSha,changedPaths:de.changedPaths,leaseId:Ae.leaseId}),ee=de.commitSha}if(I.length<B.length&&i("story-worktree-wave-resume-mismatch"),I.length===0){const o=X,c=await Ye({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:y,epicHead:S,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:C,chain:N.filter(w=>w.storyId===o.storyId).sort((w,v)=>v.integrationIndex-w.integrationIndex)});return c.ok?(D.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])})),E({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const te=new Map;for(const o of I){if(o.checkpointGraphRevision!==void 0){const w=await p(n,["show","--no-patch","--format=%B",o.sha],"story-worktree-integration-git-failed"),v=W(w,"Neocortex-Graph-Revision");v===void 0&&i("direct-yolo-trailer-missing:neocortex-graph-revision"),v!==o.checkpointGraphRevision&&i("direct-yolo-trailer-mismatch:neocortex-graph-revision"),te.set(o.sha,v);continue}const c=await nt(l.get(o.storyId),o.storyId,o.sha);c.ok||i(c.reasonCode),te.set(o.sha,c.value.graphRevision)}const F=I[I.length-1].sha,ne=[...new Set(I.flatMap(o=>o.changedPaths))].sort();(!await _(n,["diff","--cached","--quiet"])||!await _(n,["diff","--quiet","HEAD","--",...ne]))&&i("story-worktree-integration-root-dirty");const J=tr(I.length),U=ge(["p205-wave-lease-v1",m,y,L,...I.map(o=>o.sha)].join("\0")),re=I[0].storyId,ae=await Q(n,{required:!0}),$=ae.epics[m]?.branch_lease,ye=$&&$.ownerStoryId===re&&$.sessionId===U&&$.idempotencyKey===U&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!ye&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const h=ye??{schemaVersion:1,ownerStoryId:re,sessionId:U,idempotencyKey:U,acquiredAt:C,expiresAt:new Date(Date.parse(C)+rt*J).toISOString()};t=await We(n,{kind:"direct",storyId:re,sessionId:U,idempotencyKey:U,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const R=t;ye||await me(n,o=>{const c=_e(o,m),w=c.branch_lease;w&&Date.parse(String(w.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==u.graphRevision&&i("story-worktree-integration-graph-revision-raced"),c.branch_lease=h},{expectedRevision:ae.revision,preCommit:async o=>{await at(R.path,R.owner)||i("story-worktree-integration-lock-raced");const c=Z(o,m);Ie(c),he(c,L),await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing")!==S&&i("story-worktree-integration-epic-head-raced")}}),a=h;const oe=new Set(I.map(o=>o.sha));let se=!0;if(e.push&&B.length>0){const o=(await P(n,["ls-remote","--heads",e.remote??"origin",b])).stdout.split(/\s+/)[0]??"";le.test(o)&&await _(n,["merge-base","--is-ancestor",B[0],o])&&(se=!1)}let ce=S;const Se=async o=>{if((await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==ce||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ce||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==y)&&i("story-worktree-integration-epic-head-raced"),ce===o)return;const c=await _(n,["merge-base","--is-ancestor",ce,o]);!c&&(!se||!oe.has(ce))&&i("story-worktree-wave-pushed-immovable"),(!(c?await _(n,["merge","--ff-only","--no-edit",o]):await _(n,["reset","--keep",o]))||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==o||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==o)&&i("story-worktree-integration-ff-refused"),ce=o};g=se?{epicRef:b,base:L,owned:oe}:void 0,await Se(F),await e.afterWaveFastForward?.();const mt=[...new Set(I.map(o=>te.get(o.sha)))],kt=await er(n,L),Ne=async()=>{kt.length!==0&&(await(e.cleanBuildOutputs??Zt)(n)||i("story-worktree-wave-clean-failed"))},Ue=async o=>{const c=I[o];await Se(c.sha),r>=J&&i("story-worktree-wave-gate-cap-exceeded"),r>0&&await Ne(),r++;const w=await Dt({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:mt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==c.sha||!await _(n,["diff","--cached","--quiet"])||!await _(n,["diff","--quiet","HEAD","--",...ne]))&&i("story-worktree-integration-epic-head-raced"),!w.ok&&w.kind==="infrastructure"&&i(w.reasonCode),w},be=await Ue(I.length-1);let Ve=I.length-1,Xe=be.ok?be.authorities:void 0,we,pe;if(!be.ok){se||i("story-worktree-wave-gate-failed-pushed");let o=-1,c=I.length-1;for(pe=be.reasonCode;c-o>1;){const v=Math.floor((o+c)/2),O=await Ue(v);O.ok?(o=v,Xe=O.authorities):(c=v,pe=O.reasonCode)}we=c,Ve=o;const w=I[c].storyId;if(D.set(w,Object.freeze({storyId:w,outcome:"gate-failed",reasonCode:pe})),o<0)return await Se(L),await Ne(),g=void 0,E({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:w,failureReasonCode:pe,epicHeadBeforeSha:S,epicHeadAfterSha:L,gateRunCap:J});await Se(I[o].sha),await Ne()}const ie=I.slice(0,Ve+1),ue=ie[ie.length-1].sha,Qe=Rt({epicId:m,executionBranch:y,waveHeadSha:ue,waveStoryIds:ie.map(o=>o.storyId),waveCommitShas:ie.map(o=>o.sha)});e.push&&(g=void 0,await _t(n,e.remote??"origin",y,ue)||i("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ze=[];for(const[o,c]of ie.entries()){const w=o===0?L:ie[o-1].sha,v=await Et({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Qe,authorities:Xe,expectedLease:h,physicalLock:R,authorizedWriteSet:l.get(c.storyId).authorizedWriteSet,expectedGraphRevision:te.get(c.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||i(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==w)&&i("story-worktree-integration-checkpoint-mismatch");const O=await Oe({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:y,before:w,after:c.sha,checkpointDigest:$e(v.value),outcome:"integrated",integratedAt:C,expectedEpicHead:ue});Ze.push(c.storyId),D.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:Le(O)})),await e.afterWaveStoryPersist?.(c.storyId)}if(X&&we===void 0){const o=X,c=await Q(n,{required:!0}),w=await Ye({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:y,epicHead:ue,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:C,chain:Z(c,m).filter(v=>v.storyId===o.storyId).sort((v,O)=>O.integrationIndex-v.integrationIndex),lockHeld:!0});w.ok||i(w.reasonCode),D.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:w.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])}))}for(const o of ie){if(!o.leaseId)continue;const c=await Ke(n,o.leaseId,o.sha);D.set(o.storyId,Object.freeze({...D.get(o.storyId),worktreeRealigned:c}))}return E({outcome:we!==void 0?"gate-failed":X?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ze),...we!==void 0?{failedStoryId:I[we].storyId,failureReasonCode:pe}:{},epicHeadBeforeSha:S,epicHeadAfterSha:ue,qaCoverage:Qe,gateRunCap:J})}catch(d){let f=d instanceof Te?d.reasonCode:d instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(d.message)?d.message:"story-worktree-integration-failed";if(g){const k=g,l=(await P(n,["rev-parse",k.epicRef])).stdout.trim(),u=(await P(n,["rev-parse","HEAD"])).stdout.trim();l!==k.base&&(l!==u||!k.owned.has(l)||!await _(n,["reset","--keep",k.base]))&&(f="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:f,gateRuns:r}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),a&&s){const d=a;await me(n,f=>{const k=_e(f,s),l=k.branch_lease;l&&l.sessionId===d.sessionId&&l.idempotencyKey===d.idempotencyKey&&l.acquiredAt===d.acquiredAt&&(k.branch_lease=null)}).catch(()=>{})}}}async function wr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(f=>typeof f!="string"||!Ce.test(f)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??Yt,s=new Set(e.readyStoryIds),r=Ee(e.projectRoot);let g;try{const f=await Q(r,{required:!0}),k=new Set(t.map(l=>l.split(".")[0]));g=new Set([...k].flatMap(l=>Z(f,l)).filter(l=>l.outcome==="integrated").map(l=>l.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],d=[];for(const f of t){if(g.has(f))continue;if(!s.has(f))return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:k,readyStoryIds:l,integrate:u,...m}=e,y=await a({...m,projectRoot:r,storyId:f});if(n.push({storyId:f,result:y}),!y.ok)return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:y.reasonCode};if(y.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:d,stoppedAt:f,reasonCode:"integration-conflict-reopened"};d.push(f),g.add(f)}return{results:n,integratedStoryIds:d}}async function pr(e){const t=Ee(e.projectRoot),a=e.manager??new De({projectRoot:t});let s;try{s=await Q(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const g of e.directives){const n=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0,d=typeof n?.storyId=="string"&&Ce.test(n.storyId)?n.storyId:"";if(!d){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const f=Object.values(s.storyWorktrees?.entries??{}).filter(l=>l.storyId===d&&l.state==="active");if(f.length!==1){r.push({storyId:d,ok:!1,reasonCode:f.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const k=await a.sync({leaseId:f[0].leaseId,directive:g});r.push(k.ok?{storyId:d,ok:!0,outcome:k.value.outcome,integratedSha:k.value.integratedSha}:{storyId:d,ok:!1,reasonCode:k.reasonCode,...k.conflictPaths?{conflictPaths:k.conflictPaths}:{}})}return r}export{Gt 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,Qt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Xt as STORY_WORKTREE_WAVE_MAX_STORIES,Le as digestStoryWorktreeIntegrationReceipt,Yt as integrateStoryWorktree,yr as integrateStoryWorktreeWave,wr as integrateStoryWorktreesInOrder,Ut as resolveStoryWorktreeStateJsonMerge,er as storyWorktreeWaveBuildOutputPaths,tr as storyWorktreeWaveGateRunCap,pr as syncReleasedDependents};
1
+ import{execFile as Ze}from"node:child_process";import{createHash as kt}from"node:crypto";import{readFile as It,realpath as Ae}from"node:fs/promises";import{join as vt,resolve as Re}from"node:path";import{yoloopDomainHash as St}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as et,directYoloCommitIdempotencyKey as tt,directYoloWaveQaCoverage as bt,finalizeDirectYoloStoryCheckpoint as At,persistDirectYoloWaveStoryCheckpoint as Rt,pushDirectYoloWaveHead as Et,resolveDirectYoloIntegrationAuthority as rt,runDirectYoloWaveP205 as xt,validateDirectYoloWriteSet as _t,verifyDirectYoloIntegrationCommit as ot}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Ne,appendStoryWorktreeEvidence as Ct,applyGitLifecycleRuntimeOverlay as Dt,ensureRuntimeEpic as Ee,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as pe,publicStoryReviewArtifactFromBytes as Ot,publicStoryReviewArtifactFromGit as Pt,readGitLifecycleRuntime as V,readStoryWorktreeEvidence as Me,releaseGitLifecyclePhysicalIntegrationLock as We,verifyGitLifecyclePhysicalIntegrationLock as it}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ht,STATE_JSON_FIELD_MERGE_MAX_BYTES as Bt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as nt,GOVERNANCE_REASON_CODES as ce,readStoryGovernanceSync as Nt,storyReviewGovernancePath as Mt}from"./governance-runtime-store.js";import{StoryWorktreeManager as xe}from"./story-worktree-manager.js";import{revalidatePublishedStoryDependencies as Wt}from"./published-story-reconciliation.js";import{rootMemoryEffectDigest as zt}from"../private-execution/root-memory-git-evidence.js";const Lt="neocortex.p225.story-worktree-receipt.v1",jt=200,ue="Neocortex-Story-Worktree-Tip",at=3e4,de=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,$t=/^swt-[a-f0-9]{24}$/,_e=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class Ce extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function n(e){throw new Ce(e)}const st=32*1024*1024;function P(e,t,a){return new Promise(c=>{Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:st,timeout:at,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(o,f)=>{const r=o?typeof o.code=="number"?o.code:128:0;c({code:r,stdout:String(f??"")})})})}function ct(e,t,a){return new Promise(c=>{const o=Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:st,timeout:at,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(f,r)=>{const l=f?typeof f.code=="number"?f.code:128:0;c({code:l,stdout:String(r??"")})});o.stdin?.on("error",()=>{}),o.stdin?.end(a)})}async function w(e,t,a,c){const o=await P(e,t,c);return o.code!==0&&n(a),o.stdout.trim()}async function _(e,t){return(await P(e,t)).code===0}function fe(e){return kt("sha256").update(e).digest("hex")}function dt(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(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 +1 @@
1
- import{createRejectedExecutionResult as l,createUnavailableExecutionResult as I,normalizeHeadlessCommandResult as c,runHeadlessCommand as b,validateHeadlessAdapterExecutionInput as s}from"./types.js";import{checkRuntimeAvailability as h}from"./opencode-adapter.js";import{DEFAULT_HEADLESS_CHILD_PROFILE_NAME as C,governedPreflightFailureResult as E,preflightManagedHeadlessProfile as A,withGovernedHeadlessEvidence as d}from"./managed-profile.js";const a="claude-code",o="claude";function H(){return{id:a,displayName:"Claude Code Headless Adapter",async checkAvailability(i={}){return h(a,o,i,{realpathBasenamePolicy:"claude-code-versioned",versionEvidence:"claude-code"})},buildInvocation(i){const e=s(i,a);return e.ok?{ok:!0,invocation:{adapterId:a,commandName:o,args:p(e.prompt,e.input.modelId,C),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(i,e={}){const t=s(i,a);if(!t.ok)return l(a,a,t);const n=A(a,e);if(!n.ok)return E(a,t.input,n);if(e.signal?.aborted)return d(c(a,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const u=await this.checkAvailability(e);if(!u.ok)return d(I(a,t.input,u));const r=this.buildInvocation(t.input);if(!r.ok)return l(a,a,r);const m=e.commandRunner??b,f=p(t.prompt,t.input.modelId,n.childProfileName),v=await m(u.executablePath??o,f,{cwd:e.cwd,env:e.env,timeoutMs:r.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return d(c(a,t.input,v))}}}function p(i,e,t){const n=["--agent",t];return e&&n.push("--model",e),n.push("-p",i),n}export{H as createClaudeCodeHeadlessAdapter};
1
+ import{createRejectedExecutionResult as l,createUnavailableExecutionResult as I,normalizeHeadlessCommandResult as c,runHeadlessCommand as g,validateHeadlessAdapterExecutionInput as p}from"./types.js";import{checkRuntimeAvailability as E}from"./opencode-adapter.js";import{DEFAULT_HEADLESS_CHILD_PROFILE_NAME as b,governedPreflightFailureResult as A,preflightManagedHeadlessProfile as C,isRunnerWorktreePhase as k,preflightRunnerWorker as y,RUNNER_WORKER_PROFILE as m,runnerWorkerInstructions as w,withGovernedHeadlessEvidence as d}from"./managed-profile.js";const i="claude-code",s="claude";function _(){return{id:i,displayName:"Claude Code Headless Adapter",async checkAvailability(n={}){return E(i,s,n,{realpathBasenamePolicy:"claude-code-versioned",versionEvidence:"claude-code"})},buildInvocation(n){const e=p(n,i);return e.ok?{ok:!0,invocation:{adapterId:i,commandName:s,args:f(e.prompt,e.input.modelId,b),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=p(n,i);if(!t.ok)return l(i,i,t);const a=k(t.input.promptKind),r=a?y(i,e):C(i,e);if(!r.ok)return A(i,t.input,r);if(e.signal?.aborted)return d(c(i,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const u=await this.checkAvailability(e);if(!u.ok)return d(I(i,t.input,u));const o=this.buildInvocation(t.input);if(!o.ok)return l(i,i,o);const v=e.commandRunner??g,h=f(e.runnerReviewTree?"Review the staged candidate.":t.prompt,t.input.modelId,a?m:r.childProfileName,a?w(t.input,e.runnerReviewTree):void 0),R=await v(u.executablePath??s,h,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return d(c(i,t.input,R))}}}function f(n,e,t,a){const r=["--agent",t];return a&&r.push("--agents",JSON.stringify({[m]:{description:"Neocortex story-worktree phase worker",prompt:a}}),"--permission-mode","bypassPermissions","--disallowedTools","Agent,Task","--no-session-persistence"),e&&r.push("--model",e),r.push("-p",n),r}export{_ as createClaudeCodeHeadlessAdapter};
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * P201.12 -- fixed-path managed profile and effective policy preflight.
6
6
  */
7
- import { type HeadlessAdapterExecutionInput, type HeadlessAdapterExecutionOptions, type HeadlessAdapterExecutionResult, type HeadlessReasonCode } from './types.js';
7
+ import { type HeadlessAdapterExecutionInput, type HeadlessPromptKind, type HeadlessAdapterExecutionOptions, type HeadlessAdapterExecutionResult, type HeadlessReasonCode } from './types.js';
8
8
  export declare const GOVERNED_HEADLESS_EVIDENCE: "[P201-EV-HEADLESS]";
9
9
  type GovernedAdapterId = 'claude-code' | 'opencode';
10
10
  /**
@@ -37,6 +37,11 @@ export type ManagedProfilePreflight = {
37
37
  */
38
38
  export declare function classifyProfileRole(content: string): ManagedProfileRole;
39
39
  export declare function preflightManagedHeadlessProfile(adapterId: GovernedAdapterId, options: HeadlessAdapterExecutionOptions): ManagedProfilePreflight;
40
+ export declare const RUNNER_WORKER_PROFILE = "neocortex-yoloop-worker";
41
+ export declare function runnerWorkerInstructions(input: HeadlessAdapterExecutionInput, reviewTree?: string): string;
42
+ export declare function isRunnerWorktreePhase(kind: HeadlessPromptKind): boolean;
43
+ /** A runner-local worker inherits the same managed approval gate as a profile on disk. */
44
+ export declare function preflightRunnerWorker(adapterId: GovernedAdapterId, options: HeadlessAdapterExecutionOptions): ManagedProfilePreflight;
40
45
  export declare function governedPreflightFailureResult(adapterId: GovernedAdapterId, input: HeadlessAdapterExecutionInput, preflight: Extract<ManagedProfilePreflight, {
41
46
  readonly ok: false;
42
47
  }>): HeadlessAdapterExecutionResult;
@@ -1 +1 @@
1
- import{lstatSync as h,readdirSync as y,readFileSync as E}from"node:fs";import{homedir as L}from"node:os";import{basename as O,dirname as I,join as c}from"node:path";import{getSubagentApprovalPolicy as b}from"../../config.js";import{HEADLESS_REASON_CODES as d,boundPublicSummary as g,hashPublicValue as S,redaction as N}from"./types.js";const m="[P201-EV-HEADLESS]",P=Object.freeze(["neocortex-sentinel","neocortex"]),q="neocortex";function B(t){return typeof t=="string"&&P.includes(t)}const p=96*1024,v=256,x="## Parallel Delegation Contract",C=Object.freeze(["## P127 Subagent Isolation Contract","Never pass the original root invocation"]),M=Object.freeze(["I am the root agent","## Root Agent Contract"]),_=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function D(t){return M.some(e=>t.includes(e))?"orchestrator":C.every(e=>t.includes(e))?"child":"unknown"}function U(t,e){let r=!1;for(const n of T(t,e)){const o=k(t,n);if(o.kind==="absent")continue;if(o.kind==="orchestrator"){r=!0;continue}if(o.kind==="refused")return o.preflight;const s=$(t,e);return s||{ok:!0,childProfileName:o.name,publicSafe:!0}}return r?l(d.CHILD_PROFILE_IS_ORCHESTRATOR,"Only the neocortex orchestrator profile was found; the child profile is required before spawn."):l(d.MANAGED_PROFILE_MISSING,"Managed neocortex profile was not found in a trusted host location.")}function k(t,e){let r;try{r=h(e.path)}catch(f){return f.code==="ENOENT"?{kind:"absent"}:{kind:"refused",preflight:u()}}if(r.isSymbolicLink()||!r.isFile()||r.size<=0||r.size>p)return{kind:"refused",preflight:u()};let n;try{n=E(e.path,"utf8")}catch{return{kind:"refused",preflight:u()}}if(Buffer.byteLength(n)>p)return{kind:"refused",preflight:u()};if(A(n)!==e.expectedName)return{kind:"refused",preflight:u()};const o=D(n);if(o==="orchestrator")return{kind:"orchestrator"};if(o!=="child"||!F(t,n))return{kind:"refused",preflight:u()};const s=H(e);return s?{kind:"refused",preflight:s}:{kind:"accepted",name:e.expectedName}}function H(t){const e=I(t.path);let r;try{r=y(e)}catch{return u()}const n=r.filter(s=>s.endsWith(".md"));if(n.length>v)return u();let o=0;for(const s of n){const f=c(e,s);try{const i=h(f);if(i.isSymbolicLink()||!i.isFile()||i.size<=0||i.size>p)continue;A(E(f,"utf8"))===t.expectedName&&(o+=1)}catch{continue}}if(o>1)return l(d.CHILD_PROFILE_NAME_DUPLICATE,"More than one profile in one host scope declares the neocortex child name.")}function A(t){const e=_.exec(t)?.[1];return e===void 0?void 0:/^name:[ \t]*(\S+)[ \t]*$/m.exec(e)?.[1]?.replace(/^(["'])(.*)\1$/,"$2")}function K(t,e,r){return{status:"failed",adapterId:t,runtimeId:e.runtimeId,...e.modelId?{modelId:e.modelId}:{},...e.runtimeSource?{runtimeSource:e.runtimeSource}:{},reasonCode:r.reasonCode,reasonCodes:[r.reasonCode,d.RECEIPT_REDACTED],durationMs:0,counts:{governedPreflightDenials:1},hashes:{governanceEvidence:S(m)},publicSummary:r.publicSummary,redactionSummary:[N("managedProfile","managed_profile","value-denied")],relativePaths:[e.targetRef],...e.receipt?{receipt:e.receipt}:{},publicSafe:!0}}function X(t){return{...t,counts:{...t.counts,governedPreflightPasses:1},hashes:{...t.hashes,governanceEvidence:S(m)},publicSummary:g(`${t.publicSummary} ${m}`)}}function T(t,e){const r=[],n=[],o=R(e.env);if(t==="claude-code"){const i=[e.cwd,o].filter(a=>!!a);for(const a of i)r.push(c(a,".claude","agents"));for(const a of i)n.push({path:c(a,".claude","agents","neocortex","neocortex.md"),expectedName:"neocortex"})}else if(e.cwd&&r.push(c(e.cwd,".opencode","agents")),o){const i=e.env?.OPENCODE_HOME||c(e.env?.XDG_CONFIG_HOME||c(o,".config"),"opencode");r.push(c(i,"agents")),r.push(c(o,".opencode","agents"))}const s=[];for(const i of r)for(const a of P)s.push({path:c(i,`${a}.md`),expectedName:a});s.push(...n);const f=new Set;return s.filter(i=>f.has(i.path)||O(i.path)!==`${i.expectedName}.md`?!1:(f.add(i.path),!0))}function R(t){const e=t?t.HOME||t.USERPROFILE:L();return e&&!/[\r\n\0]/.test(e)?e:void 0}function F(t,e){if(Buffer.byteLength(e)>p)return!1;const r=_.exec(e)?.[1];return r===void 0||!e.includes("Never pass the original root invocation")||!e.includes(x)?!1:t==="claude-code"?/^permissionMode:\s*bypassPermissions\s*$/m.test(r)&&!/^disallowedTools:.*\b(?:Agent|Task)\b/m.test(r)&&/^\s*-\s*Agent\s*$/m.test(r):/^mode:\s*subagent\s*$/m.test(r)&&/^\s+"\*":\s*allow\s*$/m.test(r)&&!/^\s+task:\s*deny\s*$/m.test(r)&&e.includes("root OpenCode agent remains the yoloop owner")}function $(t,e){try{const r=R(e.env),n=b({...r?{configFilePath:c(r,".neocortex","config.json")}:{},platformTarget:t,hostPolicy:e.approvalHostPolicy}).resolution;return n.requestedMode!=="max"||n.effectiveMode!=="max"?l(d.APPROVAL_POLICY_MISMATCH,"Managed max profile did not match the effective subagent approval policy."):void 0}catch{return l(d.APPROVAL_POLICY_INVALID,"Managed subagent approval policy could not be validated safely.")}}function l(t,e){return{ok:!1,reasonCode:t,publicSummary:g(`${e} ${m}`),publicSafe:!0}}function u(){return l(d.MANAGED_PROFILE_INVALID,"Managed neocortex profile failed bounded identity, approval, or isolation validation.")}export{q as DEFAULT_HEADLESS_CHILD_PROFILE_NAME,m as GOVERNED_HEADLESS_EVIDENCE,P as HEADLESS_CHILD_PROFILE_NAMES,D as classifyProfileRole,K as governedPreflightFailureResult,B as isHeadlessChildProfileName,U as preflightManagedHeadlessProfile,X as withGovernedHeadlessEvidence};
1
+ import{lstatSync as m,readdirSync as x,readFileSync as g}from"node:fs";import{homedir as I}from"node:os";import{basename as A,dirname as O,join as a}from"node:path";import{getSubagentApprovalPolicy as N}from"../../config.js";import{HEADLESS_REASON_CODES as f,boundPublicSummary as E,hashPublicValue as y,redaction as L}from"./types.js";const h="[P201-EV-HEADLESS]",S=Object.freeze(["neocortex-sentinel","neocortex"]),z="neocortex";function W(t){return typeof t=="string"&&S.includes(t)}const p=96*1024,b=256,k="## Parallel Delegation Contract",C=Object.freeze(["## P127 Subagent Isolation Contract","Never pass the original root invocation"]),w=Object.freeze(["I am the root agent","## Root Agent Contract"]),R=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/;function D(t){return w.some(e=>t.includes(e))?"orchestrator":C.every(e=>t.includes(e))?"child":"unknown"}function K(t,e){let r=!1;for(const o of $(t,e)){const n=T(t,o);if(n.kind==="absent")continue;if(n.kind==="orchestrator"){r=!0;continue}if(n.kind==="refused")return n.preflight;const s=_(t,e);return s||{ok:!0,childProfileName:n.name,publicSafe:!0}}return r?l(f.CHILD_PROFILE_IS_ORCHESTRATOR,"Only the neocortex orchestrator profile was found; the child profile is required before spawn."):l(f.MANAGED_PROFILE_MISSING,"Managed neocortex profile was not found in a trusted host location.")}const B="neocortex-yoloop-worker",M=["Execute only the single story-worktree phase command you received.",'Send that command verbatim as neocortex-client invoke --args "<exact phase command>" --platform-target runner --format plain.',"Follow the admitted phase and use the same command and runner target for subsequent phase checkpoints.","Keep changes in the assigned story worktree and within its admitted write set.","The root runner owns scheduling, integration and cleanup.","Do not start another agent, invoke yoloop, or modify the epic checkout.","Stop at the phase boundary or on a refusal and return the public checkpoint outcome."].join(" ");function X(t,e){if(e===void 0)return M;if(!t.storyId||!/^[0-9a-f]{40,64}$/.test(e))throw new Error("runner-review-candidate-invalid");return[`Independently review the staged code for ${t.storyId} against its story and spec.`,`Verify that git write-tree equals ${e}, inspect git diff --cached, and check the recorded test and QA evidence.`,`Write only .neocortex/stories/${t.storyId}/review.md. Use '# ${t.storyId} Review', exactly one Verdict line (approved or changes-requested), findings, and 'Reviewed-Tree: ${e}'.`,"Approve only after reviewing the actual candidate. Leave implementation, index, Git refs, and existing evidence untouched.","This is the root review stage: do not invoke yolo or yoloop, start any agent, stage changes, or commit."].join(" ")}function Y(t){return t==="yolo-story-worktree-phase-1"||t==="yolo-story-worktree-phase-2"}function Q(t,e){return _(t,e)??{ok:!0,childProfileName:"neocortex-sentinel",publicSafe:!0}}function T(t,e){let r;try{r=m(e.path)}catch(u){return u.code==="ENOENT"?{kind:"absent"}:{kind:"refused",preflight:d()}}if(r.isSymbolicLink()||!r.isFile()||r.size<=0||r.size>p)return{kind:"refused",preflight:d()};let o;try{o=g(e.path,"utf8")}catch{return{kind:"refused",preflight:d()}}if(Buffer.byteLength(o)>p)return{kind:"refused",preflight:d()};if(P(o)!==e.expectedName)return{kind:"refused",preflight:d()};const n=D(o);if(n==="orchestrator")return{kind:"orchestrator"};if(n!=="child"||!F(t,o))return{kind:"refused",preflight:d()};const s=H(e);return s?{kind:"refused",preflight:s}:{kind:"accepted",name:e.expectedName}}function H(t){const e=O(t.path);let r;try{r=x(e)}catch{return d()}const o=r.filter(s=>s.endsWith(".md"));if(o.length>b)return d();let n=0;for(const s of o){const u=a(e,s);try{const i=m(u);if(i.isSymbolicLink()||!i.isFile()||i.size<=0||i.size>p)continue;P(g(u,"utf8"))===t.expectedName&&(n+=1)}catch{continue}}if(n>1)return l(f.CHILD_PROFILE_NAME_DUPLICATE,"More than one profile in one host scope declares the neocortex child name.")}function P(t){const e=R.exec(t)?.[1];return e===void 0?void 0:/^name:[ \t]*(\S+)[ \t]*$/m.exec(e)?.[1]?.replace(/^(["'])(.*)\1$/,"$2")}function J(t,e,r){return{status:"failed",adapterId:t,runtimeId:e.runtimeId,...e.modelId?{modelId:e.modelId}:{},...e.runtimeSource?{runtimeSource:e.runtimeSource}:{},reasonCode:r.reasonCode,reasonCodes:[r.reasonCode,f.RECEIPT_REDACTED],durationMs:0,counts:{governedPreflightDenials:1},hashes:{governanceEvidence:y(h)},publicSummary:r.publicSummary,redactionSummary:[L("managedProfile","managed_profile","value-denied")],relativePaths:[e.targetRef],...e.receipt?{receipt:e.receipt}:{},publicSafe:!0}}function Z(t){return{...t,counts:{...t.counts,governedPreflightPasses:1},hashes:{...t.hashes,governanceEvidence:y(h)},publicSummary:E(`${t.publicSummary} ${h}`)}}function $(t,e){const r=[],o=[],n=v(e.env);if(t==="claude-code"){const i=[e.cwd,n].filter(c=>!!c);for(const c of i)r.push(a(c,".claude","agents"));for(const c of i)o.push({path:a(c,".claude","agents","neocortex","neocortex.md"),expectedName:"neocortex"})}else if(e.cwd&&r.push(a(e.cwd,".opencode","agents")),n){const i=e.env?.OPENCODE_HOME||a(e.env?.XDG_CONFIG_HOME||a(n,".config"),"opencode");r.push(a(i,"agents")),r.push(a(n,".opencode","agents"))}const s=[];for(const i of r)for(const c of S)s.push({path:a(i,`${c}.md`),expectedName:c});s.push(...o);const u=new Set;return s.filter(i=>u.has(i.path)||A(i.path)!==`${i.expectedName}.md`?!1:(u.add(i.path),!0))}function v(t){const e=t?t.HOME||t.USERPROFILE:I();return e&&!/[\r\n\0]/.test(e)?e:void 0}function F(t,e){if(Buffer.byteLength(e)>p)return!1;const r=R.exec(e)?.[1];return r===void 0||!e.includes("Never pass the original root invocation")||!e.includes(k)?!1:t==="claude-code"?/^permissionMode:\s*bypassPermissions\s*$/m.test(r)&&!/^disallowedTools:.*\b(?:Agent|Task)\b/m.test(r)&&/^\s*-\s*Agent\s*$/m.test(r):/^mode:\s*subagent\s*$/m.test(r)&&/^\s+"\*":\s*allow\s*$/m.test(r)&&!/^\s+task:\s*deny\s*$/m.test(r)&&e.includes("root OpenCode agent remains the yoloop owner")}function _(t,e){try{const r=v(e.env),o=N({...r?{configFilePath:a(r,".neocortex","config.json")}:{},platformTarget:t,hostPolicy:e.approvalHostPolicy}).resolution;return o.requestedMode!=="max"||o.effectiveMode!=="max"?l(f.APPROVAL_POLICY_MISMATCH,"Managed max profile did not match the effective subagent approval policy."):void 0}catch{return l(f.APPROVAL_POLICY_INVALID,"Managed subagent approval policy could not be validated safely.")}}function l(t,e){return{ok:!1,reasonCode:t,publicSummary:E(`${e} ${h}`),publicSafe:!0}}function d(){return l(f.MANAGED_PROFILE_INVALID,"Managed neocortex profile failed bounded identity, approval, or isolation validation.")}export{z as DEFAULT_HEADLESS_CHILD_PROFILE_NAME,h as GOVERNED_HEADLESS_EVIDENCE,S as HEADLESS_CHILD_PROFILE_NAMES,B as RUNNER_WORKER_PROFILE,D as classifyProfileRole,J as governedPreflightFailureResult,W as isHeadlessChildProfileName,Y as isRunnerWorktreePhase,K as preflightManagedHeadlessProfile,Q as preflightRunnerWorker,X as runnerWorkerInstructions,Z as withGovernedHeadlessEvidence};
@@ -1,2 +1,2 @@
1
- import{checkTrustedHeadlessRuntimeBinary as I}from"../binary.js";import{HEADLESS_REASON_CODES as s,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as f,createRejectedExecutionResult as p,createUnavailableExecutionResult as h,hashPublicValue as S,normalizeHeadlessCommandResult as E,redaction as A,runHeadlessCommand as v,validateHeadlessAdapterExecutionInput as b}from"./types.js";import{DEFAULT_HEADLESS_CHILD_PROFILE_NAME as y,governedPreflightFailureResult as T,preflightManagedHeadlessProfile as C,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const i="opencode",l="opencode",P=2e3,O=2e3,k=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,N=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,g=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function U(){return{id:i,displayName:"OpenCode Headless Adapter",async checkAvailability(n={}){return D(i,l,n,{realpathBasenamePolicy:"opencode-npm-native"})},buildInvocation(n){const e=b(n,i);return e.ok?{ok:!0,invocation:{adapterId:i,commandName:l,args:_(e.prompt,e.input.modelId,y),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=b(n,i);if(!t.ok)return p(i,i,t);const r=C(i,e);if(!r.ok)return T(i,t.input,r);if(e.signal?.aborted)return c(E(i,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const a=await this.checkAvailability(e);if(!a.ok)return c(h(i,t.input,a));const o=this.buildInvocation(t.input);if(!o.ok)return p(i,i,o);const d=e.commandRunner??v,u=_(t.prompt,t.input.modelId,r.childProfileName),R=await d(a.executablePath??l,u,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(E(i,t.input,R))}}}async function D(n,e,t,r={}){const a=I({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:r.realpathBasenamePolicy});if(!a.ok)return m(n,e,a.reasonCode===s.ADAPTER_UNAVAILABLE?s.ADAPTER_UNAVAILABLE:s.RUNTIME_UNTRUSTED,a.publicSummary,a.redactionSummary);const d=await(t.versionRunner??t.commandRunner??v)(a.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=x(d,r.versionEvidence??"generic-public");return u.ok?f(n,e,B(e,r.versionEvidence),{executablePath:a.executablePath,versionText:u.versionText}):m(n,e,s.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function x(n,e){const t=V(`${n.stdout}
2
- ${n.stderr}`.trim()),r=t?[A("runtimeVersion","raw_log",S(t))]:[A("runtimeVersion","missing","value-denied")];return n.timedOut||n.exitCode!==0||t.length===0||t.length>P||n.stdoutBytes+n.stderrBytes>O||k.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:r}:e==="claude-code"&&(!N.test(t)||!g.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:r}:{ok:!0,versionText:t}}function V(n){return n.replace(/\s+/g," ").trim()}function B(n,e){return e==="claude-code"?`Trusted ${n} runtime is available with bounded Claude Code version evidence.`:`Trusted ${n} runtime is available.`}function _(n,e,t){const r=["run","--standalone","--agent",t,"--auto"];return e&&r.push("--model",e),r.push("--",n),r}export{D as checkRuntimeAvailability,U as createOpenCodeHeadlessAdapter};
1
+ import{checkTrustedHeadlessRuntimeBinary as y}from"../binary.js";import{HEADLESS_REASON_CODES as d,adapterAvailabilityFailure as m,adapterAvailabilitySuccess as S,createRejectedExecutionResult as p,createUnavailableExecutionResult as T,hashPublicValue as C,normalizeHeadlessCommandResult as E,redaction as v,runHeadlessCommand as A,validateHeadlessAdapterExecutionInput as R}from"./types.js";import{DEFAULT_HEADLESS_CHILD_PROFILE_NAME as O,governedPreflightFailureResult as P,preflightManagedHeadlessProfile as N,isRunnerWorktreePhase as k,preflightRunnerWorker as g,RUNNER_WORKER_PROFILE as _,runnerWorkerInstructions as D,withGovernedHeadlessEvidence as c}from"./managed-profile.js";const n="opencode",l="opencode",x=2e3,V=2e3,w=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|\bPRIVATE\b)/i,B=/\b(?:Claude\s+Code|claude-code|@anthropic-ai\/claude-code)\b/i,H=/\bv?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z][0-9A-Za-z.-]*)?\b/;function G(){return{id:n,displayName:"OpenCode Headless Adapter",async checkAvailability(r={}){return L(n,l,r,{realpathBasenamePolicy:"opencode-npm-native"})},buildInvocation(r){const e=R(r,n);return e.ok?{ok:!0,invocation:{adapterId:n,commandName:l,args:b(e.prompt,e.input.modelId,O),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(r,e={}){const t=R(r,n);if(!t.ok)return p(n,n,t);const i=k(t.input.promptKind),a=i?g(n,e):N(n,e);if(!a.ok)return P(n,t.input,a);if(e.signal?.aborted)return c(E(n,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const s=await this.checkAvailability(e);if(!s.ok)return c(T(n,t.input,s));const o=this.buildInvocation(t.input);if(!o.ok)return p(n,n,o);const u=e.commandRunner??A,I=b(e.runnerReviewTree?"Review the staged candidate.":t.prompt,t.input.modelId,i?_:a.childProfileName),h=i?{...e.env,OPENCODE_CONFIG_CONTENT:JSON.stringify({agent:{[_]:{mode:"primary",hidden:!0,prompt:D(t.input,e.runnerReviewTree),permission:{task:"deny"}}}})}:e.env,f=await u(s.executablePath??l,I,{cwd:e.cwd,env:h,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return c(E(n,t.input,f))}}}async function L(r,e,t,i={}){const a=y({commandName:e,env:t.env,platform:t.platform,commandLocator:t.commandLocator,realpathBasenamePolicy:i.realpathBasenamePolicy});if(!a.ok)return m(r,e,a.reasonCode===d.ADAPTER_UNAVAILABLE?d.ADAPTER_UNAVAILABLE:d.RUNTIME_UNTRUSTED,a.publicSummary,a.redactionSummary);const o=await(t.versionRunner??t.commandRunner??A)(a.executablePath,["--version"],{env:t.env,timeoutMs:5e3,maxOutputBytes:2e3}),u=M(o,i.versionEvidence??"generic-public");return u.ok?S(r,e,z(e,i.versionEvidence),{executablePath:a.executablePath,versionText:u.versionText}):m(r,e,d.ADAPTER_UNAVAILABLE,u.publicSummary,u.redactionSummary)}function M(r,e){const t=U(`${r.stdout}
2
+ ${r.stderr}`.trim()),i=t?[v("runtimeVersion","raw_log",C(t))]:[v("runtimeVersion","missing","value-denied")];return r.timedOut||r.exitCode!==0||t.length===0||t.length>x||r.stdoutBytes+r.stderrBytes>V||w.test(t)?{ok:!1,publicSummary:"Headless runtime version check did not return a bounded public result.",redactionSummary:i}:e==="claude-code"&&(!B.test(t)||!H.test(t))?{ok:!1,publicSummary:"Headless runtime version check did not return bounded Claude Code product/version evidence.",redactionSummary:i}:{ok:!0,versionText:t}}function U(r){return r.replace(/\s+/g," ").trim()}function z(r,e){return e==="claude-code"?`Trusted ${r} runtime is available with bounded Claude Code version evidence.`:`Trusted ${r} runtime is available.`}function b(r,e,t){const i=["run","--standalone","--agent",t,"--auto"];return e&&i.push("--model",e),i.push("--",r),i}export{L as checkRuntimeAvailability,G as createOpenCodeHeadlessAdapter};
@@ -162,6 +162,7 @@ export interface YoloopV4IntegrationOrderOptions {
162
162
  /** Server `DependencyReleaseDirective`s to apply after the integrations. */
163
163
  readonly releaseDirectives?: readonly unknown[];
164
164
  readonly push?: boolean;
165
+ readonly allowLinkedEpicCheckout?: boolean;
165
166
  readonly remote?: string;
166
167
  readonly integrateInOrder?: (options: IntegrateStoryWorktreesInOrderOptions) => Promise<StoryWorktreeOrderedIntegrationSummary>;
167
168
  readonly syncDependents?: (input: {
@@ -184,6 +185,7 @@ export interface YoloopV4IntegrationOrderSummary {
184
185
  export declare function executeYoloopV4IntegrationOrder(plan: unknown, options: YoloopV4IntegrationOrderOptions): Promise<YoloopV4IntegrationOrderSummary>;
185
186
  export declare function isCanonicalDelegatedStoryPrompt(prompt: string): boolean;
186
187
  export declare function defaultYoloopRootInvoker(input: RunYoloopRootInvokeInput, invokeTransport?: RunYoloopRootInvokeTransport): Promise<RunYoloopRootInvokeResult>;
188
+ export declare function runDirectYoloop(options: InvokeOptions): Promise<InvokeResult>;
187
189
  export declare function runYoloopExecutionPhase(options: RunYoloopExecutionPhaseOptions): Promise<RunYoloopExecutionPhaseSummary>;
188
190
  /** P227.23 (L3): public reason for a v4 plan that has nothing to dispatch yet. */
189
191
  export declare const YOLOOP_V4_WAITING_REASON_CODE: "story-worktree-v4-waiting";