@ornexus/neocortex 4.66.14 → 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 (51) 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 +61 -60
  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 +4 -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/published-story-reconciliation.js +4 -4
  15. package/packages/client/dist/git/state-json-field-merge.d.ts +5 -0
  16. package/packages/client/dist/git/state-json-field-merge.js +2 -2
  17. package/packages/client/dist/git/story-worktree-integration.d.ts +2 -0
  18. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  19. package/packages/client/dist/git/story-worktree-manager.d.ts +1 -0
  20. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  21. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  22. package/packages/client/dist/runner/headless/managed-profile.d.ts +6 -1
  23. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  24. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  25. package/packages/client/dist/runner/headless/run-yoloop.d.ts +2 -0
  26. package/packages/client/dist/runner/headless/run-yoloop.js +6 -2
  27. package/packages/client/dist/runner/headless/story-worktree-review.d.ts +18 -0
  28. package/packages/client/dist/runner/headless/story-worktree-review.js +2 -0
  29. package/packages/client/dist/runner/headless/types.d.ts +2 -0
  30. package/packages/client/dist/yoloop/runner-first-use.d.ts +8 -0
  31. package/packages/client/dist/yoloop/runner-first-use.js +5 -0
  32. package/targets-stubs/antigravity/gemini.md +1 -1
  33. package/targets-stubs/antigravity/neocortex.md +1 -1
  34. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  35. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  36. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  37. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  38. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  39. package/targets-stubs/claude-code/neocortex.md +2 -2
  40. package/targets-stubs/codex/AGENTS.md +1 -1
  41. package/targets-stubs/codex/neocortex.toml +1 -1
  42. package/targets-stubs/cursor/agent.md +2 -2
  43. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  44. package/targets-stubs/gemini-cli/agent.md +2 -2
  45. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  46. package/targets-stubs/grok/SKILL.md +1 -1
  47. package/targets-stubs/kimi/neocortex.md +1 -1
  48. package/targets-stubs/openclaw/SKILL.md +1 -1
  49. package/targets-stubs/opencode/neocortex-root.md +2 -2
  50. package/targets-stubs/opencode/neocortex.md +2 -2
  51. 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};
@@ -1,4 +1,4 @@
1
- import{execFile as ae}from"node:child_process";import{createHash as se}from"node:crypto";import{realpath as M}from"node:fs/promises";import{promisify as ce}from"node:util";import{parseYoloopInvocation as Q}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as ue}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as de,resolveDirectYoloIntegrationAuthority as he,verifyDirectYoloIntegrationCommit as fe}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as z}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as le,mutateGitLifecycleRuntime as ye,publishedStoryReconciliationId as V,readGitLifecycleRuntime as B,readStoryWorktreeEvidence as we}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as me}from"./governance-runtime-store.js";import{parseNeocortexTrailers as K,trailerValue as P}from"./neocortex-trailers.js";import{StoryWorktreeManager as U}from"./story-worktree-manager.js";const X=ce(ae),T=/^[a-f0-9]{64}$/,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function Z(e){return se("sha256").update(e).digest("hex")}function v(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,o){let n;try{n=v(JSON.parse(e))}catch{return}if(!(n?.schemaVersion!==2||n.storyId!==o||n.publicSafe!==!0||n.status!=="qa-passed"||n.safeToContinueYoloop!==!0||!Array.isArray(n.blockingChecks)||n.blockingChecks.length!==0))return Z(e)}async function Ce(e,o){const n=Q(o);if(!n||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(n.remainder))return[];const t=ue(o);return!t||t.source!=="explicit"?[]:ee(e,t.epicId,!0)}async function Re(e,o,n){const t=Q(o)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const h=j(e);let I;try{const m=(await h("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await B(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==m)return;const[g,b,...N]=(await h("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
2
- `);if(!g||!b||!A.test(g)||!A.test(b))return;const D=K(N.join(`
3
- `),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!D.ok)return;const a=d=>P(D.values,d),p=a("Neocortex-Story");if(!p||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(p)||a("Neocortex-Epic")!==s||a("Neocortex-Execution-Branch")!==m||a("Neocortex-Prepared-Base")!==b||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(d=>T.test(a(d)??""))||k.stories[p]?.checkpoint||n.some(d=>d.storyId===p))return;const $=me(e);if(!$.ok||!$.value||v(v(v(JSON.parse($.value.toString("utf8")))?.stories)?.[p])?.epic_id!==s)return;I={storyId:p,headSha:g,executionBranch:m}}catch{return}const{storyId:u,headSha:f,executionBranch:S}=I;try{if(await z(h,S)!==f)return}catch{return{status:"pending",storyId:u,headSha:f,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const c=await de({projectRoot:e,storyId:u,commitSha:f});if(c.ok)return{status:"recovered",storyId:u,headSha:f};if(c.reasonCode==="direct-yolo-checkpoint-conflict"){const m=await B(e,{required:!0});if(v(m.stories[u]?.checkpoint)?.headSha===f)return}return{status:"pending",storyId:u,headSha:f,reasonCode:c.reasonCode}}function j(e){return async(...o)=>(await X("git",[...o],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Pe(e,o){const n=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(o);if(!n)return[];try{const s=(await X("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),n[1]):[]}catch{return[]}}function Se(e,o){return ee(e,o,!1)}async function ee(e,o,n){const t=j(e),s=async u=>(await t("rev-parse","--verify","--quiet",`${u}^{commit}`)).trim(),h=async(u,f)=>{try{return await t("merge-base","--is-ancestor",u,f),!0}catch{return!1}},I=[];try{const u=await M((await t("rev-parse","--absolute-git-dir")).trim()),f=await M((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(u!==f)return[];const S=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),c=await s("HEAD"),m=await B(e,{required:!0});if(m.epics[o]?.execution_branch!==S)return[];const k=Object.values(m.storyWorktrees?.entries??{}).filter(i=>i.epicId===o&&i.executionBranch===S&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const g=await B(e,{required:!0});if(g.stories[i.storyId]?.checkpoint||k.filter(r=>r.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const b=v(g.epics[o]?.branch_lease);if(b&&Date.parse(String(b.expiresAt))>Date.now())continue;const N=we(g,o)?.receipts??[];if(N.some(r=>r.kind==="integration-receipt"&&r.storyId===i.storyId))continue;const D=N.filter(r=>r.kind==="phase-one-receipt"&&r.storyId===i.storyId&&r.leaseId===i.leaseId&&r.graphRevision===i.graphRevision);if(D.length!==1)continue;const a=D[0],p=String(a.graphRevision),$=String(a.receiptId);if(!T.test(p)||!A.test(String(a.headSha))||a.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const H=N.filter(r=>r.kind==="published-story-reconciliation"&&r.storyId===i.storyId&&r.graphRevision===p);if(H.length>1||!n&&H.length===0)continue;const d=await he(e,i.storyId),x=d.originBinding;if(d.epicId!==o||d.executionBranch!==S||!x||x.originBranch===S||!await h(x.originHeadSha,c))continue;const l=await new U({projectRoot:e}).probe(i.leaseId);if(!l.ok||l.value.ownership!=="proven"||l.value.clean!==!0||!l.value.headSha||!A.test(l.value.headSha)||!await h(String(a.headSha),l.value.headSha))continue;const q=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${l.value.headSha}`,`${x.originHeadSha}..${c}`)).trim().split(`
4
- `).filter(Boolean);if(q.length!==1||!A.test(q[0]))continue;const y=q[0],te=(await t("show","-s","--format=%P",y)).trim();if(!A.test(te))continue;const _=K(await t("show","-s","--format=%B",y),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||P(_.values,"Neocortex-Story-Worktree-Tip")!==l.value.headSha)continue;const E=P(_.values,"Neocortex-Graph-Revision"),W=P(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!T.test(E)||!W||!T.test(W))continue;const re=(await t("rev-parse",`${y}^{tree}`)).trim(),ie=(await t("rev-parse",`${l.value.headSha}^{tree}`)).trim();if(re!==ie)continue;const Y=await fe(d,i.storyId,y,{expectedGraphRevision:E});if(!Y.ok)continue;const oe=v(JSON.parse(await t("show",`${y}:.neocortex/state.json`))),F=v(v(oe?.stories)?.[i.storyId]);if(F?.epic_id!==o||JSON.stringify(F.depends_on??[])!==JSON.stringify(d.story.depends_on??[]))continue;const C=String(a.specRef),R=`docs/stories/${i.storyId}.story.md`;if(Z(await t("show",`${y}:${C}`))!==a.specDigest||Z(await t("show",`${c}:${C}`))!==a.specDigest||await t("show",`${y}:${R}`)!==await t("show",`${c}:${R}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R);const L=ve(await t("show",`${y}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!L)continue;const w=await z(t,x.originBranch);if(!w)continue;try{await s(w)}catch{if(!n||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",w),await s(w)!==w))continue}if(!await h(x.originHeadSha,w)||!await h(y,w))continue;const G={schemaVersion:1,kind:"published-story-reconciliation",epicId:o,storyId:i.storyId,graphRevision:p,historicalGraphRevision:E,phaseOneReceiptId:$,executionBranch:S,executionHeadSha:c,originBranch:x.originBranch,originHeadSha:w,commitSha:y,bundleDigest:Y.value.bundleDigest,historicalQaDigest:L},J=async()=>{if(await s("HEAD")!==c||await s(`refs/heads/${S}`)!==c||await z(t,x.originBranch)!==w)throw new Error("published-story-reconciliation-ref-raced");const r=await new U({projectRoot:e}).probe(i.leaseId);if(!r.ok||r.value.ownership!=="proven"||r.value.clean!==!0||r.value.headSha!==l.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R)};if(H[0]){const r=H[0],ne={...G,executionHeadSha:r.executionHeadSha,originHeadSha:r.originHeadSha};if(r.receiptId!==V(ne)||!await h(r.executionHeadSha,c)||!await h(r.originHeadSha,w)||(await J(),(await B(e,{required:!0})).revision!==g.revision))continue;I.push(r);continue}const O=Object.freeze({...G,receiptId:V(G)});if(!le(O))continue;await ye(e,r=>{pe(r,o,{receipts:[O]})},{expectedRevision:g.revision,preCommit:J}),I.push(O)}catch{}}catch{}return I}export{ve as historicalStoryQaDigest,Ce as reconcilePublishedStoriesForYoloop,Re as recoverPublishedCheckpointForYoloop,Pe as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
1
+ import{execFile as se}from"node:child_process";import{createHash as ce}from"node:crypto";import{realpath as Q}from"node:fs/promises";import{promisify as ue}from"node:util";import{parseYoloopInvocation as V}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as de}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as he,resolveDirectYoloIntegrationAuthority as fe,verifyDirectYoloIntegrationCommit as le}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as G}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as ye,mutateGitLifecycleRuntime as me,publishedStoryReconciliationId as Z,readGitLifecycleRuntime as A,readStoryWorktreeEvidence as K}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as we}from"./governance-runtime-store.js";import{parseNeocortexTrailers as U,trailerValue as q}from"./neocortex-trailers.js";import{StoryWorktreeManager as X}from"./story-worktree-manager.js";const j=ue(se),R=/^[a-f0-9]{64}$/,N=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function W(e){return ce("sha256").update(e).digest("hex")}function I(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,a){let r;try{r=I(JSON.parse(e))}catch{return}if(!(r?.schemaVersion!==2||r.storyId!==a||r.publicSafe!==!0||r.status!=="qa-passed"||r.safeToContinueYoloop!==!0||!Array.isArray(r.blockingChecks)||r.blockingChecks.length!==0))return W(e)}async function Pe(e,a){const r=V(a);if(!r||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(r.remainder))return[];const t=de(a);return!t||t.source!=="explicit"?[]:te(e,t.epicId,!0)}async function qe(e,a,r){const t=V(a)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const f=ee(e);let m;try{const p=(await f("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await A(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==p)return;const[o,c,...H]=(await f("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
2
+ `);if(!o||!c||!N.test(o)||!N.test(c))return;const B=U(H.join(`
3
+ `),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!B.ok)return;const h=w=>q(B.values,w),g=h("Neocortex-Story");if(!g||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(g)||h("Neocortex-Epic")!==s||h("Neocortex-Execution-Branch")!==p||h("Neocortex-Prepared-Base")!==c||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(w=>R.test(h(w)??""))||k.stories[g]?.checkpoint||r.some(w=>w.storyId===g))return;const D=we(e);if(!D.ok||!D.value||I(I(I(JSON.parse(D.value.toString("utf8")))?.stories)?.[g])?.epic_id!==s)return;m={storyId:g,headSha:o,executionBranch:p}}catch{return}const{storyId:d,headSha:l,executionBranch:y}=m;try{if(await G(f,y)!==l)return}catch{return{status:"pending",storyId:d,headSha:l,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const u=await he({projectRoot:e,storyId:d,commitSha:l});if(u.ok)return{status:"recovered",storyId:d,headSha:l};if(u.reasonCode==="direct-yolo-checkpoint-conflict"){const p=await A(e,{required:!0});if(I(p.stories[d]?.checkpoint)?.headSha===l)return}return{status:"pending",storyId:d,headSha:l,reasonCode:u.reasonCode}}function ee(e){return async(...a)=>(await j("git",[...a],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Re(e,a){const r=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(a);if(!r)return[];try{const s=(await j("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),r[1]):[]}catch{return[]}}function Se(e,a){return te(e,a,!1)}async function te(e,a,r){const t=ee(e),s=async d=>(await t("rev-parse","--verify","--quiet",`${d}^{commit}`)).trim(),f=async(d,l)=>{try{return await t("merge-base","--is-ancestor",d,l),!0}catch{return!1}},m=[];try{const d=await Q((await t("rev-parse","--absolute-git-dir")).trim()),l=await Q((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(d!==l)return[];const y=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),u=await s("HEAD"),p=await A(e,{required:!0});if(p.epics[a]?.execution_branch!==y)return[];const k=Object.values(p.storyWorktrees?.entries??{}).filter(i=>i.epicId===a&&i.executionBranch===y&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const o=await A(e,{required:!0});if(o.stories[i.storyId]?.checkpoint||k.filter(n=>n.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const c=I(o.epics[a]?.branch_lease);if(c&&Date.parse(String(c.expiresAt))>Date.now())continue;const H=K(o,a)?.receipts??[];if(H.some(n=>n.kind==="integration-receipt"&&n.storyId===i.storyId))continue;const B=H.filter(n=>n.kind==="phase-one-receipt"&&n.storyId===i.storyId&&n.leaseId===i.leaseId&&n.graphRevision===i.graphRevision);if(B.length!==1)continue;const h=B[0],g=String(h.graphRevision),D=String(h.receiptId);if(!R.test(g)||!N.test(String(h.headSha))||h.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const $=H.filter(n=>n.kind==="published-story-reconciliation"&&n.storyId===i.storyId&&n.graphRevision===g);if($.length>1||!r&&$.length===0)continue;const w=await fe(e,i.storyId),b=w.originBinding;if(w.epicId!==a||w.executionBranch!==y||!b||b.originBranch===y||!await f(b.originHeadSha,u))continue;const v=await new X({projectRoot:e}).probe(i.leaseId);if(!v.ok||v.value.ownership!=="proven"||v.value.clean!==!0||!v.value.headSha||!N.test(v.value.headSha)||!await f(String(h.headSha),v.value.headSha))continue;const T=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${v.value.headSha}`,`${b.originHeadSha}..${u}`)).trim().split(`
4
+ `).filter(Boolean);if(T.length!==1||!N.test(T[0]))continue;const S=T[0],re=(await t("show","-s","--format=%P",S)).trim();if(!N.test(re))continue;const _=U(await t("show","-s","--format=%B",S),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||q(_.values,"Neocortex-Story-Worktree-Tip")!==v.value.headSha)continue;const E=q(_.values,"Neocortex-Graph-Revision"),Y=q(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!R.test(E)||!Y||!R.test(Y))continue;const ie=(await t("rev-parse",`${S}^{tree}`)).trim(),oe=(await t("rev-parse",`${v.value.headSha}^{tree}`)).trim();if(ie!==oe)continue;const F=await le(w,i.storyId,S,{expectedGraphRevision:E});if(!F.ok)continue;const ne=I(JSON.parse(await t("show",`${S}:.neocortex/state.json`))),L=I(I(ne?.stories)?.[i.storyId]);if(L?.epic_id!==a||JSON.stringify(L.depends_on??[])!==JSON.stringify(w.story.depends_on??[]))continue;const C=String(h.specRef),P=`docs/stories/${i.storyId}.story.md`;if(W(await t("show",`${S}:${C}`))!==h.specDigest||W(await t("show",`${u}:${C}`))!==h.specDigest||await t("show",`${S}:${P}`)!==await t("show",`${u}:${P}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P);const J=ve(await t("show",`${S}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!J)continue;const x=await G(t,b.originBranch);if(!x)continue;try{await s(x)}catch{if(!r||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",x),await s(x)!==x))continue}if(!await f(b.originHeadSha,x)||!await f(S,x))continue;const O={schemaVersion:1,kind:"published-story-reconciliation",epicId:a,storyId:i.storyId,graphRevision:g,historicalGraphRevision:E,phaseOneReceiptId:D,executionBranch:y,executionHeadSha:u,originBranch:b.originBranch,originHeadSha:x,commitSha:S,bundleDigest:F.value.bundleDigest,historicalQaDigest:J},M=async()=>{if(await s("HEAD")!==u||await s(`refs/heads/${y}`)!==u||await G(t,b.originBranch)!==x)throw new Error("published-story-reconciliation-ref-raced");const n=await new X({projectRoot:e}).probe(i.leaseId);if(!n.ok||n.value.ownership!=="proven"||n.value.clean!==!0||n.value.headSha!==v.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P)};if($[0]){const n=$[0],ae={...O,executionHeadSha:n.executionHeadSha,originHeadSha:n.originHeadSha};if(n.receiptId!==Z(ae)||!await f(n.executionHeadSha,u)||!await f(n.originHeadSha,x)||(await M(),(await A(e,{required:!0})).revision!==o.revision))continue;m.push(n);continue}const z=Object.freeze({...O,receiptId:Z(O)});if(!ye(z))continue;await me(e,n=>{pe(n,a,{receipts:[z]})},{expectedRevision:o.revision,preCommit:M}),m.push(z)}catch{}}catch{}return m.length===0?m:xe(e,a,m,t)}async function xe(e,a,r,t){try{const s=await A(e,{required:!0}),f=(K(s,a)?.receipts??[]).filter(o=>o.kind==="integration-receipt"&&o.outcome==="integrated").sort((o,c)=>Number(c.integrationIndex)-Number(o.integrationIndex));if(f.length===0)return r;const m=String(f[0].epicHeadAfterSha),d=r[0].executionBranch;if(s.epics[a]?.execution_branch!==d)return r;const l=`refs/heads/${d}`,y=(await t("rev-parse","--verify",l)).trim(),u=async(o,c)=>{if(o===c)return!0;try{return await t("merge-base","--is-ancestor",o,c),!0}catch{return!1}},p=[...new Set([m,...r.map(o=>o.commitSha)])],k=[...p,...r.map(o=>o.executionHeadSha)];if(!(await Promise.all(k.map(o=>u(o,y)))).every(Boolean))return r;let i=y;for(const o of p)if((await Promise.all(p.map(c=>u(c,o)))).every(Boolean)){i=o;break}return(await t("rev-parse","--verify",l)).trim()!==y||(await A(e,{required:!0})).revision!==s.revision?r:r.map(o=>{const c={...o,syncBaseSha:i,syncIntegrationHeadSha:m};return Object.freeze({...c,receiptId:Z(c)})})}catch{return r}}export{ve as historicalStoryQaDigest,Pe as reconcilePublishedStoriesForYoloop,qe as recoverPublishedCheckpointForYoloop,Re as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
@@ -73,4 +73,9 @@ export declare function recomputeStateJsonEpicAggregates(input: {
73
73
  }): StateJsonEpicAggregateResult;
74
74
  /** P227-CON-STATE-MERGE: pure, deterministic 3-way field merge (R1-R7). */
75
75
  export declare function mergeStateJsonFields(input: StateJsonFieldMergeInput): StateJsonFieldMergeResult;
76
+ /** Legacy phase checkpoints can prepend locally and append on the epic.
77
+ * Permit only an intact shared sequence and new local checkpoints for this
78
+ * story. Keep arbitrary conflicting history out of the automatic sync path.
79
+ */
80
+ export declare function mergeLegacyStateForStorySync(input: StateJsonFieldMergeInput): string | undefined;
76
81
  export {};
@@ -1,2 +1,2 @@
1
- const M=33554432,l=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),C=Object.freeze(["total_stories","completed_stories","status","completed_at"]),x=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,J=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,S=Symbol("absent");class j extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function g(e,t){throw new j(e,t)}function E(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function r(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:S}function d(e,t){if(e===t)return!0;if(e===S||t===S)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>d(s,t[n]));if(E(e)){if(!E(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&d(e[n],t[n]))}return!1}function k(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&g(l.inputInvalid);let s;try{s=JSON.parse(t)}catch{g(l.inputInvalid)}E(s)||g(l.inputInvalid);for(const n of["stories","epics"]){const o=r(s,n);o!==S&&!E(o)&&g(l.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const o of Object.keys(n??{}))s.has(o)||(s.add(o),t.push(o));return t}function I(e,t,s){s===S?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function F(e,t){const s=Object.keys(e).filter(i=>r(t,i)!==S),n=Object.keys(e).filter(i=>r(t,i)===S).sort(),o={};for(const i of[...s,...n])I(o,i,e[i]);return o}function w(e,t,s,n){if(d(s,e)||d(s,t))return t;g(l.outsideAllowlist,n)}function b(e){return E(e)?e:void 0}function L(e,t,s,n,o){if(d(s,e))return t;if(E(s)||g(l.storyEntryInvalid,`stories.${n}`),(r(s,"id")!==S&&s.id!==n||r(s,"epic_id")!==S&&s.epic_id!==o)&&g(l.storyEntryInvalid,`stories.${n}`),d(t,e))return s;t!==S&&!E(t)&&g(l.storyEntryInvalid,`stories.${n}`);const i=b(e),a=b(t),m={...a??{}};for(const u of N(a,s,i)){const O=r(i,u),f=r(a,u),_=r(s,u);d(_,O)||d(_,f)?I(m,u,f):d(f,O)?I(m,u,_):g(l.storyEntryConflict,`stories.${n}.${u}`)}return m}function P(e,t,s,n){if(d(s,e)||d(s,t))return t;(!E(s)||!E(t)||e!==S&&!E(e))&&g(l.outsideAllowlist,`epics.${n}`);const o=b(e),i={...t};for(const a of N(t,s,o))C.includes(a)||I(i,a,w(r(o,a),r(t,a),r(s,a),`epics.${n}.${a}`));return i}function R(e,t,s){if(d(s,e)||d(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||g(l.outsideAllowlist,"last_updated");const o=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(o)&&o>=n?t:s}const $=new Set(["done","completed","merged"]);function D(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function z(e){const t=()=>g(l.aggregateInvalid,`epics.${e.epicId}`);E(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let o=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const _=e.stories[f];(!E(_)||_.id!==f||_.epic_id!==e.epicId)&&t(),$.has(D(_.status))&&(o+=1)}const i=n.size,a=i>0&&o===i,m=$.has(D(s.status));m&&!a&&i>0&&t(),s.total_stories=i,s.completed_stories=o;let u=!1,O=!1;return!m&&a&&(s.status="done",u=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,O=!0)),{epic:s,totalStories:i,completedStories:o,promotedDone:u,completedAtSet:O}}function G(e){return`${JSON.stringify(e,null,2)}
2
- `}function B(e){try{(!x.test(e.storyId)||!J.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&g(l.inputInvalid);const t=k(e.base).value,s=k(e.epic),n=s.value,o=k(e.story).value,i={...n};for(const c of N(n,o,t)){const p=r(t,c),y=r(n,c),A=r(o,c);c==="stories"||c==="epics"||(c==="last_updated"?I(i,c,R(p,y,A)):I(i,c,w(p,y,A,c)))}const a=b(r(t,"stories")),m=b(r(n,"stories")),u=b(r(o,"stories"));if(u||m||a){const c={...m??{}};for(const p of N(m,u,a)){const y=r(a,p),A=r(m,p),v=r(u,p);I(c,p,p===e.storyId?L(y,A,v,e.storyId,e.epicId):w(y,A,v,`stories.${p}`))}(m||Object.keys(c).length>0)&&I(i,"stories",F(c,a))}const O=b(r(t,"epics")),f=b(r(n,"epics")),_=b(r(o,"epics"));let h=!1;if(_||f||O){const c={...f??{}};for(const y of N(f,_,O)){const A=r(O,y),v=r(f,y),T=r(_,y);I(c,y,y===e.epicId?P(A,v,T,y):w(A,v,T,`epics.${y}`))}const p=r(c,e.epicId);E(p)&&Array.isArray(p.stories)&&(I(c,e.epicId,z({epicId:e.epicId,epic:p,stories:b(r(i,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),h=!0),(f||Object.keys(c).length>0)&&I(i,"epics",c)}return d(i,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:h}:{ok:!0,bytes:G(i),changed:!0,aggregatesRecomputed:h}}catch(t){return t instanceof j?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:l.inputInvalid}}}export{C as STATE_JSON_EPIC_AGGREGATE_FIELDS,M as STATE_JSON_FIELD_MERGE_MAX_BYTES,l as STATE_JSON_FIELD_MERGE_REASON_CODES,B as mergeStateJsonFields,z as recomputeStateJsonEpicAggregates,d as stateJsonValuesEqual};
1
+ const B=33554432,g=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),F=Object.freeze(["total_stories","completed_stories","status","completed_at"]),J=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,L=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,I=Symbol("absent");class $ extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function b(e,t){throw new $(e,t)}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function i(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:I}function l(e,t){if(e===t)return!0;if(e===I||t===I)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>l(s,t[n]));if(m(e)){if(!m(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&l(e[n],t[n]))}return!1}function v(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&b(g.inputInvalid);let s;try{s=JSON.parse(t)}catch{b(g.inputInvalid)}m(s)||b(g.inputInvalid);for(const n of["stories","epics"]){const r=i(s,n);r!==I&&!m(r)&&b(g.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const r of Object.keys(n??{}))s.has(r)||(s.add(r),t.push(r));return t}function A(e,t,s){s===I?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function P(e,t){const s=Object.keys(e).filter(o=>i(t,o)!==I),n=Object.keys(e).filter(o=>i(t,o)===I).sort(),r={};for(const o of[...s,...n])A(r,o,e[o]);return r}function w(e,t,s,n){if(l(s,e)||l(s,t))return t;b(g.outsideAllowlist,n)}function O(e){return m(e)?e:void 0}function R(e,t,s,n,r){if(l(s,e))return t;if(m(s)||b(g.storyEntryInvalid,`stories.${n}`),(i(s,"id")!==I&&s.id!==n||i(s,"epic_id")!==I&&s.epic_id!==r)&&b(g.storyEntryInvalid,`stories.${n}`),l(t,e))return s;t!==I&&!m(t)&&b(g.storyEntryInvalid,`stories.${n}`);const o=O(e),c=O(t),u={...c??{}};for(const d of N(c,s,o)){const p=i(o,d),f=i(c,d),y=i(s,d);l(y,p)||l(y,f)?A(u,d,f):l(f,p)?A(u,d,y):b(g.storyEntryConflict,`stories.${n}.${d}`)}return u}function z(e,t,s,n){if(l(s,e)||l(s,t))return t;(!m(s)||!m(t)||e!==I&&!m(e))&&b(g.outsideAllowlist,`epics.${n}`);const r=O(e),o={...t};for(const c of N(t,s,r))F.includes(c)||A(o,c,w(i(r,c),i(t,c),i(s,c),`epics.${n}.${c}`));return o}function G(e,t,s){if(l(s,e)||l(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||b(g.outsideAllowlist,"last_updated");const r=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(r)&&r>=n?t:s}const D=new Set(["done","completed","merged"]);function C(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function M(e){const t=()=>b(g.aggregateInvalid,`epics.${e.epicId}`);m(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let r=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const y=e.stories[f];(!m(y)||y.id!==f||y.epic_id!==e.epicId)&&t(),D.has(C(y.status))&&(r+=1)}const o=n.size,c=o>0&&r===o,u=D.has(C(s.status));u&&!c&&o>0&&t(),s.total_stories=o,s.completed_stories=r;let d=!1,p=!1;return!u&&c&&(s.status="done",d=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,p=!0)),{epic:s,totalStories:o,completedStories:r,promotedDone:d,completedAtSet:p}}function T(e){return`${JSON.stringify(e,null,2)}
2
+ `}function x(e){try{(!J.test(e.storyId)||!L.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&b(g.inputInvalid);const t=v(e.base).value,s=v(e.epic),n=s.value,r=v(e.story).value,o={...n};for(const a of N(n,r,t)){const E=i(t,a),S=i(n,a),h=i(r,a);a==="stories"||a==="epics"||(a==="last_updated"?A(o,a,G(E,S,h)):A(o,a,w(E,S,h,a)))}const c=O(i(t,"stories")),u=O(i(n,"stories")),d=O(i(r,"stories"));if(d||u||c){const a={...u??{}};for(const E of N(u,d,c)){const S=i(c,E),h=i(u,E),k=i(d,E);A(a,E,E===e.storyId?R(S,h,k,e.storyId,e.epicId):w(S,h,k,`stories.${E}`))}(u||Object.keys(a).length>0)&&A(o,"stories",P(a,c))}const p=O(i(t,"epics")),f=O(i(n,"epics")),y=O(i(r,"epics"));let _=!1;if(y||f||p){const a={...f??{}};for(const S of N(f,y,p)){const h=i(p,S),k=i(f,S),j=i(y,S);A(a,S,S===e.epicId?z(h,k,j,S):w(h,k,j,`epics.${S}`))}const E=i(a,e.epicId);m(E)&&Array.isArray(E.stories)&&(A(a,e.epicId,M({epicId:e.epicId,epic:E,stories:O(i(o,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),_=!0),(f||Object.keys(a).length>0)&&A(o,"epics",a)}return l(o,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:_}:{ok:!0,bytes:T(o),changed:!0,aggregatesRecomputed:_}}catch(t){return t instanceof $?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:g.inputInvalid}}}function Y(e){try{const t=v(e.base).value,s=v(e.epic).value,n=v(e.story).value,r=t.checkpoints,o=s.checkpoints,c=n.checkpoints;if(l(r,c)){const _=x(e);return _.ok?_.bytes:void 0}if(!Array.isArray(r)||!Array.isArray(o)||!Array.isArray(c)||c.length<=r.length||!l(o.slice(0,r.length),r))return;const u=c.length-r.length,d=l(c.slice(u),r);if(!d&&!l(c.slice(0,r.length),r))return;const p=d?c.slice(0,u):c.slice(r.length);if(!p.every(_=>m(_)&&_.story_id===e.storyId)||p.some(_=>o.some(a=>l(_,a))))return;const f=x({...e,story:T({...n,checkpoints:r})});if(!f.ok)return;const y=v(f.bytes).value;return T({...y,checkpoints:d?[...p,...o]:[...o,...p]})}catch{return}}export{F as STATE_JSON_EPIC_AGGREGATE_FIELDS,B as STATE_JSON_FIELD_MERGE_MAX_BYTES,g as STATE_JSON_FIELD_MERGE_REASON_CODES,Y as mergeLegacyStateForStorySync,x as mergeStateJsonFields,M as recomputeStateJsonEpicAggregates,l as stateJsonValuesEqual};
@@ -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};
@@ -188,6 +188,7 @@ export declare class StoryWorktreeManager {
188
188
  readonly leaseId: string;
189
189
  readonly integratedSha?: string;
190
190
  readonly directive?: unknown;
191
+ readonly automatic?: boolean;
191
192
  }): Promise<StoryWorktreeResult<StoryWorktreeSyncValue>>;
192
193
  status(input: {
193
194
  readonly leaseId?: string;