@ornexus/neocortex 4.66.14 → 4.66.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/invoke.js +55 -55
  7. package/packages/client/dist/git/git-lifecycle-store.d.ts +3 -0
  8. package/packages/client/dist/git/git-lifecycle-store.js +9 -9
  9. package/packages/client/dist/git/published-story-reconciliation.js +4 -4
  10. package/packages/client/dist/git/state-json-field-merge.d.ts +5 -0
  11. package/packages/client/dist/git/state-json-field-merge.js +2 -2
  12. package/packages/client/dist/git/story-worktree-manager.d.ts +1 -0
  13. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  14. package/targets-stubs/antigravity/gemini.md +1 -1
  15. package/targets-stubs/antigravity/neocortex.md +1 -1
  16. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  17. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  18. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  19. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  20. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  21. package/targets-stubs/claude-code/neocortex.md +2 -2
  22. package/targets-stubs/codex/AGENTS.md +1 -1
  23. package/targets-stubs/codex/neocortex.toml +1 -1
  24. package/targets-stubs/cursor/agent.md +2 -2
  25. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  26. package/targets-stubs/gemini-cli/agent.md +2 -2
  27. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  28. package/targets-stubs/grok/SKILL.md +1 -1
  29. package/targets-stubs/kimi/neocortex.md +1 -1
  30. package/targets-stubs/openclaw/SKILL.md +1 -1
  31. package/targets-stubs/opencode/neocortex-root.md +2 -2
  32. package/targets-stubs/opencode/neocortex.md +2 -2
  33. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,4 +1,4 @@
1
- import{execFile as ae}from"node:child_process";import{createHash as se}from"node:crypto";import{realpath as M}from"node:fs/promises";import{promisify as ce}from"node:util";import{parseYoloopInvocation as Q}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as ue}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as de,resolveDirectYoloIntegrationAuthority as he,verifyDirectYoloIntegrationCommit as fe}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as z}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as le,mutateGitLifecycleRuntime as ye,publishedStoryReconciliationId as V,readGitLifecycleRuntime as B,readStoryWorktreeEvidence as we}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as me}from"./governance-runtime-store.js";import{parseNeocortexTrailers as K,trailerValue as P}from"./neocortex-trailers.js";import{StoryWorktreeManager as U}from"./story-worktree-manager.js";const X=ce(ae),T=/^[a-f0-9]{64}$/,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function Z(e){return se("sha256").update(e).digest("hex")}function v(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,o){let n;try{n=v(JSON.parse(e))}catch{return}if(!(n?.schemaVersion!==2||n.storyId!==o||n.publicSafe!==!0||n.status!=="qa-passed"||n.safeToContinueYoloop!==!0||!Array.isArray(n.blockingChecks)||n.blockingChecks.length!==0))return Z(e)}async function Ce(e,o){const n=Q(o);if(!n||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(n.remainder))return[];const t=ue(o);return!t||t.source!=="explicit"?[]:ee(e,t.epicId,!0)}async function Re(e,o,n){const t=Q(o)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const h=j(e);let I;try{const m=(await h("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await B(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==m)return;const[g,b,...N]=(await h("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
2
- `);if(!g||!b||!A.test(g)||!A.test(b))return;const D=K(N.join(`
3
- `),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!D.ok)return;const a=d=>P(D.values,d),p=a("Neocortex-Story");if(!p||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(p)||a("Neocortex-Epic")!==s||a("Neocortex-Execution-Branch")!==m||a("Neocortex-Prepared-Base")!==b||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(d=>T.test(a(d)??""))||k.stories[p]?.checkpoint||n.some(d=>d.storyId===p))return;const $=me(e);if(!$.ok||!$.value||v(v(v(JSON.parse($.value.toString("utf8")))?.stories)?.[p])?.epic_id!==s)return;I={storyId:p,headSha:g,executionBranch:m}}catch{return}const{storyId:u,headSha:f,executionBranch:S}=I;try{if(await z(h,S)!==f)return}catch{return{status:"pending",storyId:u,headSha:f,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const c=await de({projectRoot:e,storyId:u,commitSha:f});if(c.ok)return{status:"recovered",storyId:u,headSha:f};if(c.reasonCode==="direct-yolo-checkpoint-conflict"){const m=await B(e,{required:!0});if(v(m.stories[u]?.checkpoint)?.headSha===f)return}return{status:"pending",storyId:u,headSha:f,reasonCode:c.reasonCode}}function j(e){return async(...o)=>(await X("git",[...o],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Pe(e,o){const n=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(o);if(!n)return[];try{const s=(await X("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),n[1]):[]}catch{return[]}}function Se(e,o){return ee(e,o,!1)}async function ee(e,o,n){const t=j(e),s=async u=>(await t("rev-parse","--verify","--quiet",`${u}^{commit}`)).trim(),h=async(u,f)=>{try{return await t("merge-base","--is-ancestor",u,f),!0}catch{return!1}},I=[];try{const u=await M((await t("rev-parse","--absolute-git-dir")).trim()),f=await M((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(u!==f)return[];const S=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),c=await s("HEAD"),m=await B(e,{required:!0});if(m.epics[o]?.execution_branch!==S)return[];const k=Object.values(m.storyWorktrees?.entries??{}).filter(i=>i.epicId===o&&i.executionBranch===S&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const g=await B(e,{required:!0});if(g.stories[i.storyId]?.checkpoint||k.filter(r=>r.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const b=v(g.epics[o]?.branch_lease);if(b&&Date.parse(String(b.expiresAt))>Date.now())continue;const N=we(g,o)?.receipts??[];if(N.some(r=>r.kind==="integration-receipt"&&r.storyId===i.storyId))continue;const D=N.filter(r=>r.kind==="phase-one-receipt"&&r.storyId===i.storyId&&r.leaseId===i.leaseId&&r.graphRevision===i.graphRevision);if(D.length!==1)continue;const a=D[0],p=String(a.graphRevision),$=String(a.receiptId);if(!T.test(p)||!A.test(String(a.headSha))||a.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const H=N.filter(r=>r.kind==="published-story-reconciliation"&&r.storyId===i.storyId&&r.graphRevision===p);if(H.length>1||!n&&H.length===0)continue;const d=await he(e,i.storyId),x=d.originBinding;if(d.epicId!==o||d.executionBranch!==S||!x||x.originBranch===S||!await h(x.originHeadSha,c))continue;const l=await new U({projectRoot:e}).probe(i.leaseId);if(!l.ok||l.value.ownership!=="proven"||l.value.clean!==!0||!l.value.headSha||!A.test(l.value.headSha)||!await h(String(a.headSha),l.value.headSha))continue;const q=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${l.value.headSha}`,`${x.originHeadSha}..${c}`)).trim().split(`
4
- `).filter(Boolean);if(q.length!==1||!A.test(q[0]))continue;const y=q[0],te=(await t("show","-s","--format=%P",y)).trim();if(!A.test(te))continue;const _=K(await t("show","-s","--format=%B",y),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||P(_.values,"Neocortex-Story-Worktree-Tip")!==l.value.headSha)continue;const E=P(_.values,"Neocortex-Graph-Revision"),W=P(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!T.test(E)||!W||!T.test(W))continue;const re=(await t("rev-parse",`${y}^{tree}`)).trim(),ie=(await t("rev-parse",`${l.value.headSha}^{tree}`)).trim();if(re!==ie)continue;const Y=await fe(d,i.storyId,y,{expectedGraphRevision:E});if(!Y.ok)continue;const oe=v(JSON.parse(await t("show",`${y}:.neocortex/state.json`))),F=v(v(oe?.stories)?.[i.storyId]);if(F?.epic_id!==o||JSON.stringify(F.depends_on??[])!==JSON.stringify(d.story.depends_on??[]))continue;const C=String(a.specRef),R=`docs/stories/${i.storyId}.story.md`;if(Z(await t("show",`${y}:${C}`))!==a.specDigest||Z(await t("show",`${c}:${C}`))!==a.specDigest||await t("show",`${y}:${R}`)!==await t("show",`${c}:${R}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R);const L=ve(await t("show",`${y}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!L)continue;const w=await z(t,x.originBranch);if(!w)continue;try{await s(w)}catch{if(!n||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",w),await s(w)!==w))continue}if(!await h(x.originHeadSha,w)||!await h(y,w))continue;const G={schemaVersion:1,kind:"published-story-reconciliation",epicId:o,storyId:i.storyId,graphRevision:p,historicalGraphRevision:E,phaseOneReceiptId:$,executionBranch:S,executionHeadSha:c,originBranch:x.originBranch,originHeadSha:w,commitSha:y,bundleDigest:Y.value.bundleDigest,historicalQaDigest:L},J=async()=>{if(await s("HEAD")!==c||await s(`refs/heads/${S}`)!==c||await z(t,x.originBranch)!==w)throw new Error("published-story-reconciliation-ref-raced");const r=await new U({projectRoot:e}).probe(i.leaseId);if(!r.ok||r.value.ownership!=="proven"||r.value.clean!==!0||r.value.headSha!==l.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R)};if(H[0]){const r=H[0],ne={...G,executionHeadSha:r.executionHeadSha,originHeadSha:r.originHeadSha};if(r.receiptId!==V(ne)||!await h(r.executionHeadSha,c)||!await h(r.originHeadSha,w)||(await J(),(await B(e,{required:!0})).revision!==g.revision))continue;I.push(r);continue}const O=Object.freeze({...G,receiptId:V(G)});if(!le(O))continue;await ye(e,r=>{pe(r,o,{receipts:[O]})},{expectedRevision:g.revision,preCommit:J}),I.push(O)}catch{}}catch{}return I}export{ve as historicalStoryQaDigest,Ce as reconcilePublishedStoriesForYoloop,Re as recoverPublishedCheckpointForYoloop,Pe as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
1
+ import{execFile as se}from"node:child_process";import{createHash as ce}from"node:crypto";import{realpath as Q}from"node:fs/promises";import{promisify as ue}from"node:util";import{parseYoloopInvocation as V}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as de}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as he,resolveDirectYoloIntegrationAuthority as fe,verifyDirectYoloIntegrationCommit as le}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as G}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as ye,mutateGitLifecycleRuntime as me,publishedStoryReconciliationId as Z,readGitLifecycleRuntime as A,readStoryWorktreeEvidence as K}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as we}from"./governance-runtime-store.js";import{parseNeocortexTrailers as U,trailerValue as q}from"./neocortex-trailers.js";import{StoryWorktreeManager as X}from"./story-worktree-manager.js";const j=ue(se),R=/^[a-f0-9]{64}$/,N=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function W(e){return ce("sha256").update(e).digest("hex")}function I(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,a){let r;try{r=I(JSON.parse(e))}catch{return}if(!(r?.schemaVersion!==2||r.storyId!==a||r.publicSafe!==!0||r.status!=="qa-passed"||r.safeToContinueYoloop!==!0||!Array.isArray(r.blockingChecks)||r.blockingChecks.length!==0))return W(e)}async function Pe(e,a){const r=V(a);if(!r||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(r.remainder))return[];const t=de(a);return!t||t.source!=="explicit"?[]:te(e,t.epicId,!0)}async function qe(e,a,r){const t=V(a)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const f=ee(e);let m;try{const p=(await f("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await A(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==p)return;const[o,c,...H]=(await f("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
2
+ `);if(!o||!c||!N.test(o)||!N.test(c))return;const B=U(H.join(`
3
+ `),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!B.ok)return;const h=w=>q(B.values,w),g=h("Neocortex-Story");if(!g||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(g)||h("Neocortex-Epic")!==s||h("Neocortex-Execution-Branch")!==p||h("Neocortex-Prepared-Base")!==c||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(w=>R.test(h(w)??""))||k.stories[g]?.checkpoint||r.some(w=>w.storyId===g))return;const D=we(e);if(!D.ok||!D.value||I(I(I(JSON.parse(D.value.toString("utf8")))?.stories)?.[g])?.epic_id!==s)return;m={storyId:g,headSha:o,executionBranch:p}}catch{return}const{storyId:d,headSha:l,executionBranch:y}=m;try{if(await G(f,y)!==l)return}catch{return{status:"pending",storyId:d,headSha:l,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const u=await he({projectRoot:e,storyId:d,commitSha:l});if(u.ok)return{status:"recovered",storyId:d,headSha:l};if(u.reasonCode==="direct-yolo-checkpoint-conflict"){const p=await A(e,{required:!0});if(I(p.stories[d]?.checkpoint)?.headSha===l)return}return{status:"pending",storyId:d,headSha:l,reasonCode:u.reasonCode}}function ee(e){return async(...a)=>(await j("git",[...a],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Re(e,a){const r=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(a);if(!r)return[];try{const s=(await j("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),r[1]):[]}catch{return[]}}function Se(e,a){return te(e,a,!1)}async function te(e,a,r){const t=ee(e),s=async d=>(await t("rev-parse","--verify","--quiet",`${d}^{commit}`)).trim(),f=async(d,l)=>{try{return await t("merge-base","--is-ancestor",d,l),!0}catch{return!1}},m=[];try{const d=await Q((await t("rev-parse","--absolute-git-dir")).trim()),l=await Q((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(d!==l)return[];const y=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),u=await s("HEAD"),p=await A(e,{required:!0});if(p.epics[a]?.execution_branch!==y)return[];const k=Object.values(p.storyWorktrees?.entries??{}).filter(i=>i.epicId===a&&i.executionBranch===y&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const o=await A(e,{required:!0});if(o.stories[i.storyId]?.checkpoint||k.filter(n=>n.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const c=I(o.epics[a]?.branch_lease);if(c&&Date.parse(String(c.expiresAt))>Date.now())continue;const H=K(o,a)?.receipts??[];if(H.some(n=>n.kind==="integration-receipt"&&n.storyId===i.storyId))continue;const B=H.filter(n=>n.kind==="phase-one-receipt"&&n.storyId===i.storyId&&n.leaseId===i.leaseId&&n.graphRevision===i.graphRevision);if(B.length!==1)continue;const h=B[0],g=String(h.graphRevision),D=String(h.receiptId);if(!R.test(g)||!N.test(String(h.headSha))||h.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const $=H.filter(n=>n.kind==="published-story-reconciliation"&&n.storyId===i.storyId&&n.graphRevision===g);if($.length>1||!r&&$.length===0)continue;const w=await fe(e,i.storyId),b=w.originBinding;if(w.epicId!==a||w.executionBranch!==y||!b||b.originBranch===y||!await f(b.originHeadSha,u))continue;const v=await new X({projectRoot:e}).probe(i.leaseId);if(!v.ok||v.value.ownership!=="proven"||v.value.clean!==!0||!v.value.headSha||!N.test(v.value.headSha)||!await f(String(h.headSha),v.value.headSha))continue;const T=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${v.value.headSha}`,`${b.originHeadSha}..${u}`)).trim().split(`
4
+ `).filter(Boolean);if(T.length!==1||!N.test(T[0]))continue;const S=T[0],re=(await t("show","-s","--format=%P",S)).trim();if(!N.test(re))continue;const _=U(await t("show","-s","--format=%B",S),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||q(_.values,"Neocortex-Story-Worktree-Tip")!==v.value.headSha)continue;const E=q(_.values,"Neocortex-Graph-Revision"),Y=q(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!R.test(E)||!Y||!R.test(Y))continue;const ie=(await t("rev-parse",`${S}^{tree}`)).trim(),oe=(await t("rev-parse",`${v.value.headSha}^{tree}`)).trim();if(ie!==oe)continue;const F=await le(w,i.storyId,S,{expectedGraphRevision:E});if(!F.ok)continue;const ne=I(JSON.parse(await t("show",`${S}:.neocortex/state.json`))),L=I(I(ne?.stories)?.[i.storyId]);if(L?.epic_id!==a||JSON.stringify(L.depends_on??[])!==JSON.stringify(w.story.depends_on??[]))continue;const C=String(h.specRef),P=`docs/stories/${i.storyId}.story.md`;if(W(await t("show",`${S}:${C}`))!==h.specDigest||W(await t("show",`${u}:${C}`))!==h.specDigest||await t("show",`${S}:${P}`)!==await t("show",`${u}:${P}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P);const J=ve(await t("show",`${S}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!J)continue;const x=await G(t,b.originBranch);if(!x)continue;try{await s(x)}catch{if(!r||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",x),await s(x)!==x))continue}if(!await f(b.originHeadSha,x)||!await f(S,x))continue;const O={schemaVersion:1,kind:"published-story-reconciliation",epicId:a,storyId:i.storyId,graphRevision:g,historicalGraphRevision:E,phaseOneReceiptId:D,executionBranch:y,executionHeadSha:u,originBranch:b.originBranch,originHeadSha:x,commitSha:S,bundleDigest:F.value.bundleDigest,historicalQaDigest:J},M=async()=>{if(await s("HEAD")!==u||await s(`refs/heads/${y}`)!==u||await G(t,b.originBranch)!==x)throw new Error("published-story-reconciliation-ref-raced");const n=await new X({projectRoot:e}).probe(i.leaseId);if(!n.ok||n.value.ownership!=="proven"||n.value.clean!==!0||n.value.headSha!==v.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,P)};if($[0]){const n=$[0],ae={...O,executionHeadSha:n.executionHeadSha,originHeadSha:n.originHeadSha};if(n.receiptId!==Z(ae)||!await f(n.executionHeadSha,u)||!await f(n.originHeadSha,x)||(await M(),(await A(e,{required:!0})).revision!==o.revision))continue;m.push(n);continue}const z=Object.freeze({...O,receiptId:Z(O)});if(!ye(z))continue;await me(e,n=>{pe(n,a,{receipts:[z]})},{expectedRevision:o.revision,preCommit:M}),m.push(z)}catch{}}catch{}return m.length===0?m:xe(e,a,m,t)}async function xe(e,a,r,t){try{const s=await A(e,{required:!0}),f=(K(s,a)?.receipts??[]).filter(o=>o.kind==="integration-receipt"&&o.outcome==="integrated").sort((o,c)=>Number(c.integrationIndex)-Number(o.integrationIndex));if(f.length===0)return r;const m=String(f[0].epicHeadAfterSha),d=r[0].executionBranch;if(s.epics[a]?.execution_branch!==d)return r;const l=`refs/heads/${d}`,y=(await t("rev-parse","--verify",l)).trim(),u=async(o,c)=>{if(o===c)return!0;try{return await t("merge-base","--is-ancestor",o,c),!0}catch{return!1}},p=[...new Set([m,...r.map(o=>o.commitSha)])],k=[...p,...r.map(o=>o.executionHeadSha)];if(!(await Promise.all(k.map(o=>u(o,y)))).every(Boolean))return r;let i=y;for(const o of p)if((await Promise.all(p.map(c=>u(c,o)))).every(Boolean)){i=o;break}return(await t("rev-parse","--verify",l)).trim()!==y||(await A(e,{required:!0})).revision!==s.revision?r:r.map(o=>{const c={...o,syncBaseSha:i,syncIntegrationHeadSha:m};return Object.freeze({...c,receiptId:Z(c)})})}catch{return r}}export{ve as historicalStoryQaDigest,Pe as reconcilePublishedStoriesForYoloop,qe as recoverPublishedCheckpointForYoloop,Re as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
@@ -73,4 +73,9 @@ export declare function recomputeStateJsonEpicAggregates(input: {
73
73
  }): StateJsonEpicAggregateResult;
74
74
  /** P227-CON-STATE-MERGE: pure, deterministic 3-way field merge (R1-R7). */
75
75
  export declare function mergeStateJsonFields(input: StateJsonFieldMergeInput): StateJsonFieldMergeResult;
76
+ /** Legacy phase checkpoints can prepend locally and append on the epic.
77
+ * Permit only an intact shared sequence and new local checkpoints for this
78
+ * story. Keep arbitrary conflicting history out of the automatic sync path.
79
+ */
80
+ export declare function mergeLegacyStateForStorySync(input: StateJsonFieldMergeInput): string | undefined;
76
81
  export {};
@@ -1,2 +1,2 @@
1
- const M=33554432,l=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),C=Object.freeze(["total_stories","completed_stories","status","completed_at"]),x=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,J=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,S=Symbol("absent");class j extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function g(e,t){throw new j(e,t)}function E(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function r(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:S}function d(e,t){if(e===t)return!0;if(e===S||t===S)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>d(s,t[n]));if(E(e)){if(!E(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&d(e[n],t[n]))}return!1}function k(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&g(l.inputInvalid);let s;try{s=JSON.parse(t)}catch{g(l.inputInvalid)}E(s)||g(l.inputInvalid);for(const n of["stories","epics"]){const o=r(s,n);o!==S&&!E(o)&&g(l.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const o of Object.keys(n??{}))s.has(o)||(s.add(o),t.push(o));return t}function I(e,t,s){s===S?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function F(e,t){const s=Object.keys(e).filter(i=>r(t,i)!==S),n=Object.keys(e).filter(i=>r(t,i)===S).sort(),o={};for(const i of[...s,...n])I(o,i,e[i]);return o}function w(e,t,s,n){if(d(s,e)||d(s,t))return t;g(l.outsideAllowlist,n)}function b(e){return E(e)?e:void 0}function L(e,t,s,n,o){if(d(s,e))return t;if(E(s)||g(l.storyEntryInvalid,`stories.${n}`),(r(s,"id")!==S&&s.id!==n||r(s,"epic_id")!==S&&s.epic_id!==o)&&g(l.storyEntryInvalid,`stories.${n}`),d(t,e))return s;t!==S&&!E(t)&&g(l.storyEntryInvalid,`stories.${n}`);const i=b(e),a=b(t),m={...a??{}};for(const u of N(a,s,i)){const O=r(i,u),f=r(a,u),_=r(s,u);d(_,O)||d(_,f)?I(m,u,f):d(f,O)?I(m,u,_):g(l.storyEntryConflict,`stories.${n}.${u}`)}return m}function P(e,t,s,n){if(d(s,e)||d(s,t))return t;(!E(s)||!E(t)||e!==S&&!E(e))&&g(l.outsideAllowlist,`epics.${n}`);const o=b(e),i={...t};for(const a of N(t,s,o))C.includes(a)||I(i,a,w(r(o,a),r(t,a),r(s,a),`epics.${n}.${a}`));return i}function R(e,t,s){if(d(s,e)||d(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||g(l.outsideAllowlist,"last_updated");const o=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(o)&&o>=n?t:s}const $=new Set(["done","completed","merged"]);function D(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function z(e){const t=()=>g(l.aggregateInvalid,`epics.${e.epicId}`);E(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let o=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const _=e.stories[f];(!E(_)||_.id!==f||_.epic_id!==e.epicId)&&t(),$.has(D(_.status))&&(o+=1)}const i=n.size,a=i>0&&o===i,m=$.has(D(s.status));m&&!a&&i>0&&t(),s.total_stories=i,s.completed_stories=o;let u=!1,O=!1;return!m&&a&&(s.status="done",u=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,O=!0)),{epic:s,totalStories:i,completedStories:o,promotedDone:u,completedAtSet:O}}function G(e){return`${JSON.stringify(e,null,2)}
2
- `}function B(e){try{(!x.test(e.storyId)||!J.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&g(l.inputInvalid);const t=k(e.base).value,s=k(e.epic),n=s.value,o=k(e.story).value,i={...n};for(const c of N(n,o,t)){const p=r(t,c),y=r(n,c),A=r(o,c);c==="stories"||c==="epics"||(c==="last_updated"?I(i,c,R(p,y,A)):I(i,c,w(p,y,A,c)))}const a=b(r(t,"stories")),m=b(r(n,"stories")),u=b(r(o,"stories"));if(u||m||a){const c={...m??{}};for(const p of N(m,u,a)){const y=r(a,p),A=r(m,p),v=r(u,p);I(c,p,p===e.storyId?L(y,A,v,e.storyId,e.epicId):w(y,A,v,`stories.${p}`))}(m||Object.keys(c).length>0)&&I(i,"stories",F(c,a))}const O=b(r(t,"epics")),f=b(r(n,"epics")),_=b(r(o,"epics"));let h=!1;if(_||f||O){const c={...f??{}};for(const y of N(f,_,O)){const A=r(O,y),v=r(f,y),T=r(_,y);I(c,y,y===e.epicId?P(A,v,T,y):w(A,v,T,`epics.${y}`))}const p=r(c,e.epicId);E(p)&&Array.isArray(p.stories)&&(I(c,e.epicId,z({epicId:e.epicId,epic:p,stories:b(r(i,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),h=!0),(f||Object.keys(c).length>0)&&I(i,"epics",c)}return d(i,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:h}:{ok:!0,bytes:G(i),changed:!0,aggregatesRecomputed:h}}catch(t){return t instanceof j?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:l.inputInvalid}}}export{C as STATE_JSON_EPIC_AGGREGATE_FIELDS,M as STATE_JSON_FIELD_MERGE_MAX_BYTES,l as STATE_JSON_FIELD_MERGE_REASON_CODES,B as mergeStateJsonFields,z as recomputeStateJsonEpicAggregates,d as stateJsonValuesEqual};
1
+ const B=33554432,g=Object.freeze({inputInvalid:"state-merge-input-invalid",outsideAllowlist:"state-merge-outside-allowlist",storyEntryInvalid:"state-merge-story-entry-invalid",storyEntryConflict:"state-merge-story-entry-conflict",aggregateInvalid:"state-merge-aggregate-invalid"}),F=Object.freeze(["total_stories","completed_stories","status","completed_at"]),J=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,L=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,I=Symbol("absent");class $ extends Error{reasonCode;pointer;constructor(t,s){super(t),this.reasonCode=t,this.pointer=s}}function b(e,t){throw new $(e,t)}function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function i(e,t){return e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]:I}function l(e,t){if(e===t)return!0;if(e===I||t===I)return!1;if(Array.isArray(e))return Array.isArray(t)&&e.length===t.length&&e.every((s,n)=>l(s,t[n]));if(m(e)){if(!m(t))return!1;const s=Object.keys(e);return s.length!==Object.keys(t).length?!1:s.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&l(e[n],t[n]))}return!1}function v(e){const t=typeof e=="string"?e:e.toString("utf8");Buffer.byteLength(t,"utf8")>33554432&&b(g.inputInvalid);let s;try{s=JSON.parse(t)}catch{b(g.inputInvalid)}m(s)||b(g.inputInvalid);for(const n of["stories","epics"]){const r=i(s,n);r!==I&&!m(r)&&b(g.inputInvalid,n)}return{text:t,value:s}}function N(...e){const t=[],s=new Set;for(const n of e)for(const r of Object.keys(n??{}))s.has(r)||(s.add(r),t.push(r));return t}function A(e,t,s){s===I?delete e[t]:Object.defineProperty(e,t,{value:s,enumerable:!0,writable:!0,configurable:!0})}function P(e,t){const s=Object.keys(e).filter(o=>i(t,o)!==I),n=Object.keys(e).filter(o=>i(t,o)===I).sort(),r={};for(const o of[...s,...n])A(r,o,e[o]);return r}function w(e,t,s,n){if(l(s,e)||l(s,t))return t;b(g.outsideAllowlist,n)}function O(e){return m(e)?e:void 0}function R(e,t,s,n,r){if(l(s,e))return t;if(m(s)||b(g.storyEntryInvalid,`stories.${n}`),(i(s,"id")!==I&&s.id!==n||i(s,"epic_id")!==I&&s.epic_id!==r)&&b(g.storyEntryInvalid,`stories.${n}`),l(t,e))return s;t!==I&&!m(t)&&b(g.storyEntryInvalid,`stories.${n}`);const o=O(e),c=O(t),u={...c??{}};for(const d of N(c,s,o)){const p=i(o,d),f=i(c,d),y=i(s,d);l(y,p)||l(y,f)?A(u,d,f):l(f,p)?A(u,d,y):b(g.storyEntryConflict,`stories.${n}.${d}`)}return u}function z(e,t,s,n){if(l(s,e)||l(s,t))return t;(!m(s)||!m(t)||e!==I&&!m(e))&&b(g.outsideAllowlist,`epics.${n}`);const r=O(e),o={...t};for(const c of N(t,s,r))F.includes(c)||A(o,c,w(i(r,c),i(t,c),i(s,c),`epics.${n}.${c}`));return o}function G(e,t,s){if(l(s,e)||l(s,t))return t;const n=typeof s=="string"?Date.parse(s):Number.NaN;Number.isFinite(n)||b(g.outsideAllowlist,"last_updated");const r=typeof t=="string"?Date.parse(t):Number.NaN;return Number.isFinite(r)&&r>=n?t:s}const D=new Set(["done","completed","merged"]);function C(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[_\s]+/g,"-"):""}function M(e){const t=()=>b(g.aggregateInvalid,`epics.${e.epicId}`);m(e.epic)||t();const s={...e.epic};(s.id!==e.epicId||!Array.isArray(s.stories))&&t();const n=new Set;let r=0;for(const f of s.stories){(typeof f!="string"||f.length===0||n.has(f))&&t(),n.add(f);const y=e.stories[f];(!m(y)||y.id!==f||y.epic_id!==e.epicId)&&t(),D.has(C(y.status))&&(r+=1)}const o=n.size,c=o>0&&r===o,u=D.has(C(s.status));u&&!c&&o>0&&t(),s.total_stories=o,s.completed_stories=r;let d=!1,p=!1;return!u&&c&&(s.status="done",d=!0,(s.completed_at===void 0||s.completed_at===null)&&(s.completed_at=e.nowIso,p=!0)),{epic:s,totalStories:o,completedStories:r,promotedDone:d,completedAtSet:p}}function T(e){return`${JSON.stringify(e,null,2)}
2
+ `}function x(e){try{(!J.test(e.storyId)||!L.test(e.epicId)||!Number.isFinite(Date.parse(e.aggregateTimestamp)))&&b(g.inputInvalid);const t=v(e.base).value,s=v(e.epic),n=s.value,r=v(e.story).value,o={...n};for(const a of N(n,r,t)){const E=i(t,a),S=i(n,a),h=i(r,a);a==="stories"||a==="epics"||(a==="last_updated"?A(o,a,G(E,S,h)):A(o,a,w(E,S,h,a)))}const c=O(i(t,"stories")),u=O(i(n,"stories")),d=O(i(r,"stories"));if(d||u||c){const a={...u??{}};for(const E of N(u,d,c)){const S=i(c,E),h=i(u,E),k=i(d,E);A(a,E,E===e.storyId?R(S,h,k,e.storyId,e.epicId):w(S,h,k,`stories.${E}`))}(u||Object.keys(a).length>0)&&A(o,"stories",P(a,c))}const p=O(i(t,"epics")),f=O(i(n,"epics")),y=O(i(r,"epics"));let _=!1;if(y||f||p){const a={...f??{}};for(const S of N(f,y,p)){const h=i(p,S),k=i(f,S),j=i(y,S);A(a,S,S===e.epicId?z(h,k,j,S):w(h,k,j,`epics.${S}`))}const E=i(a,e.epicId);m(E)&&Array.isArray(E.stories)&&(A(a,e.epicId,M({epicId:e.epicId,epic:E,stories:O(i(o,"stories"))??{},nowIso:e.aggregateTimestamp}).epic),_=!0),(f||Object.keys(a).length>0)&&A(o,"epics",a)}return l(o,n)?{ok:!0,bytes:s.text,changed:!1,aggregatesRecomputed:_}:{ok:!0,bytes:T(o),changed:!0,aggregatesRecomputed:_}}catch(t){return t instanceof $?t.pointer===void 0?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:t.reasonCode,pointer:t.pointer.slice(0,256)}:{ok:!1,reasonCode:g.inputInvalid}}}function Y(e){try{const t=v(e.base).value,s=v(e.epic).value,n=v(e.story).value,r=t.checkpoints,o=s.checkpoints,c=n.checkpoints;if(l(r,c)){const _=x(e);return _.ok?_.bytes:void 0}if(!Array.isArray(r)||!Array.isArray(o)||!Array.isArray(c)||c.length<=r.length||!l(o.slice(0,r.length),r))return;const u=c.length-r.length,d=l(c.slice(u),r);if(!d&&!l(c.slice(0,r.length),r))return;const p=d?c.slice(0,u):c.slice(r.length);if(!p.every(_=>m(_)&&_.story_id===e.storyId)||p.some(_=>o.some(a=>l(_,a))))return;const f=x({...e,story:T({...n,checkpoints:r})});if(!f.ok)return;const y=v(f.bytes).value;return T({...y,checkpoints:d?[...p,...o]:[...o,...p]})}catch{return}}export{F as STATE_JSON_EPIC_AGGREGATE_FIELDS,B as STATE_JSON_FIELD_MERGE_MAX_BYTES,g as STATE_JSON_FIELD_MERGE_REASON_CODES,Y as mergeLegacyStateForStorySync,x as mergeStateJsonFields,M as recomputeStateJsonEpicAggregates,l as stateJsonValuesEqual};
@@ -188,6 +188,7 @@ export declare class StoryWorktreeManager {
188
188
  readonly leaseId: string;
189
189
  readonly integratedSha?: string;
190
190
  readonly directive?: unknown;
191
+ readonly automatic?: boolean;
191
192
  }): Promise<StoryWorktreeResult<StoryWorktreeSyncValue>>;
192
193
  status(input: {
193
194
  readonly leaseId?: string;
@@ -1,3 +1,3 @@
1
- import{execFile as ee}from"node:child_process";import{createHash as te,randomBytes as re}from"node:crypto";import{chmod as ae,lstat as x,readFile as C,realpath as b,rename as se,unlink as B,writeFile as W}from"node:fs/promises";import{homedir as oe}from"node:os";import{isAbsolute as H,join as P,resolve as ie}from"node:path";import{isDeepStrictEqual as ne}from"node:util";import{yoloopDomainHash as ce}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as de,bindStoryWorktreeLeaseEvidence as he,compactStoryWorktreeJournal as le,ensureStoryWorktreeJournal as D,isStoryWorktreeCleanupReceiptRecord as fe,mutateGitLifecycleRuntime as we,readGitLifecycleRuntime as ue}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as pe,ensurePrivateStoryWorktreeRoot as me,ensureStoryWorktreeSharedResolution as ye,resolveStoryWorktreePath as N,resolveStoryWorktreeRoot as ke,storyWorktreeIdentity as ge}from"./story-worktree-paths.js";const T="nx-owner",ve="neocortex.p225.story-worktree-receipt.v1";function L(n){return ce(ve,n)}const z=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),Ie=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,$=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Re=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function be(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==z.length||!r.every(a=>z.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&q.test(e.directiveId)&&typeof e.epicId=="string"&&F.test(e.epicId)&&typeof e.storyId=="string"&&$.test(e.storyId)&&typeof e.releasedStepId=="string"&&Ie.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&$.test(a))&&typeof e.integratedEpicHeadSha=="string"&&A.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&G.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Re.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const V=1440*60*1e3,Se=3e4,Ee=200,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,G=/^[a-f0-9]{64}$/,j=/^swt-[a-f0-9]{24}$/,q=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,F=/^P[1-9][0-9]*$/,Pe=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,_=".neocortex/pending-epic-claims.json",J=128*1024,De=/^[a-f0-9]{64}$/;function U(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!De.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function Y(n){return`docs/epics/epic-${n}.md`}function Ae(n,e){if(e===Y(n)||e===".neocortex/state.json"||e===_||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class K extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new K(n)}function Oe(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Le(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ee("git",[...e],{cwd:n,encoding:"utf8",env:Oe(),maxBuffer:8*1024*1024,timeout:Se,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function m(n,e){return(await f(n,e)).ok}async function I(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}function O(n){return te("sha256").update(n).digest("hex")}async function xe(n){try{return await x(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function M(n){try{return await x(n),!0}catch{return!1}}function Z(n){return new Promise(e=>setTimeout(e,n))}function X(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function _e(n){return n.length>0&&n.length<=512&&!H(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class ze{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ie(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>re(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=ke({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??oe(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=N({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await me(a.value,this.platform);c.ok||o(c.reasonCode);const i=N({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const h=i.value,l=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(l){if(l.state==="active"&&l.baseSha===e.baseSha&&l.graphRevision===e.graphRevision&&await this.ownershipProven(l,t))return await this.assertNoCleanupInProgress(t,l.leaseId),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};await this.reclaimStaleReservation(l,t)||o("story-worktree-entry-conflict")}await M(h)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const d=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:h,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,d),nonceDigest:O(d),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??V)).toISOString()};await this.mutate(k=>{const y=D(k);(y.entries[w.leaseId]||Object.values(y.entries).some(g=>g.worktreePath===h))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let p=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,h,e.baseSha])||o("story-worktree-add-failed"),p=!0,this.platform!=="win32"?await ae(h,448):await this.enableWindowsLongPaths(t,h);const k=await this.prepareSharedResolution(t,h,e.baseSha),y=await this.worktreeGitDir(h,t);await W(P(y,T),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:d})}
2
- `,{flag:"wx",mode:384});const g={...w,state:"active"};return await this.mutate(R=>{const v=D(R),S=v.entries[w.leaseId];(!S||S.state!=="creating"||S.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),v.entries[w.leaseId]=g}),{ok:!0,value:{...this.leaseValue(g,!1),sharedResolution:k},privatePath:h}}catch(k){throw await this.rollbackCreate(t,w,p),k}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!H(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(E=>this.samePath(E.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Pe.test(i.branch)||i.branch===s[0]?.branch||await m(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const l=(await this.readDocument()).storyWorktrees?.entries??{},d=l[r.leaseId];if(d){if(this.samePath(d.worktreePath,a)&&d.state==="active"&&await this.ownershipProven(d,t))return(d.graphRevision!==e.graphRevision||d.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await m(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,d.leaseId),await this.mutate(E=>{this.bindLeaseEvidence(E,d)}),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};o("story-worktree-entry-conflict")}Object.values(l).some(E=>this.samePath(E.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let w;await this.clean(a)||(w=await this.reconciledClaimsSidecar(a),w===void 0&&o("native-worktree-dirty"));const p=await I(a,["rev-parse","HEAD"],"story-worktree-git-failed");p!==e.baseSha&&!await m(a,["merge-base","--is-ancestor",p,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,p,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const k=await this.worktreeGitDir(a,t),y=P(k,T),g=await M(y);g&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let R;p!==e.baseSha&&(await this.alignWorktree(a,i.branch,p,e.baseSha),R=Object.freeze({mode:"fast-forward",fromSha:p,toSha:e.baseSha}));const v=P(a,"node_modules","@neocortex","shared"),S=await x(v).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:g,alignment:R})}catch(E){throw!S&&await x(v).then(Q=>Q.isSymbolicLink(),()=>!1)&&await B(v).catch(()=>{}),R&&await this.restoreAlignment(a,i.branch,p,e.baseSha),E}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),c=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!c.ok)&&o("native-worktree-align-failed");const i=c.stdout.split("\0").filter(Boolean).map(d=>d.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(d=>i.some(u=>d===u||d.startsWith(`${u}/`)||u.startsWith(`${d}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await m(e,["update-ref","-m","neocortex: adopt align",`refs/heads/${r}`,a,t])||((await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),o("native-worktree-align-failed")),(await I(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await m(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||o("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:s,temporaryBranch:c,markerPath:i,orphanMarker:h,alignment:l}=e,d=await this.prepareSharedResolution(r,s,a.baseSha);h&&await B(i);const u=this.randomNonce(),w=this.now(),p={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:O(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:c,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:O(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??V)).toISOString()};await W(i,`${JSON.stringify({schemaVersion:1,leaseId:p.leaseId,nonce:u})}
3
- `,{flag:"wx",mode:384});try{await this.mutate(y=>{const g=D(y);(g.entries[p.leaseId]||Object.values(g.entries).some(R=>this.samePath(R.worktreePath,s)))&&o("story-worktree-entry-conflict"),g.entries[p.leaseId]=p,this.bindLeaseEvidence(y,p)})}catch(y){throw await this.removeOwnMarker(i,u),y}const k={...this.leaseValue(p,!1),sharedResolution:d};return{ok:!0,value:l?{...k,alignment:l}:k,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const h=e.directive;(!be(e.directive)||h.epicId!==t.epicId||h.storyId!==t.storyId||a!==void 0&&a!==h.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(h.integratedEpicHeadSha)}(typeof a!="string"||!A.test(a))&&o("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(!await m(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const d=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(_e).sort().slice(0,Ee);return d.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}c="synced"}const i=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(h=>{const l=D(h),d=l.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),l.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!j.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!F.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await I(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await m(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await m(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,h=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${h}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:h};return fe(l)||o("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=D(d),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...l});u.cleanupReceipts.length>de;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:l,receiptDigest:L(l)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((v,S)=>S>0&&this.samePath(v.path,t.worktreePath)),c=a.some(v=>v.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),h=i.ok&&A.test(i.stdout.trim())?i.stdout.trim():void 0,l=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=l.ok&&A.test(l.stdout.trim())?l.stdout.trim():void 0,u=await xe(t.worktreePath),w=u==="present",p=t.state==="active"&&w&&await this.ownershipProven(t,r);let k,y;if(p){const v=await f(t.worktreePath,["rev-parse","HEAD"]);v.ok&&A.test(v.stdout.trim())&&(k=v.stdout.trim()),y=await this.clean(t.worktreePath)}const g=k??(w?void 0:h),R=g&&d?await m(r.mainRoot,["merge-base","--is-ancestor",g,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:p?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...h?{branchSha:h}:{},branchCheckedOut:c,...k?{headSha:k}:{},...y!==void 0?{clean:y}:{},...d?{epicHead:d}:{},...R!==void 0?{integrated:R}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof K)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=ge(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!q.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=X(await I(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!G.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!A.test(t)||!await m(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await m(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return I(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await I(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=P(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await m(s,c))return;await Z(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await C(P(t,T),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${_}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=P(e,_);try{const a=await x(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>J)return;const s=await f(e,["show",`HEAD:${_}`]);if(!s.ok||s.stdout.length>J)return;const c=U(JSON.parse(await C(t,"utf8"))),i=U(JSON.parse(s.stdout));if(!c||!i)return;const h=Object.keys(c);return h.length>=Object.keys(i).length||!h.every(l=>Object.hasOwn(i,l)&&ne(c[l],i[l]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=P(e,_),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await x(t)).mode&511;await W(a,r,{encoding:"utf8",flag:"wx",mode:s}),await se(a,t)}catch{await B(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=Y(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(h=>Ae(r,h))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!A.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await m(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{he(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:L(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[pe]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await m(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await ye({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=D(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],le(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await C(e,"utf8")).nonce===r&&await B(e)}catch{}}async listWorktrees(e){const r=X(await I(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await C(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await M(e.worktreePath)&&!await m(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=D(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return ue(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await we(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await Z(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{T as STORY_WORKTREE_MARKER_FILE,ve as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,ze as StoryWorktreeManager,L as digestStoryWorktreeReceiptLocal,X as parseWorktreeList,Le as runStoryWorktreeGit,xe as storyWorktreePathAbsence};
1
+ import{execFile as ie}from"node:child_process";import{createHash as ne,randomBytes as ce}from"node:crypto";import{chmod as de,lstat as P,mkdir as he,open as le,readFile as A,realpath as b,rename as W,rmdir as fe,unlink as C,writeFile as j}from"node:fs/promises";import{homedir as we}from"node:os";import{isAbsolute as z,join as S,resolve as ue}from"node:path";import{isDeepStrictEqual as pe}from"node:util";import{yoloopDomainHash as q}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as me,STATE_JSON_FIELD_MERGE_MAX_BYTES as ye}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ke,bindStoryWorktreeLeaseEvidence as ge,compactStoryWorktreeJournal as ve,ensureStoryWorktreeJournal as _,isStoryWorktreeCleanupReceiptRecord as Ie,mutateGitLifecycleRuntime as Re,readGitLifecycleRuntime as Se}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as be,ensurePrivateStoryWorktreeRoot as Ee,ensureStoryWorktreeSharedResolution as Pe,resolveStoryWorktreePath as G,resolveStoryWorktreeRoot as Ae,storyWorktreeIdentity as De}from"./story-worktree-paths.js";const H="nx-owner",_e="neocortex.p225.story-worktree-receipt.v1";function F(n){return q(_e,n)}const V=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),xe=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,B=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Oe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function J(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==V.length||!r.every(a=>V.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&K.test(e.directiveId)&&typeof e.epicId=="string"&&X.test(e.epicId)&&typeof e.storyId=="string"&&B.test(e.storyId)&&typeof e.releasedStepId=="string"&&xe.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&B.test(a))&&typeof e.integratedEpicHeadSha=="string"&&x.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&U.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Oe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const Y=1440*60*1e3,Ce="neocortex.p225.two-phase-release-directive-id.v1",T=".neocortex/state.json",M=".story-worktree-sync",Te=3e4,$e=200,x=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,U=/^[a-f0-9]{64}$/,N=/^swt-[a-f0-9]{24}$/,K=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,X=/^P[1-9][0-9]*$/,Be=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",Z=128*1024,We=/^[a-f0-9]{64}$/;function Q(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!We.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function ee(n){return`docs/epics/epic-${n}.md`}function je(n,e){if(e===ee(n)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class te extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new te(n)}function He(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Ze(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ie("git",[...e],{cwd:n,encoding:"utf8",env:He(),maxBuffer:8*1024*1024,timeout:Te,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function p(n,e){return(await f(n,e)).ok}async function R(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}async function re(n,e){return p(n,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function Me(n,e,r){const t=n.worktreePath,a=S(t,T),s=S(t,".neocortex"),c=S(s,M),i=S(c,"original.json"),d=S(c,"merged.json"),h=await P(a).catch(()=>{});if(!h?.isFile()||h.nlink!==1||h.size>ye||await b(a)!==a||!await p(t,["diff","--cached","--quiet"])||await p(t,["diff","--quiet","--",T])||await p(t,["cat-file","-e",`${r}:.neocortex/${M}`])||await R(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[l,u,w]=await Promise.all([f(t,["show",`${e}:${T}`]),f(t,["show",`${r}:${T}`]),f(t,["show","-s","--format=%cI",r])]);if(!l.ok||!u.ok||!w.ok||l.stdout===u.stdout)return!1;const m=await A(a),g=me({base:l.stdout,epic:u.stdout,story:m,storyId:n.storyId,epicId:n.epicId,aggregateTimestamp:w.stdout.trim()});if(g===void 0)return!1;try{await he(c,{mode:448})}catch{return!1}let y=!1,v=!1;try{const I=await le(d,"wx",h.mode&511);try{await I.writeFile(g,"utf8"),await I.sync()}finally{await I.close()}if(!(await A(a)).equals(m))return!1;await W(a,i),y=!0,(!(await A(i)).equals(m)||!await p(t,["checkout-index","--",T]))&&o("story-worktree-sync-state-backup-preserved"),await re(t,r);const k=await R(t,["rev-parse","HEAD"],"story-worktree-git-failed"),E=k===r?u.stdout:k===e?l.stdout:void 0;return(E===void 0||!(await A(a)).equals(Buffer.from(E)))&&o("story-worktree-sync-state-backup-preserved"),await W(k===r?d:i,a),v=!0,k===r}finally{(!y||v)&&(await C(i).catch(()=>{}),await C(d).catch(()=>{}),await fe(c).catch(()=>{}))}}function O(n){return ne("sha256").update(n).digest("hex")}async function Ne(n){try{return await P(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function L(n){try{return await P(n),!0}catch{return!1}}function ae(n){return new Promise(e=>setTimeout(e,n))}function se(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function Le(n){return n.length>0&&n.length<=512&&!z(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class Qe{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ue(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>ce(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=Ae({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??we(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=G({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await Ee(a.value,this.platform);c.ok||o(c.reasonCode);const i=G({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const d=i.value,h=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(h){if(h.state==="active"&&h.baseSha===e.baseSha&&h.graphRevision===e.graphRevision&&await this.ownershipProven(h,t))return await this.assertNoCleanupInProgress(t,h.leaseId),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};await this.reclaimStaleReservation(h,t)||o("story-worktree-entry-conflict")}await L(d)&&o("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const l=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:d,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,l),nonceDigest:O(l),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??Y)).toISOString()};await this.mutate(g=>{const y=_(g);(y.entries[w.leaseId]||Object.values(y.entries).some(v=>v.worktreePath===d))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let m=!1;try{await p(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha])||o("story-worktree-add-failed"),m=!0,this.platform!=="win32"?await de(d,448):await this.enableWindowsLongPaths(t,d);const g=await this.prepareSharedResolution(t,d,e.baseSha),y=await this.worktreeGitDir(d,t);await j(S(y,H),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:l})}
2
+ `,{flag:"wx",mode:384});const v={...w,state:"active"};return await this.mutate(I=>{const k=_(I),E=k.entries[w.leaseId];(!E||E.state!=="creating"||E.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),k.entries[w.leaseId]=v}),{ok:!0,value:{...this.leaseValue(v,!1),sharedResolution:g},privatePath:d}}catch(g){throw await this.rollbackCreate(t,w,m),g}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!z(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(D=>this.samePath(D.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Be.test(i.branch)||i.branch===s[0]?.branch||await p(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const h=(await this.readDocument()).storyWorktrees?.entries??{},l=h[r.leaseId];if(l){if(this.samePath(l.worktreePath,a)&&l.state==="active"&&await this.ownershipProven(l,t))return(l.graphRevision!==e.graphRevision||l.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await p(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,l.leaseId),await this.mutate(D=>{this.bindLeaseEvidence(D,l)}),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};o("story-worktree-entry-conflict")}Object.values(h).some(D=>this.samePath(D.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let w;await this.clean(a)||(w=await this.reconciledClaimsSidecar(a),w===void 0&&o("native-worktree-dirty"));const m=await R(a,["rev-parse","HEAD"],"story-worktree-git-failed");m!==e.baseSha&&!await p(a,["merge-base","--is-ancestor",m,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,m,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const g=await this.worktreeGitDir(a,t),y=S(g,H),v=await L(y);v&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let I;m!==e.baseSha&&(await this.alignWorktree(a,i.branch,m,e.baseSha),I=Object.freeze({mode:"fast-forward",fromSha:m,toSha:e.baseSha}));const k=S(a,"node_modules","@neocortex","shared"),E=await P(k).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:v,alignment:I})}catch(D){throw!E&&await P(k).then(oe=>oe.isSymbolicLink(),()=>!1)&&await C(k).catch(()=>{}),I&&await this.restoreAlignment(a,i.branch,m,e.baseSha),D}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),c=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!c.ok)&&o("native-worktree-align-failed");const i=c.stdout.split("\0").filter(Boolean).map(l=>l.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(l=>i.some(u=>l===u||l.startsWith(`${u}/`)||u.startsWith(`${l}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await p(e,["update-ref","-m","neocortex: adopt align",`refs/heads/${r}`,a,t])||((await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),o("native-worktree-align-failed")),(await R(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await p(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||o("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:s,temporaryBranch:c,markerPath:i,orphanMarker:d,alignment:h}=e,l=await this.prepareSharedResolution(r,s,a.baseSha);d&&await C(i);const u=this.randomNonce(),w=this.now(),m={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:O(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:c,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:O(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??Y)).toISOString()};await j(i,`${JSON.stringify({schemaVersion:1,leaseId:m.leaseId,nonce:u})}
3
+ `,{flag:"wx",mode:384});try{await this.mutate(y=>{const v=_(y);(v.entries[m.leaseId]||Object.values(v.entries).some(I=>this.samePath(I.worktreePath,s)))&&o("story-worktree-entry-conflict"),v.entries[m.leaseId]=m,this.bindLeaseEvidence(y,m)})}catch(y){throw await this.removeOwnMarker(i,u),y}const g={...this.leaseValue(m,!1),sharedResolution:l};return{ok:!0,value:h?{...g,alignment:h}:g,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const d=e.directive;(!J(e.directive)||d.epicId!==t.epicId||d.storyId!==t.storyId||a!==void 0&&a!==d.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(d.integratedEpicHeadSha)}if(e.automatic){const d=e.directive;(!J(d)||d.graphRevision!==t.graphRevision||Array.isArray(d.dependsOn)&&d.dependsOn.includes(t.storyId)||d.directiveId!==q(Ce,{epicId:d.epicId,storyId:d.storyId,dependsOn:d.dependsOn,integratedEpicHeadSha:d.integratedEpicHeadSha,graphRevision:d.graphRevision}))&&o("story-worktree-directive-invalid");const h=await this.assertPhaseTwo({storyId:t.storyId});(!h.ok||h.value.leaseId!==t.leaseId)&&o("story-worktree-phase-two-lease-mismatch")}(typeof a!="string"||!x.test(a))&&o("story-worktree-sync-sha-invalid"),!e.automatic&&!await this.clean(t.worktreePath)&&o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(e.automatic){await P(S(t.worktreePath,".neocortex",M)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const d=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");d!==a&&(await p(t.worktreePath,["merge-base","--is-ancestor",d,a])||o("story-worktree-sync-not-fast-forward"),!await re(t.worktreePath,a)&&!await Me(t,d,a)&&o("story-worktree-sync-conflict-preserved"),c="synced")}if(!e.automatic&&!await p(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const l=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(Le).sort().slice(0,$e);return l.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:l}}c="synced"}const i=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&i!==a&&o("story-worktree-sync-head-raced"),await this.mutate(d=>{const h=_(d),l=h.entries[t.leaseId];(!l||l.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),h.entries[t.leaseId]={...l,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!N.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!X.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await R(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await p(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,d=this.now().toISOString(),h={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${d}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:d};return Ie(h)||o("story-worktree-receipt-invalid"),await this.mutate(l=>{const u=_(l),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...h});u.cleanupReceipts.length>ke;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:h,receiptDigest:F(h)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((k,E)=>E>0&&this.samePath(k.path,t.worktreePath)),c=a.some(k=>k.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),d=i.ok&&x.test(i.stdout.trim())?i.stdout.trim():void 0,h=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),l=h.ok&&x.test(h.stdout.trim())?h.stdout.trim():void 0,u=await Ne(t.worktreePath),w=u==="present",m=t.state==="active"&&w&&await this.ownershipProven(t,r);let g,y;if(m){const k=await f(t.worktreePath,["rev-parse","HEAD"]);k.ok&&x.test(k.stdout.trim())&&(g=k.stdout.trim()),y=await this.clean(t.worktreePath)}const v=g??(w?void 0:d),I=v&&l?await p(r.mainRoot,["merge-base","--is-ancestor",v,l]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:m?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...d?{branchSha:d}:{},branchCheckedOut:c,...g?{headSha:g}:{},...y!==void 0?{clean:y}:{},...l?{epicHead:l}:{},...I!==void 0?{integrated:I}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof te)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=De(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!K.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=se(await R(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!U.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!x.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await p(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return R(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await R(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=S(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await p(s,c))return;await ae(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await A(S(t,H),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${$}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=S(e,$);try{const a=await P(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>Z)return;const s=await f(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>Z)return;const c=Q(JSON.parse(await A(t,"utf8"))),i=Q(JSON.parse(s.stdout));if(!c||!i)return;const d=Object.keys(c);return d.length>=Object.keys(i).length||!d.every(h=>Object.hasOwn(i,h)&&pe(c[h],i[h]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=S(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await P(t)).mode&511;await j(a,r,{encoding:"utf8",flag:"wx",mode:s}),await W(a,t)}catch{await C(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=ee(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(d=>je(r,d))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!x.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{ge(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:F(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[be]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await p(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await Pe({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=_(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ve(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await A(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=se(await R(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await A(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await L(e.worktreePath)&&!await p(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=_(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return Se(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await Re(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await ae(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{H as STORY_WORKTREE_MARKER_FILE,_e as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,Qe as StoryWorktreeManager,F as digestStoryWorktreeReceiptLocal,se as parseWorktreeList,Ze as runStoryWorktreeGit,Ne as storyWorktreePathAbsence};
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.66.14 | OrNexus Team
1
+ # 🧠 Neocortex v4.66.15 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
4
4
  status: native-needs-validation
5
5
  source: https://antigravity.google/docs/subagents
6
6
  tools:
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root alias of neocortex)'
6
6
  icon: '>'
7
- version: '4.66.14'
7
+ version: '4.66.15'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.66.15 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  tools:
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
113
113
  ┌────────────────────────────────────────────────────────────┐
114
114
  │ │
115
115
  │ ####### N E O C O R T E X │
116
- │ ### ######## v4.66.14 │
116
+ │ ### ######## v4.66.15 │
117
117
  │ ######### ##### │
118
118
  │ ## ############## Development Orchestrator │
119
119
  │ ## ### ###### ## OrNexus Team │
@@ -102,7 +102,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
102
102
  ┌────────────────────────────────────────────────────────────┐
103
103
  │ │
104
104
  │ ####### N E O C O R T E X │
105
- │ ### ######## v4.66.14 │
105
+ │ ### ######## v4.66.15 │
106
106
  │ ######### ##### │
107
107
  │ ## ############## Development Orchestrator │
108
108
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.66.14'
7
+ version: '4.66.15'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  permissionMode: bypassPermissions
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
113
113
  ┌────────────────────────────────────────────────────────────┐
114
114
  │ │
115
115
  │ ####### N E O C O R T E X │
116
- │ ### ######## v4.66.14 │
116
+ │ ### ######## v4.66.15 │
117
117
  │ ######### ##### │
118
118
  │ ## ############## Development Orchestrator │
119
119
  │ ## ### ###### ## OrNexus Team │
@@ -28,7 +28,7 @@ returned instructions.
28
28
 
29
29
  <!-- END: Plugin Conflict Prevention -->
30
30
 
31
- # Neocortex v4.66.14 | OrNexus Team
31
+ # Neocortex v4.66.15 | OrNexus Team
32
32
 
33
33
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
34
34
 
@@ -1,7 +1,7 @@
1
1
  # Codex custom agent reference:
2
2
  # https://developers.openai.com/codex/subagents
3
3
  name = "neocortex"
4
- description = "🧠 Neocortex v4.66.14 | OrNexus Team — Development orchestrator for direct @neocortex requests."
4
+ description = "🧠 Neocortex v4.66.15 | OrNexus Team — Development orchestrator for direct @neocortex requests."
5
5
  # [P201-EV-CODEX-GEMINI] Approval and sandbox keys are intentionally omitted.
6
6
  # Codex reapplies the parent turn's live sandbox/approval settings, including
7
7
  # --yolo, when spawning this profile. This profile must not claim child-only max.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team"
4
4
  model: inherit
5
5
  readonly: false
6
6
  is_background: false
@@ -115,7 +115,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
115
115
  ┌────────────────────────────────────────────────────────────┐
116
116
  │ │
117
117
  │ ####### N E O C O R T E X │
118
- │ ### ######## v4.66.14 │
118
+ │ ### ######## v4.66.15 │
119
119
  │ ######### ##### │
120
120
  │ ## ############## Development Orchestrator │
121
121
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
4
4
  user-invocable: true
5
5
  disable-model-invocation: false
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -73,7 +73,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
73
73
  ┌────────────────────────────────────────────────────────────┐
74
74
  │ │
75
75
  │ ####### N E O C O R T E X │
76
- │ ### ######## v4.66.14 │
76
+ │ ### ######## v4.66.15 │
77
77
  │ ######### ##### │
78
78
  │ ## ############## Development Orchestrator │
79
79
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
72
72
  ┌────────────────────────────────────────────────────────────┐
73
73
  │ │
74
74
  │ ####### N E O C O R T E X │
75
- │ ### ######## v4.66.14 │
75
+ │ ### ######## v4.66.15 │
76
76
  │ ######### ##### │
77
77
  │ ## ############## Development Orchestrator │
78
78
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team — Run development orchestration commands through the public thin client."
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team — Run development orchestration commands through the public thin client."
4
4
  ---
5
5
 
6
6
  # Neocortex for Grok Build
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
4
4
  status: native-needs-validation
5
5
  source: https://www.kimi.com/code/docs/en/kimi-code-cli/customization/agents.html
6
6
  model_preference: primary
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 | OrNexus Team — Run Neocortex commands through the public thin client in OpenClaw."
3
+ description: "🧠 Neocortex v4.66.15 | OrNexus Team — Run Neocortex commands through the public thin client in OpenClaw."
4
4
  status: skill-fallback
5
5
  user-invocable: true
6
6
  ---
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.14 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
3
+ description: "🧠 Neocortex Root Agent v4.66.15 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
4
4
  mode: primary
5
5
  color: "#00B4FF"
6
6
  permission:
@@ -74,7 +74,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
74
74
  ┌────────────────────────────────────────────────────────────┐
75
75
  │ │
76
76
  │ ####### N E O C O R T E X │
77
- │ ### ######## v4.66.14 │
77
+ │ ### ######## v4.66.15 │
78
78
  │ ######### ##### │
79
79
  │ ## ############## Development Orchestrator │
80
80
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.14 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
3
+ description: "🧠 Neocortex v4.66.15 (Pro) | OrNexus Team — Development orchestrator for *yoloop."
4
4
  mode: primary
5
5
  color: "#00B4FF"
6
6
  permission:
@@ -73,7 +73,7 @@ user's own `*yolo @docs/stories/<id>.story.md` is never refused.
73
73
  ┌────────────────────────────────────────────────────────────┐
74
74
  │ │
75
75
  │ ####### N E O C O R T E X │
76
- │ ### ######## v4.66.14 │
76
+ │ ### ######## v4.66.15 │
77
77
  │ ######### ##### │
78
78
  │ ## ############## Development Orchestrator │
79
79
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: "neocortex"
3
- description: "Neocortex v4.66.14 | OrNexus Team"
3
+ description: "Neocortex v4.66.15 | OrNexus Team"
4
4
  tools:
5
5
  # Read / Edit (built-in tool sets)
6
6
  - read
@@ -82,7 +82,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
82
82
  ┌────────────────────────────────────────────────────────────┐
83
83
  │ │
84
84
  │ ####### N E O C O R T E X │
85
- │ ### ######## v4.66.14 │
85
+ │ ### ######## v4.66.15 │
86
86
  │ ######### ##### │
87
87
  │ ## ############## Development Orchestrator │
88
88
  │ ## ### ###### ## OrNexus Team │