@ornexus/neocortex 4.66.15 → 4.66.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/commands/invoke.d.ts +1 -1
- package/packages/client/dist/commands/invoke.js +81 -80
- package/packages/client/dist/continuity/native-worktree-custody.d.ts +10 -0
- package/packages/client/dist/continuity/native-worktree-custody.js +1 -0
- package/packages/client/dist/continuity/sqlite-store.d.ts +2 -0
- package/packages/client/dist/continuity/sqlite-store.js +39 -29
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/git-lifecycle-store.d.ts +3 -3
- package/packages/client/dist/git/git-lifecycle-store.js +9 -9
- package/packages/client/dist/git/governance-runtime-store.d.ts +1 -0
- package/packages/client/dist/git/governance-runtime-store.js +2 -2
- package/packages/client/dist/git/published-story-reconciliation.js +5 -4
- package/packages/client/dist/git/story-worktree-integration.d.ts +2 -0
- package/packages/client/dist/git/story-worktree-integration.js +3 -3
- package/packages/client/dist/git/story-write-set-extension.d.ts +1 -1
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +3 -0
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -2
- package/packages/client/dist/runner/headless/managed-profile.d.ts +6 -1
- package/packages/client/dist/runner/headless/managed-profile.js +1 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +2 -0
- package/packages/client/dist/runner/headless/run-yoloop.js +6 -2
- package/packages/client/dist/runner/headless/story-worktree-review.d.ts +18 -0
- package/packages/client/dist/runner/headless/story-worktree-review.js +2 -0
- package/packages/client/dist/runner/headless/types.d.ts +2 -0
- package/packages/client/dist/yoloop/runner-first-use.d.ts +8 -0
- package/packages/client/dist/yoloop/runner-first-use.js +5 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,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
|
|
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(!
|
|
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,5 @@
|
|
|
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
|
|
2
|
-
`);if(!
|
|
3
|
-
`)
|
|
4
|
-
`)
|
|
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 me,mutateGitLifecycleRuntime as ye,publishedStoryReconciliationId as Z,readGitLifecycleRuntime as N,readStoryWorktreeEvidence as K}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as we}from"./governance-runtime-store.js";import{parseNeocortexTrailers as U,trailerValue as P}from"./neocortex-trailers.js";import{StoryWorktreeManager as X}from"./story-worktree-manager.js";const j=ue(se),q=/^[a-f0-9]{64}$/,D=/^(?:[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 d=ee(e);let g;try{const f=(await d("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await N(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==f)return;const n=(await d("log","--first-parent","--max-count=16","--format=%H","--fixed-strings",`--grep=Neocortex-Epic: ${s}`,"HEAD")).trim().split(`
|
|
2
|
+
`).filter(Boolean),c=we(e);if(!c.ok||!c.value)return;const H=I(I(JSON.parse(c.value.toString("utf8")))?.stories),B=[];for(const w of n){if(!D.test(w))continue;const[b,...R]=(await d("show","-s","--format=%P%n%B",w)).split(`
|
|
3
|
+
`);if(!b||!D.test(b))continue;const A=U(R.join(`
|
|
4
|
+
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!A.ok)continue;const v=u=>P(A.values,u),l=v("Neocortex-Story");!l||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(l)||v("Neocortex-Epic")!==s||v("Neocortex-Execution-Branch")!==f||v("Neocortex-Prepared-Base")!==b||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(u=>q.test(v(u)??""))||k.stories[l]?.checkpoint||r.some(u=>u.storyId===l)||I(H?.[l])?.epic_id!==s||B.push({storyId:l,headSha:w,executionBranch:f})}if(B.length!==1)return;g=B[0]}catch{return}const{storyId:p,headSha:m,executionBranch:y}=g;try{const f=await G(d,y);if(!f)return;try{await d("merge-base","--is-ancestor",m,f)}catch{return}}catch{return{status:"pending",storyId:p,headSha:m,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const h=await he({projectRoot:e,storyId:p,commitSha:m});if(h.ok)return{status:"recovered",storyId:p,headSha:m};if(h.reasonCode==="direct-yolo-checkpoint-conflict"){const f=await N(e,{required:!0});if(I(f.stories[p]?.checkpoint)?.headSha===m)return}return{status:"pending",storyId:p,headSha:m,reasonCode:h.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 p=>(await t("rev-parse","--verify","--quiet",`${p}^{commit}`)).trim(),d=async(p,m)=>{try{return await t("merge-base","--is-ancestor",p,m),!0}catch{return!1}},g=[];try{const p=await Q((await t("rev-parse","--absolute-git-dir")).trim()),m=await Q((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(p!==m)return[];const y=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),h=await s("HEAD"),f=await N(e,{required:!0});if(f.epics[a]?.execution_branch!==y)return[];const k=Object.values(f.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 n=await N(e,{required:!0});if(n.stories[i.storyId]?.checkpoint||k.filter(o=>o.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const c=I(n.epics[a]?.branch_lease);if(c&&Date.parse(String(c.expiresAt))>Date.now())continue;const H=K(n,a)?.receipts??[];if(H.some(o=>o.kind==="integration-receipt"&&o.storyId===i.storyId))continue;const B=H.filter(o=>o.kind==="phase-one-receipt"&&o.storyId===i.storyId&&o.leaseId===i.leaseId&&o.graphRevision===i.graphRevision);if(B.length!==1)continue;const w=B[0],b=String(w.graphRevision),R=String(w.receiptId);if(!q.test(b)||!D.test(String(w.headSha))||w.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const A=H.filter(o=>o.kind==="published-story-reconciliation"&&o.storyId===i.storyId&&o.graphRevision===b);if(A.length>1||!r&&A.length===0)continue;const v=await fe(e,i.storyId),l=v.originBinding;if(v.epicId!==a||v.executionBranch!==y||!l||l.originBranch===y||!await d(l.originHeadSha,h))continue;const u=await new X({projectRoot:e}).probe(i.leaseId);if(!u.ok||u.value.ownership!=="proven"||u.value.clean!==!0||!u.value.headSha||!D.test(u.value.headSha)||!await d(String(w.headSha),u.value.headSha))continue;const T=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${u.value.headSha}`,`${l.originHeadSha}..${h}`)).trim().split(`
|
|
5
|
+
`).filter(Boolean);if(T.length!==1||!D.test(T[0]))continue;const S=T[0],re=(await t("show","-s","--format=%P",S)).trim();if(!D.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||P($.values,"Neocortex-Story-Worktree-Tip")!==u.value.headSha)continue;const _=P($.values,"Neocortex-Graph-Revision"),Y=P($.values,"Neocortex-Review-Artifact-Digest");if(!_||!q.test(_)||!Y||!q.test(Y))continue;const ie=(await t("rev-parse",`${S}^{tree}`)).trim(),oe=(await t("rev-parse",`${u.value.headSha}^{tree}`)).trim();if(ie!==oe)continue;const F=await le(v,i.storyId,S,{expectedGraphRevision:_});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(v.story.depends_on??[]))continue;const E=String(w.specRef),C=`docs/stories/${i.storyId}.story.md`;if(W(await t("show",`${S}:${E}`))!==w.specDigest||W(await t("show",`${h}:${E}`))!==w.specDigest||await t("show",`${S}:${C}`)!==await t("show",`${h}:${C}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",E,C);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,l.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 d(l.originHeadSha,x)||!await d(S,x))continue;const O={schemaVersion:1,kind:"published-story-reconciliation",epicId:a,storyId:i.storyId,graphRevision:b,historicalGraphRevision:_,phaseOneReceiptId:R,executionBranch:y,executionHeadSha:h,originBranch:l.originBranch,originHeadSha:x,commitSha:S,bundleDigest:F.value.bundleDigest,historicalQaDigest:J},M=async()=>{if(await s("HEAD")!==h||await s(`refs/heads/${y}`)!==h||await G(t,l.originBranch)!==x)throw new Error("published-story-reconciliation-ref-raced");const o=await new X({projectRoot:e}).probe(i.leaseId);if(!o.ok||o.value.ownership!=="proven"||o.value.clean!==!0||o.value.headSha!==u.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",E,C)};if(A[0]){const o=A[0],ae={...O,executionHeadSha:o.executionHeadSha,originHeadSha:o.originHeadSha};if(o.receiptId!==Z(ae)||!await d(o.executionHeadSha,h)||!await d(o.originHeadSha,x)||(await M(),(await N(e,{required:!0})).revision!==n.revision))continue;g.push(o);continue}const z=Object.freeze({...O,receiptId:Z(O)});if(!me(z))continue;await ye(e,o=>{pe(o,a,{receipts:[z]})},{expectedRevision:n.revision,preCommit:M}),g.push(z)}catch{}}catch{}return g.length===0?g:xe(e,a,g,t)}async function xe(e,a,r,t){try{const s=await N(e,{required:!0}),d=(K(s,a)?.receipts??[]).filter(n=>n.kind==="integration-receipt"&&n.outcome==="integrated").sort((n,c)=>Number(c.integrationIndex)-Number(n.integrationIndex));if(d.length===0)return r;const g=String(d[0].epicHeadAfterSha),p=r[0].executionBranch;if(s.epics[a]?.execution_branch!==p)return r;const m=`refs/heads/${p}`,y=(await t("rev-parse","--verify",m)).trim(),h=async(n,c)=>{if(n===c)return!0;try{return await t("merge-base","--is-ancestor",n,c),!0}catch{return!1}},f=[...new Set([g,...r.map(n=>n.commitSha)])],k=[...f,...r.map(n=>n.executionHeadSha)];if(!(await Promise.all(k.map(n=>h(n,y)))).every(Boolean))return r;let i=y;for(const n of f)if((await Promise.all(f.map(c=>h(c,n)))).every(Boolean)){i=n;break}return(await t("rev-parse","--verify",m)).trim()!==y||(await N(e,{required:!0})).revision!==s.revision?r:r.map(n=>{const c={...n,syncBaseSha:i,syncIntegrationHeadSha:g};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};
|
|
@@ -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
|
|
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};
|
|
@@ -29,7 +29,7 @@ export type StoryWriteSetExtensionResult = {
|
|
|
29
29
|
readonly reasonCode: string;
|
|
30
30
|
};
|
|
31
31
|
export interface ExtendStoryWriteSetOptions {
|
|
32
|
-
/** Root
|
|
32
|
+
/** Root checkout or the linked checkout of the epic execution branch. */
|
|
33
33
|
readonly projectRoot: string;
|
|
34
34
|
readonly storyId: string;
|
|
35
35
|
readonly paths: readonly string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFile as
|
|
1
|
+
import{execFile as O}from"node:child_process";import{createHash as V}from"node:crypto";import{readFile as I,realpath as m}from"node:fs/promises";import{join as C,resolve as x}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLockWithin as J,ensureRuntimeStory as Z,isStoryWorktreeIntegrationReceiptRecord as K,isStoryWriteSetExtension as X,isStoryWriteSetExtensionPath as $,mutateGitLifecycleRuntime as Q,readGitLifecycleRuntime as S,readStoryWorktreeEvidence as B,releaseGitLifecyclePhysicalIntegrationLock as ee,STORY_WRITE_SET_MAX_ENTRIES as R,storyWriteSetExtensionDigest as q,storyWriteSetExtensionPaths as z,verifyGitLifecyclePhysicalIntegrationLock as te}from"./git-lifecycle-store.js";const b=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class D extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function d(e){throw new D(e)}function k(e,t){return new Promise((r,n)=>{O("git",[...t],{cwd:e,encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(s,i)=>s?n(new D("story-write-set-extension-not-root")):r(String(i).trim()))})}function w(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function P(e,t,r){const n=await k(e,["symbolic-ref","--quiet","--short","HEAD"]),s=r.epics[t.split(".")[0]],i=await m(await k(e,["rev-parse","--show-toplevel"]));(i!==e||s?.branch_mode!=="epic"||s.execution_branch!==n||Object.values(r.storyWorktrees?.entries??{}).some(c=>c.temporaryBranch===n||x(c.worktreePath)===i))&&d("story-write-set-extension-not-root");const a=(await k(e,["worktree","list","--porcelain","-z"])).split("\0\0").map(c=>c.split("\0")).filter(c=>c.includes(`branch refs/heads/${n}`)),g=a[0]?.[0];(a.length!==1||!g?.startsWith("worktree ")||await m(g.slice(9))!==i)&&d("story-write-set-extension-not-root")}function M(e){try{return X(e)}catch{return!1}}function re(e){return V("sha256").update([...e].sort().join("\0")).digest("hex")}function N(e,t,r,n,s){const i=w(w(t.stories)?.[r]);i||d("story-write-set-extension-story-missing");const o=typeof i.epic_id=="string"?i.epic_id:r.split(".")[0];r.startsWith(`${o}.`)||d("story-write-set-extension-story-missing");const a=e.stories[r];(B(e,o)?.receipts??[]).filter(K).some(y=>y.storyId===r&&y.outcome==="integrated")&&d("story-write-set-extension-story-integrated"),(a?.checkpoint||i.checkpoint)&&d("story-write-set-extension-checkpoint-accepted");const c=w(e.epics[o]?.branch_lease);c&&Date.parse(String(c.expiresAt))>s&&d("story-write-set-extension-writer-active"),a?.write_set_extension!==void 0&&!M(a.write_set_extension)&&d("story-write-set-extension-invalid");const l=z(a);l.some(y=>!n.includes(y))&&d("story-write-set-extension-not-superset");const f=Array.isArray(i.files_to_modify)?i.files_to_modify.filter(y=>typeof y=="string"):[],h=[...new Set([...f,...n])].sort();return h.length>R&&d("story-write-set-extension-too-large"),{epicId:o,union:h,unchanged:l.length===n.length}}async function ye(e){let t=x(e.projectRoot),r;try{(typeof e.storyId!="string"||!b.test(e.storyId))&&d("story-write-set-extension-story-invalid"),(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>R||e.paths.some(u=>!$(u)))&&d("story-write-set-extension-path-invalid");const n=[...new Set(e.paths)].sort();t=await m(t);const s=await m(await k(t,["rev-parse","--absolute-git-dir"])),i=await m(await k(t,["rev-parse","--path-format=absolute","--git-common-dir"])),o=s!==i;o&&await P(t,e.storyId,await S(t,{required:!0}));const a=await F({projectRoot:t,storyId:e.storyId});a.ok||d(a.reasonCode);const g=new Date(e.nowIso??Date.now()).toISOString(),c=C(t,".neocortex","state.json"),l=async()=>{const u=await I(c,"utf8"),p=w(JSON.parse(u))??d("story-write-set-extension-state-invalid"),E=await S(t,{required:!0});return o&&await P(t,e.storyId,E),{trackedBytes:u,tracked:p,runtime:E,plan:N(E,p,e.storyId,n,Date.now())}},f=q(n),h=(u,p)=>({ok:!0,value:Object.freeze({storyId:e.storyId,epicId:u.epicId,outcome:p,extensionPathCount:n.length,extensionDigest:f,authorizedPathCount:u.union.length,claimRevision:re(u.union)})}),y=await l();if(y.plan.unchanged)return h(y.plan,"unchanged");const _=`write-set-extension-${f.slice(0,40)}`;r=await J(t,{kind:"direct",storyId:e.storyId,sessionId:_,idempotencyKey:_,expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1},e.lockWait),r.ok||d(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-write-set-extension-backpressure":"story-write-set-extension-lock-failed");const W=r,{trackedBytes:H,tracked:Y,runtime:j,plan:v}=await l();if(v.unchanged)return h(v,"unchanged");await e.beforeCas?.();const U={schemaVersion:1,kind:"root-write-set-extension",paths:n,digest:f,approvedAt:g,approvedBy:"root_agent"};try{await Q(t,u=>{N(u,Y,e.storyId,n,Date.now()).unchanged&&d("story-write-set-extension-raced"),Z(u,e.storyId).write_set_extension=U},{expectedRevision:j.revision,preCommit:async()=>{await te(W.path,W.owner)||d("story-write-set-extension-lock-raced"),o&&await P(t,e.storyId,j),await I(c,"utf8")!==H&&d("story-write-set-extension-raced")}})}catch(u){throw u instanceof Error&&u.message==="git-lifecycle-runtime-revision-conflict"&&d("story-write-set-extension-raced"),u}return h(v,"recorded")}catch(n){if(n instanceof D)return{ok:!1,reasonCode:n.reasonCode};const s=n instanceof Error?n.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(s)?{ok:!1,reasonCode:s}:{ok:!1,reasonCode:"story-write-set-extension-failed"}}finally{r?.ok&&await ee(r.path,r.owner).catch(()=>{})}}const ne="story-write-set-manual-edit-refused",se="story-write-set-manual-edit-unverified",ie="neocortex-client story-checkpoint extend-write-set",L=/^[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/;function A(e,t){return new Promise(r=>{O("git",[...t],{cwd:e,encoding:"utf8",timeout:3e4,maxBuffer:64*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(n,s)=>r(n?void 0:String(s)))})}function T(e){if(e!==void 0)try{return w(JSON.parse(e))}catch{return}}function G(e){const t=w(e.stories)??{},r=new Map;for(const[n,s]of Object.entries(t)){const i=w(s)?.files_to_modify;i!==void 0&&r.set(n,Array.isArray(i)?JSON.stringify([...new Set(i.filter(o=>typeof o=="string"))].sort()):"!invalid")}return r}async function F(e){let t=x(e.projectRoot);const r={ok:!1,reasonCode:se};if(typeof e.storyId!="string"||!b.test(e.storyId)||e.candidateRef!==void 0&&(!L.test(e.candidateRef)||e.candidateRef.includes("..")))return r;const n=e.candidateRef===void 0?await I(C(t,".neocortex","state.json"),"utf8").catch(()=>{}):await A(t,["show",`refs/heads/${e.candidateRef}:.neocortex/state.json`]),s=T(n);if(!s)return r;const i=w(w(s.stories)?.[e.storyId]),o=typeof i?.epic_id=="string"?i.epic_id:e.storyId.split(".")[0],a=w(w(s.epics)?.[o])?.execution_branch,g=e.candidateRef===void 0?"HEAD":`refs/heads/${e.candidateRef}`;let c;if(typeof a=="string"&&L.test(a)&&!a.includes("..")&&await A(t,["rev-parse","--verify","--quiet",`refs/heads/${a}^{commit}`])!==void 0){const y=(await A(t,["merge-base",g,`refs/heads/${a}`]))?.trim();if(!y||!/^[a-f0-9]{40,64}$/.test(y))return r;c=y}else if(e.candidateRef===void 0)c="HEAD";else return r;const l=T(await A(t,["show",`${c}:.neocortex/state.json`]));if(!l)return r;const f=G(l),h=G(s);for(const[y,_]of f)if(h.get(y)!==_)return{ok:!1,reasonCode:ne};return{ok:!0,value:Object.freeze({storiesCompared:f.size})}}async function ue(e){let t=x(e.projectRoot);if(typeof e.storyId!="string"||!b.test(e.storyId))return{ok:!1,reasonCode:"story-write-set-extension-story-invalid"};if(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>R||e.paths.some(f=>!$(f)))return{ok:!1,reasonCode:"story-write-set-extension-path-invalid"};const r=await F({projectRoot:t,storyId:e.storyId});if(!r.ok)return r;const n=T(await I(C(t,".neocortex","state.json"),"utf8").catch(()=>{}));if(!n)return{ok:!1,reasonCode:"story-write-set-extension-state-invalid"};const s=w(w(n.stories)?.[e.storyId]);if(!s)return{ok:!1,reasonCode:"story-write-set-extension-story-missing"};const i=typeof s.epic_id=="string"?s.epic_id:e.storyId.split(".")[0];if(!e.storyId.startsWith(`${i}.`))return{ok:!1,reasonCode:"story-write-set-extension-story-missing"};let o;try{const h=(await S(t)).stories[e.storyId];if(h?.write_set_extension!==void 0&&!M(h.write_set_extension))return{ok:!1,reasonCode:"story-write-set-extension-invalid"};o=z(h)}catch{return{ok:!1,reasonCode:"story-write-set-extension-state-invalid"}}const a=new Set(Array.isArray(s.files_to_modify)?s.files_to_modify.filter(f=>typeof f=="string"):[]),g=new Set([...a,...o]),c=[...new Set(e.paths)].filter(f=>!g.has(f)),l=[...new Set([...o,...e.paths.filter(f=>!a.has(f))])].sort();return a.size+l.length>R?{ok:!1,reasonCode:"story-write-set-extension-too-large"}:{ok:!0,value:Object.freeze({schemaVersion:1,kind:"story-write-set-extension-request",storyId:e.storyId,epicId:i,outcome:c.length===0?"already-authorized":"requested",paths:Object.freeze(l),requestedPathCount:c.length,digest:q(l),requestedBy:"story_child",applyCommand:l.length>0?`${ie} --story ${e.storyId} --paths ${l.join(",")}`:""})}}async function le(e,t){try{const r=await S(x(e)),n=t.split(".")[0],i=(B(r,n)?.receipts??[]).map(o=>w(o)).filter(o=>o?.kind==="story-worktree-lease"&&o.storyId===t&&typeof o.temporaryBranch=="string"&&L.test(o.temporaryBranch)).sort((o,a)=>String(o.acquiredAt??"").localeCompare(String(a.acquiredAt??""))).at(-1);return i?String(i.temporaryBranch):void 0}catch{return}}export{ne as STORY_WRITE_SET_MANUAL_EDIT_REFUSED,se as STORY_WRITE_SET_MANUAL_EDIT_UNVERIFIED,F as detectStoryWriteSetManualEdit,ye as extendStoryWriteSet,ue as requestStoryWriteSetExtension,le as storyWorktreeTemporaryBranchForManualEditGate};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRejectedExecutionResult as l,createUnavailableExecutionResult as I,normalizeHeadlessCommandResult as c,runHeadlessCommand as
|
|
1
|
+
import{createRejectedExecutionResult as l,createUnavailableExecutionResult as I,normalizeHeadlessCommandResult as c,runHeadlessCommand as g,validateHeadlessAdapterExecutionInput as p}from"./types.js";import{checkRuntimeAvailability as E}from"./opencode-adapter.js";import{DEFAULT_HEADLESS_CHILD_PROFILE_NAME as b,governedPreflightFailureResult as A,preflightManagedHeadlessProfile as C,isRunnerWorktreePhase as k,preflightRunnerWorker as y,RUNNER_WORKER_PROFILE as m,runnerWorkerInstructions as w,withGovernedHeadlessEvidence as d}from"./managed-profile.js";const i="claude-code",s="claude";function _(){return{id:i,displayName:"Claude Code Headless Adapter",async checkAvailability(n={}){return E(i,s,n,{realpathBasenamePolicy:"claude-code-versioned",versionEvidence:"claude-code"})},buildInvocation(n){const e=p(n,i);return e.ok?{ok:!0,invocation:{adapterId:i,commandName:s,args:f(e.prompt,e.input.modelId,b),promptHash:e.promptHash,...e.input.modelId?{modelId:e.input.modelId}:{},timeoutMs:e.input.timeoutMs??600*1e3,publicSafe:!0},publicSafe:!0}:e},async execute(n,e={}){const t=p(n,i);if(!t.ok)return l(i,i,t);const a=k(t.input.promptKind),r=a?y(i,e):C(i,e);if(!r.ok)return A(i,t.input,r);if(e.signal?.aborted)return d(c(i,t.input,{exitCode:null,signal:"SIGTERM",timedOut:!1,cancelled:!0,durationMs:0,stdout:"",stderr:"",stdoutBytes:0,stderrBytes:0}));const u=await this.checkAvailability(e);if(!u.ok)return d(I(i,t.input,u));const o=this.buildInvocation(t.input);if(!o.ok)return l(i,i,o);const v=e.commandRunner??g,h=f(e.runnerReviewTree?"Review the staged candidate.":t.prompt,t.input.modelId,a?m:r.childProfileName,a?w(t.input,e.runnerReviewTree):void 0),R=await v(u.executablePath??s,h,{cwd:e.cwd,env:e.env,timeoutMs:o.invocation.timeoutMs,maxOutputBytes:e.maxOutputBytes,signal:e.signal,...t.input.receipt?.jobId?{localConsole:{projectRoot:e.cwd,jobId:t.input.receipt.jobId,attemptId:t.input.receipt.attemptId,executionId:t.input.receipt.executionId,publicSafe:!0}}:{}});return d(c(i,t.input,R))}}}function f(n,e,t,a){const r=["--agent",t];return a&&r.push("--agents",JSON.stringify({[m]:{description:"Neocortex story-worktree phase worker",prompt:a}}),"--permission-mode","bypassPermissions","--disallowedTools","Agent,Task","--no-session-persistence"),e&&r.push("--model",e),r.push("-p",n),r}export{_ as createClaudeCodeHeadlessAdapter};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type EpicMergeCandidateQaReceipt } from '../../../../shared/dist/yoloop/epic-terminal-git.js';
|
|
2
|
+
import { type P205TransientExecutionAuthority } from '../../git/git-lifecycle-store.js';
|
|
2
3
|
export interface EpicMergeCandidateBinding {
|
|
3
4
|
readonly originHeadSha: string;
|
|
4
5
|
readonly executionHeadSha: string;
|
|
@@ -13,3 +14,5 @@ export declare function executeEpicMergeCandidateQa(projectRoot: string, binding
|
|
|
13
14
|
readonly candidateQa: EpicMergeCandidateQaReceipt;
|
|
14
15
|
readonly candidateAuthority: EpicMergeCandidateQaAuthority;
|
|
15
16
|
}>;
|
|
17
|
+
/** Run P205 on an immutable commit without switching the user's checkout. */
|
|
18
|
+
export declare function executeDetachedCommitQa(projectRoot: string, headSha: string, graphRevision: string, nowIso?: string): Promise<P205TransientExecutionAuthority>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{execFile as
|
|
1
|
+
import{execFile as v}from"node:child_process";import{createHash as E,randomBytes as S}from"node:crypto";import{join as D}from"node:path";import{promisify as x}from"node:util";import{P205_RELEASE_GATE_BUDGETS as A}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{assertGitLifecyclePrivateDirectory as H,ensureGitLifecyclePrivateChildDirectory as j,executeP205TransientAuthority as O,gitLifecycleRuntimeDirectory as L,P205_COMPLETE_COMMAND as C,p205TransientAuthorityMatchesAggregate as P,projectP205TransientExecutionEvidence as _,removeGitLifecyclePrivateDirectory as $}from"../../git/git-lifecycle-store.js";import{anchoredCreateDirectory as q,anchoredDirectoryIdentity as m,anchoredExecuteGit as M,anchoredExecuteNode as R,anchoredExecuteNpm as T,secureFilesystemBoundaryAvailable as g}from"../../git/secure-filesystem-boundary.js";const y=x(v),k=new WeakMap;function V(o,e){const c=o&&k.get(o);if(!c||!P(c.p205,e.mergeSha,e.graphRevision))return;const s=Date.now()-c.acceptedAt;if(s<0||s>A.aggregateValidityMs)return;const a=c.receipt;return a.originHeadSha===e.originHeadSha&&a.executionHeadSha===e.executionHeadSha&&a.mergeSha===e.mergeSha&&a.graphRevision===e.graphRevision?a:void 0}async function W(o,e,c=new Date().toISOString()){if(!g())throw new Error("epic-merge-candidate-platform-unsupported");if(![e.originHeadSha,e.executionHeadSha,e.mergeSha].every(f=>/^[a-f0-9]{40,64}$/.test(f))||!/^[a-f0-9]{64}$/.test(e.graphRevision))throw new Error("epic-merge-candidate-binding-invalid");const s=async(...f)=>String((await y("git",f,{cwd:o,encoding:"utf8"})).stdout).trim(),a=(await s("rev-list","--parents","-n","1",e.mergeSha)).split(/\s+/);if(a.length!==3||a[1]!==e.originHeadSha||a[2]!==e.executionHeadSha)throw new Error("epic-merge-candidate-parents-invalid");const h=await s("rev-parse",`${e.mergeSha}^{tree}`),i=await I(o,e.mergeSha,e.graphRevision,c),t=_(i);if(!t||t.executionHeadSha!==e.mergeSha)throw new Error("epic-merge-candidate-authority-missing");const n=`merge-qa:${E("sha256").update(["epic-merge-candidate-qa-v1",e.originHeadSha,e.executionHeadSha,e.mergeSha,h,e.graphRevision,t.manifestDigest,t.resultDigest,t.gateIds.join(",")].join("\0")).digest("hex")}`,d=Object.freeze({schemaVersion:1,kind:"epic_merge_candidate_qa",contract:"P205-CI-02",command:C,...e,treeSha:h,manifestDigest:t.manifestDigest,resultDigest:t.resultDigest,gateIds:Object.freeze([...t.gateIds]),checkedAt:t.executedAt,receiptRef:n}),r=Object.freeze(Object.create(null));return k.set(r,{receipt:d,p205:i,acceptedAt:Date.now()}),{candidateQa:d,candidateAuthority:r}}async function I(o,e,c,s){if(!g())throw new Error("epic-merge-candidate-platform-unsupported");if(!/^[a-f0-9]{40,64}$/.test(e)||!/^[a-f0-9]{64}$/.test(c))throw new Error("epic-merge-candidate-binding-invalid");const a=String((await y("git",["rev-parse",`${e}^{tree}`],{cwd:o,encoding:"utf8"})).stdout).trim(),h=await L(o),i=await j(h,"detached-qa"),t=`${e.slice(0,16)}-${S(8).toString("hex")}`,n=await q(i,t),d=D(i,t),r=async(...p)=>(await M(i,t,n,p)).toString("utf8").trim();let f;try{if(await r("init","--quiet","--template="),await r("fetch","--quiet","--no-tags",o,e),await r("checkout","--quiet","--detach","FETCH_HEAD"),await r("rev-parse","HEAD")!==e||await r("rev-parse","HEAD^{tree}")!==a)throw new Error("epic-merge-candidate-checkout-invalid");const p=(await r("ls-files","--stage","-z","--","package.json","*/package.json","package-lock.json","*/package-lock.json","npm-shrinkwrap.json","*/npm-shrinkwrap.json",".npmrc","*/.npmrc")).split("\0").filter(Boolean);if(p.length>1024||p.some(u=>!/^100(?:644|755) [a-f0-9]{40,64} 0\t/.test(u)))throw new Error("epic-merge-candidate-dependency-entry-unsafe");const w=(await r("ls-files","-z","--","package-lock.json","*/package-lock.json","npm-shrinkwrap.json","*/npm-shrinkwrap.json")).split("\0").filter(Boolean);if(w.length>32)throw new Error("epic-merge-candidate-dependency-limit");const l=JSON.parse((await R(i,t,n,["-e",`
|
|
2
2
|
const fs=require('node:fs'); const path=require('node:path'); const locks=JSON.parse(process.argv[1]);
|
|
3
3
|
// npm-shrinkwrap wins over package-lock in the same installation root.
|
|
4
4
|
// Validate every selected root, not only the repository's top-level lock.
|
|
@@ -25,4 +25,4 @@ import{execFile as D}from"node:child_process";import{createHash as x,randomBytes
|
|
|
25
25
|
}
|
|
26
26
|
process.stdout.write(JSON.stringify({unsafeLinks,roots:[...selected.keys()]
|
|
27
27
|
.filter(p=>!workspacePaths.has(p)).sort((a,b)=>a.length-b.length)}));
|
|
28
|
-
`,JSON.stringify(
|
|
28
|
+
`,JSON.stringify(w)])).toString("utf8"));if(l.unsafeLinks)throw new Error("epic-merge-candidate-dependency-link-unsafe");if(l.roots.length>16)throw new Error("epic-merge-candidate-dependency-limit");for(const u of l.roots){if(u!=="."&&!/^[A-Za-z0-9_.\/-]+$/.test(u)||u.split("/").includes(".."))throw new Error("epic-merge-candidate-dependency-path-invalid");await T(i,t,n,["--prefix",u,"ci","--include=dev","--no-audit","--no-fund"])}if(await r("status","--porcelain","--untracked-files=normal"))throw new Error("epic-merge-candidate-dirty");if(f=await O(d,{headSha:e,graphRevision:c,nowIso:s,anchoredWorkspace:{parent:i,name:t,identity:n}}),await r("status","--porcelain","--untracked-files=normal")||await r("rev-parse","HEAD")!==e||await r("rev-parse","HEAD^{tree}")!==a)throw new Error("epic-merge-candidate-raced")}finally{await H(d,i);const p=await m(d);if(p.dev!==n.dev||p.ino!==n.ino)throw new Error("epic-merge-candidate-cleanup-owner-raced");if(!await $(d,i,async w=>{const l=await m(w);return l.dev===n.dev&&l.ino===n.ino}))throw new Error("epic-merge-candidate-cleanup-unverified")}return f}export{I as executeDetachedCommitQa,W as executeEpicMergeCandidateQa,V as verifiedEpicMergeCandidateReceipt};
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* P201.12 -- fixed-path managed profile and effective policy preflight.
|
|
6
6
|
*/
|
|
7
|
-
import { type HeadlessAdapterExecutionInput, type HeadlessAdapterExecutionOptions, type HeadlessAdapterExecutionResult, type HeadlessReasonCode } from './types.js';
|
|
7
|
+
import { type HeadlessAdapterExecutionInput, type HeadlessPromptKind, type HeadlessAdapterExecutionOptions, type HeadlessAdapterExecutionResult, type HeadlessReasonCode } from './types.js';
|
|
8
8
|
export declare const GOVERNED_HEADLESS_EVIDENCE: "[P201-EV-HEADLESS]";
|
|
9
9
|
type GovernedAdapterId = 'claude-code' | 'opencode';
|
|
10
10
|
/**
|
|
@@ -37,6 +37,11 @@ export type ManagedProfilePreflight = {
|
|
|
37
37
|
*/
|
|
38
38
|
export declare function classifyProfileRole(content: string): ManagedProfileRole;
|
|
39
39
|
export declare function preflightManagedHeadlessProfile(adapterId: GovernedAdapterId, options: HeadlessAdapterExecutionOptions): ManagedProfilePreflight;
|
|
40
|
+
export declare const RUNNER_WORKER_PROFILE = "neocortex-yoloop-worker";
|
|
41
|
+
export declare function runnerWorkerInstructions(input: HeadlessAdapterExecutionInput, reviewTree?: string): string;
|
|
42
|
+
export declare function isRunnerWorktreePhase(kind: HeadlessPromptKind): boolean;
|
|
43
|
+
/** A runner-local worker inherits the same managed approval gate as a profile on disk. */
|
|
44
|
+
export declare function preflightRunnerWorker(adapterId: GovernedAdapterId, options: HeadlessAdapterExecutionOptions): ManagedProfilePreflight;
|
|
40
45
|
export declare function governedPreflightFailureResult(adapterId: GovernedAdapterId, input: HeadlessAdapterExecutionInput, preflight: Extract<ManagedProfilePreflight, {
|
|
41
46
|
readonly ok: false;
|
|
42
47
|
}>): HeadlessAdapterExecutionResult;
|