@ornexus/neocortex 4.61.6 → 4.64.0

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 (99) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +28 -5
  5. package/package.json +6 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/agent/update-description.d.ts +8 -1
  9. package/packages/client/dist/agent/update-description.js +2 -1
  10. package/packages/client/dist/commands/invoke.d.ts +24 -0
  11. package/packages/client/dist/commands/invoke.js +73 -73
  12. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  13. package/packages/client/dist/commands/refresh-memory.js +5 -3
  14. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  15. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +110 -10
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  18. package/packages/client/dist/git/git-lifecycle-store.d.ts +96 -2
  19. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  20. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  21. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  22. package/packages/client/dist/git/release-gate-env.d.ts +23 -0
  23. package/packages/client/dist/git/release-gate-env.js +1 -0
  24. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  25. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  26. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  27. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  28. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  29. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  30. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  31. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  32. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  33. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  34. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  35. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  36. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  37. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  38. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  39. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  40. package/packages/client/dist/runner/headless/child-env.js +1 -0
  41. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  42. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +31 -0
  43. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  44. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  45. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  46. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  47. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  48. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  49. package/packages/client/dist/runner/headless/types.js +2 -2
  50. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  51. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  52. package/packages/client/dist/state/state-json-repair.js +4 -3
  53. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  54. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  55. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  56. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  57. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  58. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  59. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  60. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  61. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  62. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  63. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  64. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  65. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  66. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  67. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  68. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +62 -1
  69. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  71. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  72. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  73. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  74. package/packages/shared/dist/compatibility/index.js +6 -0
  75. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  76. package/packages/shared/dist/project-manifest-projection.js +202 -0
  77. package/packages/shared/dist/project-validation-commands.js +14 -6
  78. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  79. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  80. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  81. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  82. package/packages/shared/dist/yoloop/epic-terminal-git.js +98 -6
  83. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  84. package/targets-stubs/antigravity/gemini.md +1 -1
  85. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  86. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  87. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  88. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  89. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  90. package/targets-stubs/claude-code/neocortex.md +5 -5
  91. package/targets-stubs/codex/AGENTS.md +1 -1
  92. package/targets-stubs/codex/install-codex.sh +12 -4
  93. package/targets-stubs/cursor/agent.md +2 -2
  94. package/targets-stubs/gemini-cli/agent.md +2 -2
  95. package/targets-stubs/lib/managed-config-merge.js +459 -5
  96. package/targets-stubs/lib/managed-profile.sh +54 -7
  97. package/targets-stubs/opencode/neocortex-root.md +1 -1
  98. package/targets-stubs/vscode/install-vscode.sh +21 -0
  99. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,3 +1,3 @@
1
- import{execFile as Ze}from"node:child_process";import{createHash as et}from"node:crypto";import{readFile as tt,realpath as ve}from"node:fs/promises";import{join as rt,resolve as Se}from"node:path";import{yoloopDomainHash as ot}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as $e,directYoloCommitIdempotencyKey as Le,directYoloWaveQaCoverage as it,finalizeDirectYoloStoryCheckpoint as at,persistDirectYoloWaveStoryCheckpoint as nt,pushDirectYoloWaveHead as st,resolveDirectYoloIntegrationAuthority as Ge,runDirectYoloWaveP205 as ct,validateDirectYoloWriteSet as dt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Ce,appendStoryWorktreeEvidence as ft,applyGitLifecycleRuntimeOverlay as gt,ensureRuntimeEpic as be,isStoryWorktreeIntegrationReceiptRecord as lt,mutateGitLifecycleRuntime as ye,publicStoryReviewArtifactFromGit as yt,readGitLifecycleRuntime as Y,readStoryWorktreeEvidence as Ke,releaseGitLifecyclePhysicalIntegrationLock as Ee,verifyGitLifecyclePhysicalIntegrationLock as Ye}from"./git-lifecycle-store.js";import{StoryWorktreeManager as Ae}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as ht}from"../private-execution/root-memory-git-evidence.js";const wt="neocortex.p225.story-worktree-receipt.v1",pt=200,he="Neocortex-Story-Worktree-Tip",ut=3e4,Oe=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,mt=/^swt-[a-f0-9]{24}$/,xe=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(a){super(a),this.reasonCode=a}}function o(e){throw new _e(e)}function Z(e,a,c){return new Promise(d=>{Ze("git",[...a],{cwd:e,encoding:"utf8",maxBuffer:32*1024*1024,timeout:ut,env:{...process.env,...c,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,w)=>{const i=r?typeof r.code=="number"?r.code:128:0;d({code:i,stdout:String(w??"")})})})}async function h(e,a,c,d){const r=await Z(e,a,d);return r.code!==0&&o(c),r.stdout.trim()}async function R(e,a){return(await Z(e,a)).code===0}function ne(e){return et("sha256").update(e).digest("hex")}function kt(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(a=>a!==""&&a!=="."&&a!=="..")}function N(e,a){const c=`${a}: `,d=e.split(`
2
- `).map(r=>r.trim()).filter(r=>r.startsWith(c));return d.length===1?d[0].slice(c.length):void 0}function He(e){return ot(wt,e)}function F(e,a){return(Ke(e,a)?.receipts??[]).filter(lt)}function we(e){const a=[...e].sort((c,d)=>c.integrationIndex-d.integrationIndex);a.forEach((c,d)=>{(c.integrationIndex!==d+1||d>0&&c.epicHeadBeforeSha!==a[d-1].epicHeadAfterSha)&&o("story-worktree-integration-chain-invalid")})}function se(e,a){const c=[...e].sort((d,r)=>r.integrationIndex-d.integrationIndex)[0];c&&c.epicHeadAfterSha!==a&&o("story-worktree-integration-chain-invalid")}const It=new Set(["done","merged","completed","released"]);function Fe(e,a,c,d,r,w=new Set){(Ke(e,c)?.receipts??[]).some(s=>s.kind==="phase-one-receipt"&&s.storyId===d||s.kind==="spec-barrier-receipt"&&Array.isArray(s.storyIds)&&s.storyIds.includes(d))||o("story-worktree-integration-unbound");const u=new Set(F(e,c).filter(s=>s.outcome==="integrated").map(s=>s.storyId));for(const s of r){if(!s.startsWith(`${c}.`))continue;const v=a[s],k=!!e.stories[s]?.checkpoint||typeof v?.status=="string"&&It.has(v.status);!u.has(s)&&!w.has(s)&&!k&&o("story-worktree-integration-dependency-waiting")}}function vt(e){const a=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",c=`int-${ne(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:c,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:a,integratedAt:e.integratedAt})}function Te(e){return ne(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Re(e){let a;return await ye(e.projectRoot,c=>{const d=F(c,e.epicId);we(d);const r=[...d].sort((i,f)=>f.integrationIndex-i.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&o("story-worktree-integration-chain-invalid"),[...d].filter(i=>i.storyId===e.storyId).sort((i,f)=>f.integrationIndex-i.integrationIndex)[0]?.outcome==="integrated"&&o("story-worktree-integration-already-integrated"),a=vt({epicId:e.epicId,storyId:e.storyId,index:d.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),ft(c,e.epicId,{receipts:[a]})},{preCommit:async()=>{await h(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&o("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await R(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&o("story-worktree-integration-epic-head-raced")}}),a}function pe(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:He(e.receipt)})}}async function St(e){let a,c,d="";const r=Se(e.projectRoot);try{(typeof e.storyId!="string"||!xe.test(e.storyId))&&o("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!mt.test(e.leaseId)&&o("story-worktree-integration-lease-invalid");const w=await ve(await h(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),i=await ve(await h(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));w!==i&&o("story-worktree-integration-not-root");let f;try{f=await Ge(r,e.storyId)}catch(l){o(l instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(l.message)?l.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:s}=f;d=g;const v=new Date(e.nowIso??Date.now()).toISOString(),k=`refs/heads/${u}`,p=await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing");await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&o("story-worktree-integration-root-head-mismatch");const _=f.originBinding;(!_||!await R(r,["merge-base","--is-ancestor",_.originHeadSha,p]))&&o("story-worktree-integration-origin-binding-invalid");const A=await Y(r,{required:!0}),S=F(A,g);we(S);const z=S.filter(l=>l.storyId===s).sort((l,b)=>b.integrationIndex-l.integrationIndex),E=A.stories[s]?.checkpoint;if(z[0]?.outcome==="integrated")return pe({storyId:s,epicId:g,outcome:"already-integrated",receipt:z[0],...E?.headSha?{checkpointHeadSha:E.headSha}:{}});const ce=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(l=>typeof l=="string"):[],T=await Ue(r,A);Fe(A,T,g,s,ce);const D=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));if(E&&typeof E.headSha=="string"){const l=E.headSha,b=await h(r,["show","--no-patch","--format=%B",l],"story-worktree-integration-git-failed");(N(b,"Neocortex-Story")!==s||!N(b,he))&&o("story-worktree-integration-checkpoint-not-worktree"),l!==p&&o("story-worktree-integration-epic-head-raced"),se(S,E.baseSha);const X=await Ve(r,s,`recover-${l.slice(0,40)}`,()=>Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:E.baseSha,after:l,checkpointDigest:Te(E),outcome:"integrated",integratedAt:v})),oe=D.length===1?await Pe(r,D[0].leaseId,l):!1;return pe({storyId:s,epicId:g,outcome:"integrated",receipt:X,checkpointHeadSha:l,worktreeRealigned:oe})}const q=Object.values(A.storyWorktrees?.entries??{}).filter(l=>l.storyId===s&&l.epicId===g&&l.state==="active"&&(e.leaseId===void 0||l.leaseId===e.leaseId));q.length===0&&o("story-worktree-integration-lease-missing"),q.length>1&&o("story-worktree-integration-lease-ambiguous");const C=q[0];C.executionBranch!==u&&o("story-worktree-integration-lease-invalid");const M=await new Ae({projectRoot:r}).probe(C.leaseId);(!M.ok||M.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),M.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const ee=await h(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");M.value.headSha!==ee&&o("story-worktree-integration-worktree-dirty");const O=await h(r,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),J=N(O,he)===ee&&N(O,"Neocortex-Story")===s;let x,P,m,K=!1;if(J){x=await h(r,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),P=p;const l=N(O,"Neocortex-Bundle-Digest")??"",b=N(O,"Neocortex-Claim-Revision")??"";m=Le({storyId:s,epicId:g,executionBranch:u,baseSha:x,bundleDigest:l,graphRevision:f.graphRevision,claimRevision:b}),se(S,x)}else{se(S,p);const l=await Je(r,f,s,p,ee);if(l.kind==="conflict")return await je({projectRoot:r,epicId:g,storyId:s,executionBranch:u,epicHead:p,tip:ee,conflictPaths:l.conflictPaths,integratedAt:v,chain:z});const b=l.changedPaths;P=l.commitSha,m=l.idempotencyKey,x=p,K=!0,(!await R(r,["diff","--cached","--quiet"])||!await R(r,["diff","--quiet","HEAD","--",...b]))&&o("story-worktree-integration-root-dirty")}const U=await Y(r,{required:!0}),B=U.epics[g]?.branch_lease,te=B&&B.ownerStoryId===s&&B.sessionId===m&&B.idempotencyKey===m&&Date.parse(String(B.expiresAt))>Date.now()?B:void 0;B&&!te&&Date.parse(String(B.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const W=te??{schemaVersion:1,ownerStoryId:s,sessionId:m,idempotencyKey:m,acquiredAt:v,expiresAt:new Date(Date.parse(v)+$e).toISOString()};a=await Ce(r,{kind:"direct",storyId:s,sessionId:m,idempotencyKey:m,expiresAt:String(W.expiresAt),persistent:!0,createdAt:String(W.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const $=a;te||(await ye(r,l=>{const b=be(l,g),X=b.branch_lease;X&&Date.parse(String(X.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(b.origin_binding)!==JSON.stringify(_)&&o("story-worktree-integration-origin-binding-invalid"),b.graph_revision!==f.graphRevision&&o("story-worktree-integration-graph-revision-raced"),b.branch_lease=W},{expectedRevision:U.revision,preCommit:async l=>{await Ye($.path,$.owner)||o("story-worktree-integration-lock-raced");const b=F(l,g);we(b),se(b,x),await h(r,["rev-parse",k],"story-worktree-integration-epic-branch-missing")!==p&&o("story-worktree-integration-epic-head-raced")}}),c=W),K&&((await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),await R(r,["merge","--ff-only","--no-edit",P])||o("story-worktree-integration-ff-refused"),await h(r,["rev-parse",k],"story-worktree-integration-git-failed")!==P&&o("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let V;const re=await at({projectRoot:r,storyId:s,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const l=(await Y(r,{required:!0})).stories[s]?.checkpoint;(!l||l.headSha!==P||l.baseSha!==x)&&o("story-worktree-integration-checkpoint-mismatch"),V=await Re({projectRoot:r,epicId:g,storyId:s,executionBranch:u,before:x,after:P,checkpointDigest:Te(l),outcome:"integrated",integratedAt:v})}});if(!re.ok)return{ok:!1,reasonCode:re.reasonCode};const j=re.value;(j.headSha!==P||j.baseSha!==x||!V)&&o("story-worktree-integration-checkpoint-mismatch");const de=await Pe(r,C.leaseId,P);return pe({storyId:s,epicId:g,outcome:"integrated",receipt:V,checkpointHeadSha:P,worktreeRealigned:de})}catch(w){if(w instanceof _e)return{ok:!1,reasonCode:w.reasonCode};const i=w instanceof Error?w.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(i)?{ok:!1,reasonCode:i}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const w=c;await ye(r,i=>{const f=be(i,d),g=f.branch_lease;g&&g.sessionId===w.sessionId&&g.idempotencyKey===w.idempotencyKey&&g.acquiredAt===w.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}async function Je(e,a,c,d,r){const{epicId:w,executionBranch:i}=a;await R(e,["merge-base","--is-ancestor",r,d])&&o("story-worktree-integration-range-empty");const f=await h(e,["merge-base",d,r],"story-worktree-integration-unrelated-history"),g=await Z(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,d,r]);g.code!==0&&g.code!==1&&o("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),s=u[0]?.trim()??"";if(Oe.test(s)||o("story-worktree-integration-git-unsupported"),g.code===1){const C=[...new Set(u.slice(1).filter(kt))].sort().slice(0,pt);return C.length===0&&o("story-worktree-integration-git-failed"),{kind:"conflict",conflictPaths:C}}const v=(await h(e,["diff","--name-only","-z",d,s],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),k=dt(v,a.authorizedWriteSet,c,a.rootMemoryEffect);k.ok||o(k.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const p=yt(e,c,s);p?.verdict!=="approved"&&o("story-worktree-integration-review-not-approved");const _=await Z(e,["diff","--binary","--full-index",d,s]);_.code!==0&&o("story-worktree-integration-git-failed");const A=_.stdout;A||o("story-worktree-integration-range-empty");const S=ne(A),z=ne([...a.authorizedWriteSet].sort().join("\0")),E=Le({storyId:c,epicId:w,executionBranch:i,baseSha:d,bundleDigest:S,graphRevision:a.graphRevision,claimRevision:z}),ce=(await h(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${c}): integrate story worktree`,T=[`Neocortex-Story: ${c}`,`Neocortex-Epic: ${w}`,`Neocortex-Execution-Branch: ${i}`,`Neocortex-Prepared-Base: ${d}`,`Neocortex-Bundle-Digest: ${S}`,`Neocortex-Review-Artifact-Digest: ${p.digest}`,`Neocortex-Graph-Revision: ${a.graphRevision}`,`Neocortex-Claim-Revision: ${z}`,...a.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${ht(a.rootMemoryEffect)}`]:[],`${he}: ${r}`],D=(await h(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");D.length!==6&&o("story-worktree-integration-git-failed");const q=await h(e,["commit-tree",s,"-p",d,"-m",ce,"-m",`Story: ${c}`,"-m",T.join(`
3
- `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:D[0],GIT_AUTHOR_EMAIL:D[1],GIT_AUTHOR_DATE:D[2],GIT_COMMITTER_NAME:D[3],GIT_COMMITTER_EMAIL:D[4],GIT_COMMITTER_DATE:D[5]});return Oe.test(q)||o("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:q,changedPaths:v,idempotencyKey:E}}async function Ue(e,a){const c=JSON.parse(await tt(rt(e,".neocortex","state.json"),"utf8")),r=gt(c,a).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function Ve(e,a,c,d){const r=await Ce(e,{kind:"direct",storyId:a,sessionId:c,idempotencyKey:c,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||o(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await d()}finally{await Ee(r.path,r.owner).catch(()=>{})}}async function Pe(e,a,c){const d=await new Ae({projectRoot:e}).probe(a);return!d.ok||d.value.ownership!=="proven"||d.value.clean!==!0?!1:R(d.value.entry.worktreePath,["reset","--keep",c])}async function je(e){const a=ne(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),c=e.chain[0];if(c?.outcome==="conflict-reopened"&&c.epicHeadAfterSha===e.epicHead&&c.checkpointDigest===a)return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:c,conflictPaths:Object.freeze([...e.conflictPaths])});const d=()=>Re({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:a,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await d():await Ve(e.projectRoot,e.storyId,`conflict-${a.slice(0,48)}`,d);return pe({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const bt=64;function At(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function Pt(e){let a,c,d="",r=0,w;const i=Se(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>bt||new Set(f).size!==f.length||f.some(t=>typeof t!="string"||!xe.test(t)))&&o("story-worktree-wave-stories-invalid");const g=await ve(await h(i,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await ve(await h(i,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&o("story-worktree-integration-not-root");const s=new Map;for(const t of f)try{s.set(t,await Ge(i,t))}catch(n){o(n instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(n.message)?n.message:"story-worktree-integration-authority-invalid")}const v=s.get(f[0]),{epicId:k,executionBranch:p}=v;for(const t of s.values())(t.epicId!==k||t.executionBranch!==p||t.graphRevision!==v.graphRevision||JSON.stringify(t.originBinding)!==JSON.stringify(v.originBinding))&&o("story-worktree-wave-epic-mixed");d=k;const _=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,S=await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==S||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&o("story-worktree-integration-root-head-mismatch");const z=v.originBinding;(!z||!await R(i,["merge-base","--is-ancestor",z.originHeadSha,S]))&&o("story-worktree-integration-origin-binding-invalid");const E=t=>{const n=s.get(t).story;return Array.isArray(n.depends_on)?n.depends_on.filter(y=>typeof y=="string"):[]},ce=new Map(f.map((t,n)=>[t,n]));f.forEach((t,n)=>{for(const y of E(t)){const I=ce.get(y);I!==void 0&&I>=n&&o("story-worktree-wave-order-invalid")}});const T=await Y(i,{required:!0}),D=F(T,k);we(D);const q=t=>D.filter(n=>n.storyId===t).sort((n,y)=>y.integrationIndex-n.integrationIndex)[0],C=f.filter(t=>q(t)?.outcome!=="integrated"),G=new Map(f.filter(t=>!C.includes(t)).map(t=>{const n=q(t),y=T.stories[t]?.checkpoint;return[t,Object.freeze({storyId:t,outcome:"already-integrated",receiptDigest:He(n),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),M=t=>({ok:!0,value:Object.freeze({epicId:k,...t,gateRuns:r,stories:Object.freeze(f.map(n=>G.get(n)??Object.freeze({storyId:n,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return M({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0});const ee=new Set(C),O=[];let J=S;for(let t=0;t<C.length;t++){const n=await h(i,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed"),y=N(n,"Neocortex-Story");if(!y||!ee.has(y)||!N(n,he))break;O.unshift(J),J=await h(i,["rev-parse",`${J}^`],"story-worktree-integration-git-failed")}const x=J;se(D,x);const P=await Ue(i,T),m=[];let K,U=x;for(const[t,n]of C.entries()){const y=s.get(n);Fe(T,P,k,n,E(n),new Set(C.slice(0,t)));const I=Object.values(T.storyWorktrees?.entries??{}).filter(L=>L.storyId===n&&L.epicId===k&&L.state==="active"),H=T.stories[n]?.checkpoint;if(H&&typeof H.headSha=="string"){const L=H.headSha,We=await h(i,["show","--no-patch","--format=%B",L],"story-worktree-integration-git-failed");(N(We,"Neocortex-Story")!==n||!N(We,he))&&o("story-worktree-integration-checkpoint-not-worktree"),(H.baseSha!==U||O[t]!==L)&&o("story-worktree-integration-checkpoint-mismatch");const Qe=(await h(i,["diff-tree","--no-commit-id","--name-only","-r","-z",L],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);m.push({storyId:n,sha:L,changedPaths:Qe,...I.length===1?{leaseId:I[0].leaseId}:{}}),U=L;continue}I.length===0&&o("story-worktree-integration-lease-missing"),I.length>1&&o("story-worktree-integration-lease-ambiguous");const ke=I[0];ke.executionBranch!==p&&o("story-worktree-integration-lease-invalid");const Ie=await new Ae({projectRoot:i}).probe(ke.leaseId);(!Ie.ok||Ie.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),Ie.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const De=await h(i,["rev-parse",`refs/heads/${ke.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ie.value.headSha!==De&&o("story-worktree-integration-worktree-dirty");const ae=await Je(i,y,n,U,De);if(ae.kind==="conflict"){t<O.length&&o("story-worktree-wave-resume-mismatch"),K={storyId:n,tip:De,conflictPaths:ae.conflictPaths};break}t<O.length&&O[t]!==ae.commitSha&&o("story-worktree-wave-resume-mismatch"),m.push({storyId:n,sha:ae.commitSha,changedPaths:ae.changedPaths,leaseId:ke.leaseId}),U=ae.commitSha}if(m.length<O.length&&o("story-worktree-wave-resume-mismatch"),m.length===0){const t=K,n=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:S,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:D.filter(y=>y.storyId===t.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return n.ok?(G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:n.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])})),M({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:S,epicHeadAfterSha:S,gateRunCap:0})):{ok:!1,reasonCode:n.reasonCode,gateRuns:r}}const B=m[m.length-1].sha,te=[...new Set(m.flatMap(t=>t.changedPaths))].sort();(!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-root-dirty");const W=At(m.length),$=ne(["p205-wave-lease-v1",k,p,x,...m.map(t=>t.sha)].join("\0")),V=m[0].storyId,re=await Y(i,{required:!0}),j=re.epics[k]?.branch_lease,de=j&&j.ownerStoryId===V&&j.sessionId===$&&j.idempotencyKey===$&&Date.parse(String(j.expiresAt))>Date.now()?j:void 0;j&&!de&&Date.parse(String(j.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const l=de??{schemaVersion:1,ownerStoryId:V,sessionId:$,idempotencyKey:$,acquiredAt:_,expiresAt:new Date(Date.parse(_)+$e*W).toISOString()};a=await Ce(i,{kind:"direct",storyId:V,sessionId:$,idempotencyKey:$,expiresAt:String(l.expiresAt),persistent:!0,createdAt:String(l.acquiredAt)}),a.ok||o(a.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const b=a;de||await ye(i,t=>{const n=be(t,k),y=n.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(n.origin_binding)!==JSON.stringify(z)&&o("story-worktree-integration-origin-binding-invalid"),n.graph_revision!==v.graphRevision&&o("story-worktree-integration-graph-revision-raced"),n.branch_lease=l},{expectedRevision:re.revision,preCommit:async t=>{await Ye(b.path,b.owner)||o("story-worktree-integration-lock-raced");const n=F(t,k);we(n),se(n,x),await h(i,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==S&&o("story-worktree-integration-epic-head-raced")}}),c=l;const X=new Set(m.map(t=>t.sha));let oe=!0;if(e.push&&O.length>0){const t=(await Z(i,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";Oe.test(t)&&await R(i,["merge-base","--is-ancestor",O[0],t])&&(oe=!1)}let ie=S;const ue=async t=>{if((await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==ie||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ie||await h(i,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&o("story-worktree-integration-epic-head-raced"),ie===t)return;const n=await R(i,["merge-base","--is-ancestor",ie,t]);!n&&(!oe||!X.has(ie))&&o("story-worktree-wave-pushed-immovable"),(!(n?await R(i,["merge","--ff-only","--no-edit",t]):await R(i,["reset","--keep",t]))||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==t||await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==t)&&o("story-worktree-integration-ff-refused"),ie=t};w=oe?{epicRef:A,base:x,owned:X}:void 0,await ue(B),await e.afterWaveFastForward?.();const Xe=[...new Set([v.graphRevision,...m.map(t=>T.stories[t.storyId]?.checkpoint?.graphRevision).filter(t=>typeof t=="string")])],ze=async t=>{const n=m[t];await ue(n.sha),r>=W&&o("story-worktree-wave-gate-cap-exceeded"),r++;const y=await ct({projectRoot:i,headSha:n.sha,storyId:n.storyId,graphRevisions:Xe,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await h(i,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==n.sha||await h(i,["rev-parse",A],"story-worktree-integration-git-failed")!==n.sha||!await R(i,["diff","--cached","--quiet"])||!await R(i,["diff","--quiet","HEAD","--",...te]))&&o("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&o(y.reasonCode),y},me=await ze(m.length-1);let Be=m.length-1,Ne=me.ok?me.authorities:void 0,fe,ge;if(!me.ok){oe||o("story-worktree-wave-gate-failed-pushed");let t=-1,n=m.length-1;for(ge=me.reasonCode;n-t>1;){const I=Math.floor((t+n)/2),H=await ze(I);H.ok?(t=I,Ne=H.authorities):(n=I,ge=H.reasonCode)}fe=n,Be=t;const y=m[n].storyId;if(G.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:ge})),t<0)return await ue(x),w=void 0,M({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:ge,epicHeadBeforeSha:S,epicHeadAfterSha:x,gateRunCap:W});await ue(m[t].sha)}const Q=m.slice(0,Be+1),le=Q[Q.length-1].sha,qe=it({epicId:k,executionBranch:p,waveHeadSha:le,waveStoryIds:Q.map(t=>t.storyId),waveCommitShas:Q.map(t=>t.sha)});e.push&&(w=void 0,await st(i,e.remote??"origin",p,le)||o("story-worktree-wave-remote-head-mismatch")),w=void 0;const Me=[];for(const[t,n]of Q.entries()){const y=t===0?x:Q[t-1].sha,I=await nt({projectRoot:i,storyId:n.storyId,headSha:n.sha,coverage:qe,authorities:Ne,expectedLease:l,physicalLock:b,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||o(I.reasonCode),(I.value.headSha!==n.sha||I.value.baseSha!==y)&&o("story-worktree-integration-checkpoint-mismatch");const H=await Re({projectRoot:i,epicId:k,storyId:n.storyId,executionBranch:p,before:y,after:n.sha,checkpointDigest:Te(I.value),outcome:"integrated",integratedAt:_,expectedEpicHead:le});Me.push(n.storyId),G.set(n.storyId,Object.freeze({storyId:n.storyId,outcome:"integrated",checkpointHeadSha:n.sha,receiptDigest:He(H)})),await e.afterWaveStoryPersist?.(n.storyId)}if(K&&fe===void 0){const t=K,n=await Y(i,{required:!0}),y=await je({projectRoot:i,epicId:k,storyId:t.storyId,executionBranch:p,epicHead:le,tip:t.tip,conflictPaths:t.conflictPaths,integratedAt:_,chain:F(n,k).filter(I=>I.storyId===t.storyId).sort((I,H)=>H.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||o(y.reasonCode),G.set(t.storyId,Object.freeze({storyId:t.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...t.conflictPaths])}))}for(const t of Q){if(!t.leaseId)continue;const n=await Pe(i,t.leaseId,t.sha);G.set(t.storyId,Object.freeze({...G.get(t.storyId),worktreeRealigned:n}))}return M({outcome:fe!==void 0?"gate-failed":K?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Me),...fe!==void 0?{failedStoryId:m[fe].storyId,failureReasonCode:ge}:{},epicHeadBeforeSha:S,epicHeadAfterSha:le,qaCoverage:qe,gateRunCap:W})}catch(f){let g=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(w){const u=w,s=(await Z(i,["rev-parse",u.epicRef])).stdout.trim(),v=(await Z(i,["rev-parse","HEAD"])).stdout.trim();s!==u.base&&(s!==v||!u.owned.has(s)||!await R(i,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:r}}finally{if(a?.ok&&await Ee(a.path,a.owner).catch(()=>{}),c&&d){const f=c;await ye(i,g=>{const u=be(g,d),s=u.branch_lease;s&&s.sessionId===f.sessionId&&s.idempotencyKey===f.idempotencyKey&&s.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function jt(e){const a=e.integrationOrder;if(!Array.isArray(a)||a.length===0||new Set(a).size!==a.length||a.some(g=>typeof g!="string"||!xe.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const c=e.integrate??St,d=new Set(e.readyStoryIds),r=Se(e.projectRoot);let w;try{const g=await Y(r,{required:!0}),u=new Set(a.map(s=>s.split(".")[0]));w=new Set([...u].flatMap(s=>F(g,s)).filter(s=>s.outcome==="integrated").map(s=>s.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const i=[],f=[];for(const g of a){if(w.has(g))continue;if(!d.has(g))return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:s,integrate:v,...k}=e,p=await c({...k,projectRoot:r,storyId:g});if(i.push({storyId:g,result:p}),!p.ok)return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:i,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),w.add(g)}return{results:i,integratedStoryIds:f}}async function zt(e){const a=Se(e.projectRoot),c=e.manager??new Ae({projectRoot:a});let d;try{d=await Y(a,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const w of e.directives){const i=w&&typeof w=="object"&&!Array.isArray(w)?w:void 0,f=typeof i?.storyId=="string"&&xe.test(i.storyId)?i.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(d.storyWorktrees?.entries??{}).filter(s=>s.storyId===f&&s.state==="active");if(g.length!==1){r.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await c.sync({leaseId:g[0].leaseId,directive:w});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,wt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,bt as STORY_WORKTREE_WAVE_MAX_STORIES,He as digestStoryWorktreeIntegrationReceipt,St as integrateStoryWorktree,Pt as integrateStoryWorktreeWave,jt as integrateStoryWorktreesInOrder,At as storyWorktreeWaveGateRunCap,zt as syncReleasedDependents};
1
+ import{execFile as Xe}from"node:child_process";import{createHash as wt}from"node:crypto";import{readFile as pt,realpath as be}from"node:fs/promises";import{join as ut,resolve as Ae}from"node:path";import{yoloopDomainHash as mt}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as Qe,directYoloCommitIdempotencyKey as Ze,directYoloWaveQaCoverage as kt,finalizeDirectYoloStoryCheckpoint as It,persistDirectYoloWaveStoryCheckpoint as vt,pushDirectYoloWaveHead as St,resolveDirectYoloIntegrationAuthority as et,runDirectYoloWaveP205 as bt,validateDirectYoloWriteSet as At}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Be,appendStoryWorktreeEvidence as xt,applyGitLifecycleRuntimeOverlay as Rt,ensureRuntimeEpic as xe,isStoryWorktreeIntegrationReceiptRecord as Et,mutateGitLifecycleRuntime as we,publicStoryReviewArtifactFromGit as _t,readGitLifecycleRuntime as U,readStoryWorktreeEvidence as tt,releaseGitLifecyclePhysicalIntegrationLock as je,verifyGitLifecyclePhysicalIntegrationLock as rt}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ot,STATE_JSON_FIELD_MERGE_MAX_BYTES as Tt}from"./state-json-field-merge.js";import{StoryWorktreeManager as Re}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Ct}from"../private-execution/root-memory-git-evidence.js";const Dt="neocortex.p225.story-worktree-receipt.v1",Pt=200,pe="Neocortex-Story-Worktree-Tip",ot=3e4,ce=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Ht=/^swt-[a-f0-9]{24}$/,Ee=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class _e extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new _e(e)}const it=32*1024*1024;function P(e,t,s){return new Promise(a=>{Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,...s,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;a({code:n,stdout:String(g??"")})})})}function nt(e,t,s){return new Promise(a=>{const r=Xe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:it,timeout:ot,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const f=g?typeof g.code=="number"?g.code:128:0;a({code:f,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(s)})}async function p(e,t,s,a){const r=await P(e,t,a);return r.code!==0&&i(s),r.stdout.trim()}async function O(e,t){return(await P(e,t)).code===0}function de(e){return wt("sha256").update(e).digest("hex")}function at(e){return e.length>0&&e.length<=1024&&!e.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(e)&&!e.includes("\\")&&!e.includes("\0")&&e.split("/").every(t=>t!==""&&t!=="."&&t!=="..")}function q(e,t){const s=`${t}: `,a=e.split(`
2
+ `).map(r=>r.trim()).filter(r=>r.startsWith(s));return a.length===1?a[0].slice(s.length):void 0}function Ne(e){return mt(Dt,e)}function V(e,t){return(tt(e,t)?.receipts??[]).filter(Et)}function ue(e){const t=[...e].sort((s,a)=>s.integrationIndex-a.integrationIndex);t.forEach((s,a)=>{(s.integrationIndex!==a+1||a>0&&s.epicHeadBeforeSha!==t[a-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function fe(e,t){const s=[...e].sort((a,r)=>r.integrationIndex-a.integrationIndex)[0];s&&s.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const Bt=new Set(["done","merged","completed","released"]);function st(e,t,s,a,r,g=new Set){(tt(e,s)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===a||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(a))||i("story-worktree-integration-unbound");const u=new Set(V(e,s).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of r){if(!d.startsWith(`${s}.`))continue;const S=t[d],m=!!e.stories[d]?.checkpoint||typeof S?.status=="string"&&Bt.has(S.status);!u.has(d)&&!g.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function jt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",s=`int-${de(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:s,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function ze(e){return de(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Oe(e){let t;return await we(e.projectRoot,s=>{const a=V(s,e.epicId);ue(a);const r=[...a].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...a].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=jt({epicId:e.epicId,storyId:e.storyId,index:a.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),xt(s,e.epicId,{receipts:[t]})},{preCommit:async()=>{await p(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await O(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function me(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:Ne(e.receipt)})}}async function Nt(e){let t,s,a="";const r=Ae(e.projectRoot);try{(typeof e.storyId!="string"||!Ee.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Ht.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const g=await be(await p(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await be(await p(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&i("story-worktree-integration-not-root");let f;try{f=await et(r,e.storyId)}catch(y){i(y instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(y.message)?y.message:"story-worktree-integration-authority-invalid")}const{epicId:l,executionBranch:u,storyId:d}=f;a=l;const S=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,h=await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h&&i("story-worktree-integration-root-head-mismatch");const D=f.originBinding;(!D||!await O(r,["merge-base","--is-ancestor",D.originHeadSha,h]))&&i("story-worktree-integration-origin-binding-invalid");const b=await U(r,{required:!0}),I=V(b,l);ue(I);const H=I.filter(y=>y.storyId===d).sort((y,x)=>x.integrationIndex-y.integrationIndex),A=b.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return me({storyId:d,epicId:l,outcome:"already-integrated",receipt:H[0],...A?.headSha?{checkpointHeadSha:A.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(y=>typeof y=="string"):[],R=await ft(r,b);st(b,R,l,d,G);const j=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));if(A&&typeof A.headSha=="string"){const y=A.headSha,x=await p(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed");(q(x,"Neocortex-Story")!==d||!q(x,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),y!==h&&i("story-worktree-integration-epic-head-raced"),fe(I,A.baseSha);const ee=await lt(r,d,`recover-${y.slice(0,40)}`,()=>Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:A.baseSha,after:y,checkpointDigest:ze(A),outcome:"integrated",integratedAt:S})),ne=j.length===1?await $e(r,j[0].leaseId,y):!1;return me({storyId:d,epicId:l,outcome:"integrated",receipt:ee,checkpointHeadSha:y,worktreeRealigned:ne})}const N=Object.values(b.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));N.length===0&&i("story-worktree-integration-lease-missing"),N.length>1&&i("story-worktree-integration-lease-ambiguous");const C=N[0];C.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const E=await new Re({projectRoot:r}).probe(C.leaseId);(!E.ok||E.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),E.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const re=await p(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");E.value.headSha!==re&&i("story-worktree-integration-worktree-dirty");const B=await p(r,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed"),X=q(B,pe)===re&&q(B,"Neocortex-Story")===d;let _,M,k,J=!1;if(X){_=await p(r,["rev-parse",`${h}^`],"story-worktree-integration-git-failed"),M=h;const y=q(B,"Neocortex-Bundle-Digest")??"",x=q(B,"Neocortex-Claim-Revision")??"";k=Ze({storyId:d,epicId:l,executionBranch:u,baseSha:_,bundleDigest:y,graphRevision:f.graphRevision,claimRevision:x}),fe(I,_)}else{fe(I,h);const y=await dt(r,f,d,h,re);if(y.kind==="conflict")return await qe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,epicHead:h,tip:re,conflictPaths:y.conflictPaths,integratedAt:S,chain:H});const x=y.changedPaths;M=y.commitSha,k=y.idempotencyKey,_=h,J=!0,(!await O(r,["diff","--cached","--quiet"])||!await O(r,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Q=await U(r,{required:!0}),$=Q.epics[l]?.branch_lease,oe=$&&$.ownerStoryId===d&&$.sessionId===k&&$.idempotencyKey===k&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!oe&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:S,expiresAt:new Date(Date.parse(S)+Qe).toISOString()};t=await Be(r,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await we(r,y=>{const x=xe(y,l),ee=x.branch_lease;ee&&Date.parse(String(ee.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(D)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:Q.revision,preCommit:async y=>{await rt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=V(y,l);ue(x),fe(x,_),await p(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==h&&i("story-worktree-integration-epic-head-raced")}}),s=K),J&&((await p(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==h||await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),await O(r,["merge","--ff-only","--no-edit",M])||i("story-worktree-integration-ff-refused"),await p(r,["rev-parse",m],"story-worktree-integration-git-failed")!==M&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let Z;const ie=await It({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const y=(await U(r,{required:!0})).stories[d]?.checkpoint;(!y||y.headSha!==M||y.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),Z=await Oe({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:_,after:M,checkpointDigest:ze(y),outcome:"integrated",integratedAt:S})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==M||L.baseSha!==_||!Z)&&i("story-worktree-integration-checkpoint-mismatch");const le=await $e(r,C.leaseId,M);return me({storyId:d,epicId:l,outcome:"integrated",receipt:Z,checkpointHeadSha:M,worktreeRealigned:le})}catch(g){if(g instanceof _e)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const g=s;await we(r,n=>{const f=xe(n,a),l=f.branch_lease;l&&l.sessionId===g.sessionId&&l.idempotencyKey===g.idempotencyKey&&l.acquiredAt===g.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const We=".neocortex/state.json",Te=".neocortex",Ce="state.json",W="story-worktree-integration-state-merge-git-failed";function De(e){const t=[];for(const s of e.split("\0")){if(!s)continue;const a=s.indexOf(" "),[r,g,n]=s.slice(0,a).split(" ");(a<0||!r||!g||!n)&&i(W),t.push({mode:r,type:g,oid:n,name:s.slice(a+1)})}return t}function zt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function ct(e,t,s,a){const r=await P(e,["ls-tree","-z",t]);r.code!==0&&i(W);const g=De(r.stdout).filter(l=>l.name!==s),n=await nt(e,["mktree","-z"],zt([...g,a])),f=n.stdout.trim();return(n.code!==0||!ce.test(f))&&i(W),f}async function Me(e,t){const s=await P(e,["ls-tree","-z",t,"--",We]);s.code!==0&&i(W);const a=De(s.stdout).find(r=>r.name===We);return a?((a.type!=="blob"||a.mode!=="100644"&&a.mode!=="100755")&&i("state-merge-input-invalid"),ce.test(a.oid)||i(W),a.oid):null}async function Le(e,t){t===null&&i("state-merge-input-invalid");const s=await P(e,["cat-file","-s",t]),a=Number.parseInt(s.stdout.trim(),10);(s.code!==0||!Number.isSafeInteger(a)||a<0||a>Tt)&&i(W);const r=await P(e,["cat-file","blob",t]);return r.code!==0&&i(W),r.stdout}async function Wt(e){try{const{projectRoot:t,mergeBase:s,epicHead:a,tip:r,tree:g,storyId:n,epicId:f}=e,l={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},u=await Me(t,s),d=await Me(t,r);if(u===d)return l;const S=await Le(t,u),m=await Le(t,await Me(t,a)),h=await Le(t,d),D=await p(t,["show","--no-patch","--format=%cI",r],W),b=Ot({base:S,epic:m,story:h,storyId:n,epicId:f,aggregateTimestamp:D});if(!b.ok)return{ok:!1,reasonCode:b.reasonCode};const I=e.conflictPaths.filter(E=>E!==We),H=await P(t,["ls-tree","-z",g,"--",Te]);H.code!==0&&i(W);const A=De(H.stdout).find(E=>E.name===Te);if(!A||A.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const G=await P(t,["ls-tree","-z",A.oid,"--",Ce]);G.code!==0&&i(W);const R=De(G.stdout).find(E=>E.name===Ce);if(R&&(R.type!=="blob"||R.mode!=="100644"&&R.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const j=await nt(t,["hash-object","-w","--stdin"],b.bytes),N=j.stdout.trim();if((j.code!==0||!ce.test(N))&&i(W),R?.oid===N)return{ok:!0,tree:g,conflictPaths:I,merged:!0};const C=await ct(t,A.oid,Ce,{mode:R?.mode??"100644",type:"blob",oid:N,name:Ce});return{ok:!0,tree:await ct(t,g,Te,{mode:A.mode,type:"tree",oid:C,name:Te}),conflictPaths:I,merged:!0}}catch(t){return t instanceof _e?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function dt(e,t,s,a,r){const{epicId:g,executionBranch:n}=t;await O(e,["merge-base","--is-ancestor",r,a])&&i("story-worktree-integration-range-empty");const f=await p(e,["merge-base",a,r],"story-worktree-integration-unrelated-history"),l=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,a,r]);l.code!==0&&l.code!==1&&i("story-worktree-integration-git-unsupported");const u=l.stdout.split("\0"),d=u[0]?.trim()??"";ce.test(d)||i("story-worktree-integration-git-unsupported");const S=l.code===1?[...new Set(u.slice(1).filter(at))].sort():[];l.code===1&&S.length===0&&i("story-worktree-integration-git-failed");const m=await Wt({projectRoot:e,mergeBase:f,epicHead:a,tip:r,tree:d,storyId:s,epicId:g,conflictPaths:S});m.ok||i(m.reasonCode);const h=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Pt)};const D=(await p(e,["diff","--name-only","-z",a,h],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),b=At(D,t.authorizedWriteSet,s,t.rootMemoryEffect);b.ok||i(b.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":"story-worktree-integration-write-set-invalid");const I=_t(e,s,h);I?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const H=await P(e,["diff","--binary","--full-index",a,h]);H.code!==0&&i("story-worktree-integration-git-failed");const A=H.stdout;A||i("story-worktree-integration-range-empty");const G=de(A),R=de([...t.authorizedWriteSet].sort().join("\0")),j=Ze({storyId:s,epicId:g,executionBranch:n,baseSha:a,bundleDigest:G,graphRevision:t.graphRevision,claimRevision:R}),N=(await p(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${s}): integrate story worktree`,C=[`Neocortex-Story: ${s}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${a}`,`Neocortex-Bundle-Digest: ${G}`,`Neocortex-Review-Artifact-Digest: ${I.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${R}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Ct(t.rootMemoryEffect)}`]:[],`${pe}: ${r}`],T=(await p(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",r],"story-worktree-integration-git-failed")).split("\0");T.length!==6&&i("story-worktree-integration-git-failed");const E=await p(e,["commit-tree",h,"-p",a,"-m",N,"-m",`Story: ${s}`,"-m",C.join(`
3
+ `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:T[0],GIT_AUTHOR_EMAIL:T[1],GIT_AUTHOR_DATE:T[2],GIT_COMMITTER_NAME:T[3],GIT_COMMITTER_EMAIL:T[4],GIT_COMMITTER_DATE:T[5]});return ce.test(E)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:E,changedPaths:D,idempotencyKey:j}}async function ft(e,t){const s=JSON.parse(await pt(ut(e,".neocortex","state.json"),"utf8")),r=Rt(s,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function lt(e,t,s,a){const r=await Be(e,{kind:"direct",storyId:t,sessionId:s,idempotencyKey:s,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});r.ok||i(r.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await a()}finally{await je(r.path,r.owner).catch(()=>{})}}async function $e(e,t,s){const a=await new Re({projectRoot:e}).probe(t);return!a.ok||a.value.ownership!=="proven"||a.value.clean!==!0?!1:O(a.value.entry.worktreePath,["reset","--keep",s])}async function qe(e){const t=de(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),s=e.chain[0];if(s?.outcome==="conflict-reopened"&&s.epicHeadAfterSha===e.epicHead&&s.checkpointDigest===t)return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:s,conflictPaths:Object.freeze([...e.conflictPaths])});const a=()=>Oe({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await a():await lt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,a);return me({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Mt=64,Lt="@ornexus/neocortex",Ge=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ge)if(!at(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function $t(e){return O(e,["clean","-X","-f","-q","--",...Ge])}async function qt(e,t){const s=await P(e,["show",`${t}:package.json`]);if(s.code!==0)return[];try{return JSON.parse(s.stdout)?.name===Lt?Ge:[]}catch{return[]}}function Gt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function tr(e){let t,s,a="",r=0,g;const n=Ae(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Mt||new Set(f).size!==f.length||f.some(o=>typeof o!="string"||!Ee.test(o)))&&i("story-worktree-wave-stories-invalid");const l=await be(await p(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await be(await p(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const o of f)try{d.set(o,await et(n,o))}catch(c){i(c instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(c.message)?c.message:"story-worktree-integration-authority-invalid")}const S=d.get(f[0]),{epicId:m,executionBranch:h}=S;for(const o of d.values())(o.epicId!==m||o.executionBranch!==h||o.graphRevision!==S.graphRevision||JSON.stringify(o.originBinding)!==JSON.stringify(S.originBinding))&&i("story-worktree-wave-epic-mixed");a=m;const D=new Date(e.nowIso??Date.now()).toISOString(),b=`refs/heads/${h}`,I=await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing");(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==I||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==h)&&i("story-worktree-integration-root-head-mismatch");const H=S.originBinding;(!H||!await O(n,["merge-base","--is-ancestor",H.originHeadSha,I]))&&i("story-worktree-integration-origin-binding-invalid");const A=o=>{const c=d.get(o).story;return Array.isArray(c.depends_on)?c.depends_on.filter(w=>typeof w=="string"):[]},G=new Map(f.map((o,c)=>[o,c]));f.forEach((o,c)=>{for(const w of A(o)){const v=G.get(w);v!==void 0&&v>=c&&i("story-worktree-wave-order-invalid")}});const R=await U(n,{required:!0}),j=V(R,m);ue(j);const N=o=>j.filter(c=>c.storyId===o).sort((c,w)=>w.integrationIndex-c.integrationIndex)[0],C=f.filter(o=>N(o)?.outcome!=="integrated"),T=new Map(f.filter(o=>!C.includes(o)).map(o=>{const c=N(o),w=R.stories[o]?.checkpoint;return[o,Object.freeze({storyId:o,outcome:"already-integrated",receiptDigest:Ne(c),...w?.headSha?{checkpointHeadSha:w.headSha}:{}})]})),E=o=>({ok:!0,value:Object.freeze({epicId:m,...o,gateRuns:r,stories:Object.freeze(f.map(c=>T.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return E({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0});const re=new Set(C),B=[];let X=I;for(let o=0;o<C.length;o++){const c=await p(n,["show","--no-patch","--format=%B",X],"story-worktree-integration-git-failed"),w=q(c,"Neocortex-Story");if(!w||!re.has(w)||!q(c,pe))break;B.unshift(X),X=await p(n,["rev-parse",`${X}^`],"story-worktree-integration-git-failed")}const _=X;fe(j,_);const M=await ft(n,R),k=[];let J,Q=_;for(const[o,c]of C.entries()){const w=d.get(c);st(R,M,m,c,A(c),new Set(C.slice(0,o)));const v=Object.values(R.storyWorktrees?.entries??{}).filter(F=>F.storyId===c&&F.epicId===m&&F.state==="active"),z=R.stories[c]?.checkpoint;if(z&&typeof z.headSha=="string"){const F=z.headSha,Ve=await p(n,["show","--no-patch","--format=%B",F],"story-worktree-integration-git-failed");(q(Ve,"Neocortex-Story")!==c||!q(Ve,pe))&&i("story-worktree-integration-checkpoint-not-worktree"),(z.baseSha!==Q||B[o]!==F)&&i("story-worktree-integration-checkpoint-mismatch");const ht=(await p(n,["diff-tree","--no-commit-id","--name-only","-r","-z",F],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:c,sha:F,changedPaths:ht,...v.length===1?{leaseId:v[0].leaseId}:{}}),Q=F;continue}v.length===0&&i("story-worktree-integration-lease-missing"),v.length>1&&i("story-worktree-integration-lease-ambiguous");const ve=v[0];ve.executionBranch!==h&&i("story-worktree-integration-lease-invalid");const Se=await new Re({projectRoot:n}).probe(ve.leaseId);(!Se.ok||Se.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Se.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const He=await p(n,["rev-parse",`refs/heads/${ve.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Se.value.headSha!==He&&i("story-worktree-integration-worktree-dirty");const se=await dt(n,w,c,Q,He);if(se.kind==="conflict"){o<B.length&&i("story-worktree-wave-resume-mismatch"),J={storyId:c,tip:He,conflictPaths:se.conflictPaths};break}o<B.length&&B[o]!==se.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:c,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:ve.leaseId}),Q=se.commitSha}if(k.length<B.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const o=J,c=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:I,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:j.filter(w=>w.storyId===o.storyId).sort((w,v)=>v.integrationIndex-w.integrationIndex)});return c.ok?(T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])})),E({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const $=k[k.length-1].sha,oe=[...new Set(k.flatMap(o=>o.changedPaths))].sort();(!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-root-dirty");const K=Gt(k.length),Y=de(["p205-wave-lease-v1",m,h,_,...k.map(o=>o.sha)].join("\0")),Z=k[0].storyId,ie=await U(n,{required:!0}),L=ie.epics[m]?.branch_lease,le=L&&L.ownerStoryId===Z&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!le&&Date.parse(String(L.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const y=le??{schemaVersion:1,ownerStoryId:Z,sessionId:Y,idempotencyKey:Y,acquiredAt:D,expiresAt:new Date(Date.parse(D)+Qe*K).toISOString()};t=await Be(n,{kind:"direct",storyId:Z,sessionId:Y,idempotencyKey:Y,expiresAt:String(y.expiresAt),persistent:!0,createdAt:String(y.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;le||await we(n,o=>{const c=xe(o,m),w=c.branch_lease;w&&Date.parse(String(w.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==S.graphRevision&&i("story-worktree-integration-graph-revision-raced"),c.branch_lease=y},{expectedRevision:ie.revision,preCommit:async o=>{await rt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const c=V(o,m);ue(c),fe(c,_),await p(n,["rev-parse",b],"story-worktree-integration-epic-branch-missing")!==I&&i("story-worktree-integration-epic-head-raced")}}),s=y;const ee=new Set(k.map(o=>o.sha));let ne=!0;if(e.push&&B.length>0){const o=(await P(n,["ls-remote","--heads",e.remote??"origin",b])).stdout.split(/\s+/)[0]??"";ce.test(o)&&await O(n,["merge-base","--is-ancestor",B[0],o])&&(ne=!1)}let ae=I;const ke=async o=>{if((await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==ae||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await p(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==h)&&i("story-worktree-integration-epic-head-raced"),ae===o)return;const c=await O(n,["merge-base","--is-ancestor",ae,o]);!c&&(!ne||!ee.has(ae))&&i("story-worktree-wave-pushed-immovable"),(!(c?await O(n,["merge","--ff-only","--no-edit",o]):await O(n,["reset","--keep",o]))||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==o||await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==o)&&i("story-worktree-integration-ff-refused"),ae=o};g=ne?{epicRef:b,base:_,owned:ee}:void 0,await ke($),await e.afterWaveFastForward?.();const gt=[...new Set([S.graphRevision,...k.map(o=>R.stories[o.storyId]?.checkpoint?.graphRevision).filter(o=>typeof o=="string")])],yt=await qt(n,_),Pe=async()=>{yt.length!==0&&(await(e.cleanBuildOutputs??$t)(n)||i("story-worktree-wave-clean-failed"))},Ke=async o=>{const c=k[o];await ke(c.sha),r>=K&&i("story-worktree-wave-gate-cap-exceeded"),r>0&&await Pe(),r++;const w=await bt({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:gt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await p(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await p(n,["rev-parse",b],"story-worktree-integration-git-failed")!==c.sha||!await O(n,["diff","--cached","--quiet"])||!await O(n,["diff","--quiet","HEAD","--",...oe]))&&i("story-worktree-integration-epic-head-raced"),!w.ok&&w.kind==="infrastructure"&&i(w.reasonCode),w},Ie=await Ke(k.length-1);let Ye=k.length-1,Fe=Ie.ok?Ie.authorities:void 0,ge,ye;if(!Ie.ok){ne||i("story-worktree-wave-gate-failed-pushed");let o=-1,c=k.length-1;for(ye=Ie.reasonCode;c-o>1;){const v=Math.floor((o+c)/2),z=await Ke(v);z.ok?(o=v,Fe=z.authorities):(c=v,ye=z.reasonCode)}ge=c,Ye=o;const w=k[c].storyId;if(T.set(w,Object.freeze({storyId:w,outcome:"gate-failed",reasonCode:ye})),o<0)return await ke(_),await Pe(),g=void 0,E({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:w,failureReasonCode:ye,epicHeadBeforeSha:I,epicHeadAfterSha:_,gateRunCap:K});await ke(k[o].sha),await Pe()}const te=k.slice(0,Ye+1),he=te[te.length-1].sha,Je=kt({epicId:m,executionBranch:h,waveHeadSha:he,waveStoryIds:te.map(o=>o.storyId),waveCommitShas:te.map(o=>o.sha)});e.push&&(g=void 0,await St(n,e.remote??"origin",h,he)||i("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ue=[];for(const[o,c]of te.entries()){const w=o===0?_:te[o-1].sha,v=await vt({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Je,authorities:Fe,expectedLease:y,physicalLock:x,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||i(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==w)&&i("story-worktree-integration-checkpoint-mismatch");const z=await Oe({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:h,before:w,after:c.sha,checkpointDigest:ze(v.value),outcome:"integrated",integratedAt:D,expectedEpicHead:he});Ue.push(c.storyId),T.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:Ne(z)})),await e.afterWaveStoryPersist?.(c.storyId)}if(J&&ge===void 0){const o=J,c=await U(n,{required:!0}),w=await qe({projectRoot:n,epicId:m,storyId:o.storyId,executionBranch:h,epicHead:he,tip:o.tip,conflictPaths:o.conflictPaths,integratedAt:D,chain:V(c,m).filter(v=>v.storyId===o.storyId).sort((v,z)=>z.integrationIndex-v.integrationIndex),lockHeld:!0});w.ok||i(w.reasonCode),T.set(o.storyId,Object.freeze({storyId:o.storyId,outcome:"conflict-reopened",receiptDigest:w.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...o.conflictPaths])}))}for(const o of te){if(!o.leaseId)continue;const c=await $e(n,o.leaseId,o.sha);T.set(o.storyId,Object.freeze({...T.get(o.storyId),worktreeRealigned:c}))}return E({outcome:ge!==void 0?"gate-failed":J?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ue),...ge!==void 0?{failedStoryId:k[ge].storyId,failureReasonCode:ye}:{},epicHeadBeforeSha:I,epicHeadAfterSha:he,qaCoverage:Je,gateRunCap:K})}catch(f){let l=f instanceof _e?f.reasonCode:f instanceof Error&&/^(?:git-lifecycle|direct-yolo|p205)-[a-z0-9-]{1,80}$/.test(f.message)?f.message:"story-worktree-integration-failed";if(g){const u=g,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),S=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==S||!u.owned.has(d)||!await O(n,["reset","--keep",u.base]))&&(l="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:l,gateRuns:r}}finally{if(t?.ok&&await je(t.path,t.owner).catch(()=>{}),s&&a){const f=s;await we(n,l=>{const u=xe(l,a),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function rr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(l=>typeof l!="string"||!Ee.test(l)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const s=e.integrate??Nt,a=new Set(e.readyStoryIds),r=Ae(e.projectRoot);let g;try{const l=await U(r,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));g=new Set([...u].flatMap(d=>V(l,d)).filter(d=>d.outcome==="integrated").map(d=>d.storyId))}catch{return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-evidence-invalid"}}const n=[],f=[];for(const l of t){if(g.has(l))continue;if(!a.has(l))return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:S,...m}=e,h=await s({...m,projectRoot:r,storyId:l});if(n.push({storyId:l,result:h}),!h.ok)return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:h.reasonCode};if(h.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"integration-conflict-reopened"};f.push(l),g.add(l)}return{results:n,integratedStoryIds:f}}async function or(e){const t=Ae(e.projectRoot),s=e.manager??new Re({projectRoot:t});let a;try{a=await U(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const r=[];for(const g of e.directives){const n=g&&typeof g=="object"&&!Array.isArray(g)?g:void 0,f=typeof n?.storyId=="string"&&Ee.test(n.storyId)?n.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const l=Object.values(a.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(l.length!==1){r.push({storyId:f,ok:!1,reasonCode:l.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await s.sync({leaseId:l[0].leaseId,directive:g});r.push(u.ok?{storyId:f,ok:!0,outcome:u.value.outcome,integratedSha:u.value.integratedSha}:{storyId:f,ok:!1,reasonCode:u.reasonCode,...u.conflictPaths?{conflictPaths:u.conflictPaths}:{}})}return r}export{Pt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Dt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,We as STORY_WORKTREE_STATE_JSON_PATH,Ge as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Lt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Mt as STORY_WORKTREE_WAVE_MAX_STORIES,Ne as digestStoryWorktreeIntegrationReceipt,Nt as integrateStoryWorktree,tr as integrateStoryWorktreeWave,rr as integrateStoryWorktreesInOrder,Wt as resolveStoryWorktreeStateJsonMerge,qt as storyWorktreeWaveBuildOutputPaths,Gt as storyWorktreeWaveGateRunCap,or as syncReleasedDependents};
@@ -53,6 +53,19 @@ export interface StoryWorktreeAdoptInput extends StoryWorktreeCreateInput {
53
53
  /** Absolute path of an existing secondary worktree (native harness). */
54
54
  readonly worktreePath: string;
55
55
  }
56
+ /**
57
+ * P227.08 DEC-05 (P227.10 D-001): worktree-local `@neocortex/shared` outcome of
58
+ * a fresh create/adopt. `not-applicable` when the repository has no
59
+ * `@neocortex/shared` workspace; `build-missing` when the link points into the
60
+ * worktree but its build is absent (P227.10-ADR-3: never the main checkout).
61
+ */
62
+ export type StoryWorktreeSharedPreparation = 'not-applicable' | 'unchanged' | 'already-linked' | 'linked' | 'build-missing';
63
+ /** P227.08-ADR-3: receipt of a fresh adopt that fast-forwarded HEAD to the base. */
64
+ export interface StoryWorktreeAdoptAlignment {
65
+ readonly mode: 'fast-forward';
66
+ readonly fromSha: string;
67
+ readonly toSha: string;
68
+ }
56
69
  export interface StoryWorktreeLeaseValue {
57
70
  readonly lease: StoryWorktreeLease;
58
71
  readonly leaseDigest: string;
@@ -62,6 +75,10 @@ export interface StoryWorktreeLeaseValue {
62
75
  readonly baseSha: string;
63
76
  readonly reused: boolean;
64
77
  readonly env: Readonly<Record<string, string>>;
78
+ /** Present only when a fresh adoption moved HEAD; outside the lease digest. */
79
+ readonly alignment?: StoryWorktreeAdoptAlignment;
80
+ /** Present only on a fresh create/adopt; outside the lease digest (DEC-05). */
81
+ readonly sharedResolution?: StoryWorktreeSharedPreparation;
65
82
  }
66
83
  export interface StoryWorktreeSyncValue {
67
84
  readonly leaseId: string;
@@ -100,6 +117,12 @@ export interface StoryWorktreeProbe {
100
117
  readonly facts: RepositoryFacts;
101
118
  readonly ownership: 'proven' | 'unproven';
102
119
  readonly pathExists: boolean;
120
+ /**
121
+ * P227.07: typed absence proof of the registered directory. Only `enoent`
122
+ * (a definite `ENOENT` from `lstat`) may admit orphan recovery; any other
123
+ * `lstat` error (`EACCES`, `ENOTDIR`, I/O) is `unknown` and fails closed.
124
+ */
125
+ readonly pathAbsence: StoryWorktreePathAbsence;
103
126
  readonly registered: boolean;
104
127
  /** Tip of `refs/heads/<temporaryBranch>` when the branch exists. */
105
128
  readonly branchSha?: string;
@@ -111,10 +134,13 @@ export interface StoryWorktreeProbe {
111
134
  /** Worktree HEAD (or branch tip when the directory vanished) contained in `epic/<ID>`. */
112
135
  readonly integrated?: boolean;
113
136
  }
137
+ export type StoryWorktreePathAbsence = 'enoent' | 'present' | 'unknown';
114
138
  export type StoryWorktreeFailureTrigger = 'failure' | 'abandon';
115
139
  export interface GitOutcome {
116
140
  readonly ok: boolean;
117
141
  readonly stdout: string;
142
+ /** P227.07: process exit code (0 on success; -1 when Git did not exit normally). */
143
+ readonly exitCode: number;
118
144
  }
119
145
  export interface RepositoryFacts {
120
146
  readonly mainRoot: string;
@@ -122,6 +148,8 @@ export interface RepositoryFacts {
122
148
  }
123
149
  /** Bounded Git execution shared with the P225.06 cleanup module (exit code + stdout only). */
124
150
  export declare function runStoryWorktreeGit(cwd: string, args: readonly string[]): Promise<GitOutcome>;
151
+ /** P227.07: `lstat`-based absence classification (never follows symlinks). */
152
+ export declare function storyWorktreePathAbsence(path: string): Promise<StoryWorktreePathAbsence>;
125
153
  export interface PorcelainWorktree {
126
154
  readonly path: string;
127
155
  readonly head?: string;
@@ -137,6 +165,25 @@ export declare class StoryWorktreeManager {
137
165
  constructor(options: StoryWorktreeManagerOptions);
138
166
  create(input: StoryWorktreeCreateInput): Promise<StoryWorktreeResult<StoryWorktreeLeaseValue>>;
139
167
  adopt(input: StoryWorktreeAdoptInput): Promise<StoryWorktreeResult<StoryWorktreeLeaseValue>>;
168
+ /**
169
+ * C11 F1/F5 (+ re-review L2): fast-forward a clean worktree without `merge`.
170
+ * Protection of ignored files comes from the explicit pre-check below: it
171
+ * refuses when an ignored path equals, contains or lies inside a path the
172
+ * base changes. `read-tree -m -u` (no hooks) then refuses untracked
173
+ * overwrites, but current Git treats ignored files as expendable, so it is
174
+ * not the ignored-file guard. The branch moves last by a CAS update-ref.
175
+ * Residual time-of-check/time-of-use window: see DEC-10 in the story tasks.
176
+ */
177
+ private alignWorktree;
178
+ /**
179
+ * Rollback of `alignWorktree` (re-review L1): the tree goes back first, then
180
+ * the branch by CAS (never moving a branch someone else moved). Both results
181
+ * are checked; any failure is the distinct `native-worktree-align-restore-failed`
182
+ * refusal, which supersedes the original error so a tree/branch mismatch is
183
+ * always reported.
184
+ */
185
+ private restoreAlignment;
186
+ private adoptAligned;
140
187
  sync(input: {
141
188
  readonly leaseId: string;
142
189
  readonly integratedSha?: string;
@@ -188,6 +235,16 @@ export declare class StoryWorktreeManager {
188
235
  private clean;
189
236
  private project;
190
237
  private leaseValue;
238
+ /**
239
+ * DEC-05 (P227.10 D-001): make `@neocortex/shared` resolve to the worktree's
240
+ * own package. Applies only when the authorized base tree carries an
241
+ * `@neocortex/shared` workspace (C11 F2: decided by the base, after
242
+ * alignment). The link path must be Git-ignored in the worktree, otherwise
243
+ * it would dirty the tree (`story-worktree-shared-link-not-ignored`). Every
244
+ * helper failure becomes a typed refusal except a missing build, which keeps
245
+ * the worktree-local link (never a main-checkout fallback).
246
+ */
247
+ private prepareSharedResolution;
191
248
  private rollbackCreate;
192
249
  private removeOwnMarker;
193
250
  /** `git worktree list` with every path canonicalised for comparison. */
@@ -1,3 +1,3 @@
1
- import{execFile as U}from"node:child_process";import{createHash as K,randomBytes as Y}from"node:crypto";import{chmod as Z,lstat as X,readFile as x,realpath as R,unlink as C,writeFile as B}from"node:fs/promises";import{homedir as Q}from"node:os";import{isAbsolute as W,join as E,resolve as ee}from"node:path";import{yoloopDomainHash as te}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,compactStoryWorktreeJournal as ae,ensureStoryWorktreeJournal as b,isStoryWorktreeCleanupReceiptRecord as oe,mutateGitLifecycleRuntime as se,readGitLifecycleRuntime as ie}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as ne,ensurePrivateStoryWorktreeRoot as ce,resolveStoryWorktreePath as H,resolveStoryWorktreeRoot as de,storyWorktreeIdentity as he}from"./story-worktree-paths.js";const O="nx-owner",le="neocortex.p225.story-worktree-receipt.v1";function $(n){return te(le,n)}const j=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),we=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,M=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,fe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function ue(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==j.length||!r.every(a=>j.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&z.test(e.directiveId)&&typeof e.epicId=="string"&&V.test(e.epicId)&&typeof e.storyId=="string"&&M.test(e.storyId)&&typeof e.releasedStepId=="string"&&we.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&M.test(a))&&typeof e.integratedEpicHeadSha=="string"&&P.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&L.test(e.graphRevision)&&typeof e.issuedAt=="string"&&fe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const N=1440*60*1e3,pe=3e4,me=200,P=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,L=/^[a-f0-9]{64}$/,T=/^swt-[a-f0-9]{24}$/,z=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,V=/^P[1-9][0-9]*$/,ke=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/;class G extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new G(n)}function ye(){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 Ae(n,e){return w(n,e)}function w(n,e){return new Promise(r=>{U("git",[...e],{cwd:n,encoding:"utf8",env:ye(),maxBuffer:8*1024*1024,timeout:pe,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??"")}))})}async function m(n,e){return(await w(n,e)).ok}async function S(n,e,r){const t=await w(n,e);return t.ok||o(r),t.stdout.trim()}function D(n){return K("sha256").update(n).digest("hex")}async function A(n){try{return await X(n),!0}catch{return!1}}function q(n){return new Promise(e=>setTimeout(e,n))}function F(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 ge(n){return n.length>0&&n.length<=512&&!W(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class _e{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ee(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>Y(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);const a=de({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??Q(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=H({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await ce(a.value,this.platform);c.ok||o(c.reasonCode);const i=H({root:await R(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const l=i.value,d=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(d){if(d.state==="active"&&d.baseSha===e.baseSha&&d.graphRevision===e.graphRevision&&await this.ownershipProven(d,t))return await this.assertNoCleanupInProgress(t,d.leaseId),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};await this.reclaimStaleReservation(d,t)||o("story-worktree-entry-conflict")}await A(l)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const h=this.randomNonce(),y=this.now(),f={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:D(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:l,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,h),nonceDigest:D(h),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:y.toISOString(),expiresAt:new Date(y.getTime()+(this.options.ttlMs??N)).toISOString()};await this.mutate(p=>{const k=b(p);(k.entries[f.leaseId]||Object.values(k.entries).some(v=>v.worktreePath===l))&&o("story-worktree-entry-conflict"),k.entries[f.leaseId]=f});let I=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,l,e.baseSha])||o("story-worktree-add-failed"),I=!0,this.platform!=="win32"?await Z(l,448):await this.enableWindowsLongPaths(t,l);const p=await this.worktreeGitDir(l,t);await B(E(p,O),`${JSON.stringify({schemaVersion:1,leaseId:f.leaseId,nonce:h})}
2
- `,{flag:"wx",mode:384});const k={...f,state:"active"};return await this.mutate(v=>{const u=b(v),g=u.entries[f.leaseId];(!g||g.state!=="creating"||g.nonceDigest!==f.nonceDigest)&&o("story-worktree-entry-conflict"),u.entries[f.leaseId]=k}),{ok:!0,value:this.leaseValue(k,!1),privatePath:l}}catch(p){throw await this.rollbackCreate(t,f,I),p}})}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),(typeof e.worktreePath!="string"||!W(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await R(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(g=>this.samePath(g.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"),(ke.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 d=(await this.readDocument()).storyWorktrees?.entries??{},h=d[r.leaseId];if(h){if(this.samePath(h.worktreePath,a)&&h.state==="active"&&await this.ownershipProven(h,t))return await m(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,h.leaseId),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};o("story-worktree-entry-conflict")}Object.values(d).some(g=>this.samePath(g.worktreePath,a))&&o("story-worktree-entry-conflict"),await S(a,["rev-parse","HEAD"],"story-worktree-git-failed")!==e.baseSha&&o("native-worktree-base-mismatch"),(await w(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed"),await this.clean(a)||o("native-worktree-dirty");const I=await this.worktreeGitDir(a,t),p=E(I,O);await A(p)&&(await this.markerLeaseId(p)!==r.leaseId&&o("story-worktree-marker-exists"),await C(p));const k=this.randomNonce(),v=this.now(),u={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:D(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:i.branch,worktreeRef:r.worktreeRef,worktreePath:a,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(e.ownerId,k),nonceDigest:D(k),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"active",acquiredAt:v.toISOString(),expiresAt:new Date(v.getTime()+(this.options.ttlMs??N)).toISOString()};await B(p,`${JSON.stringify({schemaVersion:1,leaseId:u.leaseId,nonce:k})}
3
- `,{flag:"wx",mode:384});try{await this.mutate(g=>{const _=b(g);(_.entries[u.leaseId]||Object.values(_.entries).some(J=>this.samePath(J.worktreePath,a)))&&o("story-worktree-entry-conflict"),_.entries[u.leaseId]=u})}catch(g){throw await this.removeOwnMarker(p,k),g}return{ok:!0,value:this.leaseValue(u,!1),privatePath:a}})}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 l=e.directive;(!ue(e.directive)||l.epicId!==t.epicId||l.storyId!==t.storyId||a!==void 0&&a!==l.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(l.integratedEpicHeadSha)}(typeof a!="string"||!P.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 w(t.worktreePath,["merge","--no-edit",a])).ok){const h=(await w(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(ge).sort().slice(0,me);return h.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:h}}c="synced"}const i=await S(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(l=>{const d=b(l),h=d.entries[t.leaseId];(!h||h.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),d.entries[t.leaseId]={...h,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{e.leaseId===void 0==(e.epicId===void 0)&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!T.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!V.test(e.epicId)&&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: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 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 S(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 w(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,l=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${D(`${t.leaseId}|${t.nonceDigest}|${l}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:l};return oe(d)||o("story-worktree-receipt-invalid"),await this.mutate(h=>{const y=b(h),f=y.entries[t.leaseId];for(f&&f.nonceDigest===t.nonceDigest&&delete y.entries[t.leaseId],y.cleanupReceipts.push({...d});y.cleanupReceipts.length>re;)y.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:d,receiptDigest:$(d)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!T.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((u,g)=>g>0&&this.samePath(u.path,t.worktreePath)),c=a.some(u=>u.branch===t.temporaryBranch),i=await w(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),l=i.ok&&P.test(i.stdout.trim())?i.stdout.trim():void 0,d=await w(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),h=d.ok&&P.test(d.stdout.trim())?d.stdout.trim():void 0,y=await A(t.worktreePath),f=t.state==="active"&&y&&await this.ownershipProven(t,r);let I,p;if(f){const u=await w(t.worktreePath,["rev-parse","HEAD"]);u.ok&&P.test(u.stdout.trim())&&(I=u.stdout.trim()),p=await this.clean(t.worktreePath)}const k=I??(y?void 0:l),v=k&&h?await m(r.mainRoot,["merge-base","--is-ancestor",k,h]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:f?"proven":"unproven",pathExists:y,registered:s,...l?{branchSha:l}:{},branchCheckedOut:c,...I?{headSha:I}:{},...p!==void 0?{clean:p}:{},...h?{epicHead:h}:{},...v!==void 0?{integrated:v}:{}}}})}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 G)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=he(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!z.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-${D(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await R(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await S(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await R(r),s=F(await S(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await R(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!L.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!P.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 S(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await R(await S(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await R(await S(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=E(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 q(25*i)}o("story-worktree-config-failed")},a=await w(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 R(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await x(E(t,O),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||D(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"||!T.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 clean(e){const r=await w(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await w(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 w(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!P.test(s))return{...t,ownership:"proven"};const c=await w(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}}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:$(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[ne]:a}}}async rollbackCreate(e,r,t){t&&(await w(e.mainRoot,["worktree","remove",r.worktreePath]),await w(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await w(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=b(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ae(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await x(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=F(await S(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 R(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 x(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await A(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=b(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 ie(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 se(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 q(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{O as STORY_WORKTREE_MARKER_FILE,le as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,_e as StoryWorktreeManager,$ as digestStoryWorktreeReceiptLocal,F as parseWorktreeList,Ae as runStoryWorktreeGit};
1
+ import{execFile as K}from"node:child_process";import{createHash as Y,randomBytes as Z}from"node:crypto";import{chmod as X,lstat as x,readFile as _,realpath as S,unlink as O,writeFile as B}from"node:fs/promises";import{homedir as Q}from"node:os";import{isAbsolute as $,join as A,resolve as ee}from"node:path";import{yoloopDomainHash as te}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,compactStoryWorktreeJournal as ae,ensureStoryWorktreeJournal as P,isStoryWorktreeCleanupReceiptRecord as oe,mutateGitLifecycleRuntime as se,readGitLifecycleRuntime as ie}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as ne,ensurePrivateStoryWorktreeRoot as ce,ensureStoryWorktreeSharedResolution as de,resolveStoryWorktreePath as H,resolveStoryWorktreeRoot as he,storyWorktreeIdentity as le}from"./story-worktree-paths.js";const W="nx-owner",we="neocortex.p225.story-worktree-receipt.v1";function j(c){return te(we,c)}const M=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),fe=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,N=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,ue=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function pe(c){if(c===null||typeof c!="object"||Array.isArray(c))return!1;const e=c,r=Object.keys(e);if(r.length!==M.length||!r.every(a=>M.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&V.test(e.directiveId)&&typeof e.epicId=="string"&&G.test(e.epicId)&&typeof e.storyId=="string"&&N.test(e.storyId)&&typeof e.releasedStepId=="string"&&fe.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&N.test(a))&&typeof e.integratedEpicHeadSha=="string"&&E.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&z.test(e.graphRevision)&&typeof e.issuedAt=="string"&&ue.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const L=1440*60*1e3,me=3e4,ke=200,E=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,z=/^[a-f0-9]{64}$/,C=/^swt-[a-f0-9]{24}$/,V=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,G=/^P[1-9][0-9]*$/,ye=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/;class q extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function s(c){throw new q(c)}function ge(){const c={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete c[e];return c.GIT_TERMINAL_PROMPT="0",c}function _e(c,e){return f(c,e)}function f(c,e){return new Promise(r=>{K("git",[...e],{cwd:c,encoding:"utf8",env:ge(),maxBuffer:8*1024*1024,timeout:me,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function p(c,e){return(await f(c,e)).ok}async function b(c,e,r){const t=await f(c,e);return t.ok||s(r),t.stdout.trim()}function D(c){return Y("sha256").update(c).digest("hex")}async function Ie(c){try{return await x(c),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function T(c){try{return await x(c),!0}catch{return!1}}function F(c){return new Promise(e=>setTimeout(e,c))}function J(c){const e=[];for(const r of c.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const o=t.find(i=>i.startsWith("HEAD "))?.slice(5),n=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...o?{head:o}:{},...n?.startsWith("refs/heads/")?{branch:n.slice(11)}:{}})}return e}function ve(c){return c.length>0&&c.length<=512&&!$(c)&&!/^[A-Za-z]:/.test(c)&&!c.includes("\\")&&!c.split("/").some(e=>e===".."||e==="")}class Oe{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ee(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>Z(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);const a=he({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??Q(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||s(a.reasonCode);const o=H({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});o.ok||s(o.reasonCode);const n=await ce(a.value,this.platform);n.ok||s(n.reasonCode);const i=H({root:await S(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||s(i.reasonCode);const l=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)||s("story-worktree-entry-conflict")}await T(l)&&s("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&s("story-worktree-branch-exists");const d=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:D(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:l,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,d),nonceDigest:D(d),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??L)).toISOString()};await this.mutate(m=>{const k=P(m);(k.entries[w.leaseId]||Object.values(k.entries).some(y=>y.worktreePath===l))&&s("story-worktree-entry-conflict"),k.entries[w.leaseId]=w});let g=!1;try{await p(t.mainRoot,["worktree","add","-b",r.temporaryBranch,l,e.baseSha])||s("story-worktree-add-failed"),g=!0,this.platform!=="win32"?await X(l,448):await this.enableWindowsLongPaths(t,l);const m=await this.prepareSharedResolution(t,l,e.baseSha),k=await this.worktreeGitDir(l,t);await B(A(k,W),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:d})}
2
+ `,{flag:"wx",mode:384});const y={...w,state:"active"};return await this.mutate(R=>{const I=P(R),v=I.entries[w.leaseId];(!v||v.state!=="creating"||v.nonceDigest!==w.nonceDigest)&&s("story-worktree-entry-conflict"),I.entries[w.leaseId]=y}),{ok:!0,value:{...this.leaseValue(y,!1),sharedResolution:m},privatePath:l}}catch(m){throw await this.rollbackCreate(t,w,g),m}})}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),(typeof e.worktreePath!="string"||!$(e.worktreePath))&&s("story-worktree-adopt-path-invalid");let a;try{a=await S(e.worktreePath)}catch{s("story-worktree-adopt-unregistered")}const o=await this.listWorktrees(t),n=o.findIndex(v=>this.samePath(v.path,a));n===0&&s("story-worktree-adopt-main-refused"),n<0&&s("story-worktree-adopt-unregistered");const i=o[n];i.branch||s("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&s("story-worktree-adopt-branch-invalid"),(ye.test(i.branch)||i.branch===o[0]?.branch||await p(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&s("story-worktree-adopt-branch-protected");const h=(await this.readDocument()).storyWorktrees?.entries??{},d=h[r.leaseId];if(d){if(this.samePath(d.worktreePath,a)&&d.state==="active"&&await this.ownershipProven(d,t))return await p(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||s("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,d.leaseId),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};s("story-worktree-entry-conflict")}Object.values(h).some(v=>this.samePath(v.worktreePath,a))&&s("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||s("story-worktree-git-failed"),await this.clean(a)||s("native-worktree-dirty");const w=await b(a,["rev-parse","HEAD"],"story-worktree-git-failed");w!==e.baseSha&&!await p(a,["merge-base","--is-ancestor",w,e.baseSha])&&s("native-worktree-base-mismatch");const g=await this.worktreeGitDir(a,t),m=A(g,W),k=await T(m);k&&await this.markerLeaseId(m)!==r.leaseId&&s("story-worktree-marker-exists");let y;w!==e.baseSha&&(await this.alignWorktree(a,i.branch,w,e.baseSha),y=Object.freeze({mode:"fast-forward",fromSha:w,toSha:e.baseSha}));const R=A(a,"node_modules","@neocortex","shared"),I=await x(R).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:m,orphanMarker:k,alignment:y})}catch(v){throw!I&&await x(R).then(U=>U.isSymbolicLink(),()=>!1)&&await O(R).catch(()=>{}),y&&await this.restoreAlignment(a,i.branch,w,e.baseSha),v}})}async alignWorktree(e,r,t,a){const o=await f(e,["diff","--name-only","--no-renames","-z",t,a]),n=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!o.ok||!n.ok)&&s("native-worktree-align-failed");const i=n.stdout.split("\0").filter(Boolean).map(d=>d.replace(/\/$/,""));o.stdout.split("\0").filter(Boolean).some(d=>i.some(u=>d===u||d.startsWith(`${u}/`)||u.startsWith(`${d}/`)))&&s("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||s("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||s("native-worktree-align-restore-failed"),s("native-worktree-align-failed")),(await b(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),s("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||s("native-worktree-align-restore-failed"),await p(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||s("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:o,temporaryBranch:n,markerPath:i,orphanMarker:l,alignment:h}=e,d=await this.prepareSharedResolution(r,o,a.baseSha);l&&await O(i);const u=this.randomNonce(),w=this.now(),g={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:D(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:n,worktreeRef:t.worktreeRef,worktreePath:o,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:D(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??L)).toISOString()};await B(i,`${JSON.stringify({schemaVersion:1,leaseId:g.leaseId,nonce:u})}
3
+ `,{flag:"wx",mode:384});try{await this.mutate(k=>{const y=P(k);(y.entries[g.leaseId]||Object.values(y.entries).some(R=>this.samePath(R.worktreePath,o)))&&s("story-worktree-entry-conflict"),y.entries[g.leaseId]=g})}catch(k){throw await this.removeOwnMarker(i,u),k}const m={...this.leaseValue(g,!1),sharedResolution:d};return{ok:!0,value:h?{...m,alignment:h}:m,privatePath:o}}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 l=e.directive;(!pe(e.directive)||l.epicId!==t.epicId||l.storyId!==t.storyId||a!==void 0&&a!==l.integratedEpicHeadSha)&&s("story-worktree-directive-invalid"),a=String(l.integratedEpicHeadSha)}(typeof a!="string"||!E.test(a))&&s("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||s("story-worktree-dirty");const o=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,o])||s("story-worktree-sync-sha-unintegrated");let n="already-synced";if(!await p(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(ve).sort().slice(0,ke);return d.length===0&&s("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}n="synced"}const i=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(l=>{const h=P(l),d=h.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&s("story-worktree-entry-conflict"),h.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:n,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{e.leaseId===void 0==(e.epicId===void 0)&&s("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!C.test(e.leaseId)&&s("story-worktree-lease-invalid"),e.epicId!==void 0&&!G.test(e.epicId)&&s("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(o=>e.leaseId?o.leaseId===e.leaseId:o.epicId===e.epicId).sort((o,n)=>o.leaseId.localeCompare(n.leaseId));e.leaseId&&t.length===0&&s("story-worktree-lease-unknown");const a=[];for(const o of t)a.push(await this.project(o,r));return{ok:!0,value:{entries:a}}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||s("story-worktree-dirty");const a=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),o=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,o])||s("story-worktree-not-integrated"),await p(r.mainRoot,["worktree","remove",t.worktreePath])||s("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let n;t.workspaceMechanism==="native_subagent_worktree"?n="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(n="story-worktree-branch-moved");const i=n===void 0,l=this.now().toISOString(),h={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${D(`${t.leaseId}|${t.nonceDigest}|${l}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...n?{preservedReasonCode:n}:{},cleanedAt:l};return oe(h)||s("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=P(d),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...h});u.cleanupReceipts.length>re;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:h,receiptDigest:j(h)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!C.test(e))&&s("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||s("story-worktree-lease-unknown");const a=await this.listWorktrees(r),o=a.some((I,v)=>v>0&&this.samePath(I.path,t.worktreePath)),n=a.some(I=>I.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),l=i.ok&&E.test(i.stdout.trim())?i.stdout.trim():void 0,h=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=h.ok&&E.test(h.stdout.trim())?h.stdout.trim():void 0,u=await Ie(t.worktreePath),w=u==="present",g=t.state==="active"&&w&&await this.ownershipProven(t,r);let m,k;if(g){const I=await f(t.worktreePath,["rev-parse","HEAD"]);I.ok&&E.test(I.stdout.trim())&&(m=I.stdout.trim()),k=await this.clean(t.worktreePath)}const y=m??(w?void 0:l),R=y&&d?await p(r.mainRoot,["merge-base","--is-ancestor",y,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:g?"proven":"unproven",pathExists:w,pathAbsence:u,registered:o,...l?{branchSha:l}:{},branchCheckedOut:n,...m?{headSha:m}:{},...k!==void 0?{clean:k}:{},...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 q)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=le(e);return r.ok||s(r.reasonCode),e.ownerId!==void 0&&!V.test(e.ownerId)&&s("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())&&s("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${D(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await S(this.projectRoot)}catch{s("story-worktree-project-root-invalid")}const r=await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await S(r),o=J(await b(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return o||s("story-worktree-project-root-invalid"),{mainRoot:await S(o.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!z.test(a))&&s("story-worktree-graph-revision-invalid"),(typeof t!="string"||!E.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&s("story-worktree-base-invalid");const o=await this.epicHead(e,r);await p(e.mainRoot,["merge-base","--is-ancestor",t,o])||s("story-worktree-base-divergent")}async epicHead(e,r){return b(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await S(await b(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await S(await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),o=A(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${o}/`)&&!t.startsWith(`${o}\\`))&&s("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(o,n)=>{for(let i=1;i<=8;i++){if(await p(o,n))return;await F(25*i)}s("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 S(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await _(A(t,W),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||D(a.nonce)!==e.nonceDigest)return!1;const o=await this.listWorktrees(r),n=o.findIndex(i=>this.samePath(i.path,e.worktreePath));return n>0&&o[n].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!C.test(e))&&s("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||s("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&s("story-worktree-ownership-unproven"),t}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"]),o=a.stdout.trim();if(!a.ok||!E.test(o))return{...t,ownership:"proven"};const n=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=n.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",o,n.stdout.trim()]);return{...t,ownership:"proven",headSha:o,clean:await this.clean(e.worktreePath),integrated:i}}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:j(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[ne]: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"])||s("story-worktree-shared-link-not-ignored");const o=await de({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(o.ok)return o.value;if(o.reasonCode==="story-worktree-shared-build-missing")return"build-missing";s(o.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(o=>o.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(o=>{const n=P(o),i=n.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete n.entries[r.leaseId],ae(o)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await _(e,"utf8")).nonce===r&&await O(e)}catch{}}async listWorktrees(e){const r=J(await b(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 S(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 _(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await T(e.worktreePath)&&!await p(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(o=>{const n=P(o),i=n.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete n.entries[e.leaseId],a=!0)}),a}async readDocument(){return ie(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 se(this.projectRoot,e);return}catch(o){if(!(o instanceof Error&&(o.message==="git-lifecycle-runtime-lock-active"||o.code==="ENOENT"&&o.message.includes("runtime.lock")))||a>=r)throw o;await F(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{W as STORY_WORKTREE_MARKER_FILE,we as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,Oe as StoryWorktreeManager,j as digestStoryWorktreeReceiptLocal,J as parseWorktreeList,_e as runStoryWorktreeGit,Ie as storyWorktreePathAbsence};
@@ -15,7 +15,7 @@ export declare const STORY_WORKTREE_WIN32_MAX_PATH = 80;
15
15
  export declare const STORY_WORKTREE_ROOT_ENV = "NEOCORTEX_STORY_WORKTREE_ROOT";
16
16
  export declare const STORY_WORKTREE_ID_ENV = "NEOCORTEX_STORY_WORKTREE_ID";
17
17
  export type StoryWorktreePlatform = 'linux' | 'darwin' | 'win32';
18
- export type StoryWorktreePathReasonCode = 'story-worktree-identity-invalid' | 'story-worktree-platform-unsupported' | 'story-worktree-root-invalid' | 'story-worktree-path-too-long' | 'story-worktree-path-inside-repository' | 'story-worktree-root-unsafe';
18
+ export type StoryWorktreePathReasonCode = 'story-worktree-identity-invalid' | 'story-worktree-platform-unsupported' | 'story-worktree-root-invalid' | 'story-worktree-path-too-long' | 'story-worktree-path-inside-repository' | 'story-worktree-root-unsafe' | 'story-worktree-shared-source-missing' | 'story-worktree-shared-link-unsafe' | 'story-worktree-shared-link-failed' | 'story-worktree-shared-build-missing';
19
19
  export type StoryWorktreePathResult<T> = {
20
20
  readonly ok: true;
21
21
  readonly value: T;
@@ -63,3 +63,25 @@ export declare function resolveStoryWorktreePath(input: {
63
63
  * segments that already exist under the deepest existing ancestor.
64
64
  */
65
65
  export declare function ensurePrivateStoryWorktreeRoot(root: string, platform?: string): Promise<StoryWorktreePathResult<string>>;
66
+ /** P227.10 -- outcome of preparing the worktree-local `@neocortex/shared`. */
67
+ export type StoryWorktreeSharedResolution = 'unchanged' | 'already-linked' | 'linked';
68
+ /** @internal Test-only link seam (DEC-02); not part of the public contract. */
69
+ export type StoryWorktreeSymlink = (target: string, path: string, type: 'dir' | 'junction') => Promise<void>;
70
+ export interface StoryWorktreeSharedResolutionInput {
71
+ readonly worktreePath: string;
72
+ readonly repositoryRoot: string;
73
+ /** Selects the link type (`junction` on win32, relative `dir` elsewhere). */
74
+ readonly platform?: string;
75
+ }
76
+ /** @internal Test-only seams (DEC-02). Production callers omit this argument. */
77
+ export interface StoryWorktreeSharedResolutionInternals {
78
+ readonly symlink?: StoryWorktreeSymlink;
79
+ }
80
+ /**
81
+ * P227.10 (P227-REQ-06, P227-EX-11): make `@neocortex/shared` resolve to the
82
+ * story worktree's own `packages/shared`. Writes only under
83
+ * `<worktree>/node_modules/@neocortex/`; never replaces an existing entry,
84
+ * never falls back to an ancestor/main-checkout package and never echoes a
85
+ * path or errno (ADR-1..3, R1..R8).
86
+ */
87
+ export declare function ensureStoryWorktreeSharedResolution(input: StoryWorktreeSharedResolutionInput, internals?: StoryWorktreeSharedResolutionInternals): Promise<StoryWorktreePathResult<StoryWorktreeSharedResolution>>;
@@ -1 +1 @@
1
- import{createHash as w}from"node:crypto";import{lstat as c,mkdir as m,chmod as h}from"node:fs/promises";import{posix as d,win32 as l}from"node:path";const R=80,O="NEOCORTEX_STORY_WORKTREE_ROOT",T="NEOCORTEX_STORY_WORKTREE_ID",u=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,C=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;function v(e){const{epicId:r,storyId:o,dispatchId:n}=e;if(typeof r!="string"||!u.test(r)||r.includes(".")||typeof o!="string"||!u.test(o)||!o.startsWith(`${r}.`)||typeof n!="string"||!C.test(n))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};const s=w("sha256").update(`${r}|${o}|${n}`).digest("hex"),t=s.slice(0,8);return{ok:!0,value:Object.freeze({epicId:r,storyId:o,dispatchId:n,hash8:t,temporaryBranch:`nx/${r}/${t}`,executionBranch:`epic/${r}`,leaseId:`swt-${s.slice(0,24)}`,worktreeId:`nxwt-${t}`,worktreeRef:`wt/${t}`})}}function p(e){return e==="win32"?l:d}function k(e){return e==="linux"||e==="darwin"||e==="win32"?e:void 0}function x(e={}){const r=k(e.platform??process.platform);if(!r)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const o=p(r),n=e.env??process.env,s=e.override??n[O];if(s!==void 0&&s!=="")return o.isAbsolute(s)?{ok:!0,value:o.normalize(s)}:{ok:!1,reasonCode:"story-worktree-root-invalid"};const t=e.homedir,a=f=>f&&o.isAbsolute(f)?f:void 0;let i;return r==="linux"?i=a(n.XDG_CACHE_HOME)??(a(t)?o.join(t,".cache"):void 0):r==="darwin"?i=a(t)?o.join(t,"Library","Caches"):void 0:i=a(n.LOCALAPPDATA)??(a(t)?o.join(t,"AppData","Local"):void 0),i?{ok:!0,value:o.join(i,"nx","wt")}:{ok:!1,reasonCode:"story-worktree-root-invalid"}}function y(e,r,o,n){const s=i=>n?i.toLowerCase():i,t=e.relative(s(r),s(o)),a=t===".."||t.startsWith(`..${e.sep}`);return t===""||!a&&!e.isAbsolute(t)}function I(e){const r=k(e.platform??process.platform);if(!r)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const o=p(r);if(!/^[a-f0-9]{8}$/.test(e.hash8))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};if(!o.isAbsolute(e.root)||!o.isAbsolute(e.repositoryRoot))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const n=o.join(o.normalize(e.root),e.hash8);if(r==="win32"&&n.length>R)return{ok:!1,reasonCode:"story-worktree-path-too-long"};const s=r!=="linux";return y(o,e.repositoryRoot,n,s)||y(o,n,e.repositoryRoot,s)?{ok:!1,reasonCode:"story-worktree-path-inside-repository"}:{ok:!0,value:n}}async function $(e,r=process.platform){const o=r==="win32"?l:d;if(!o.isAbsolute(e))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const n=[o.dirname(e),e];try{await m(e,{recursive:!0,mode:448});for(const s of n){const t=await c(s);if(t.isSymbolicLink()||!t.isDirectory())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}if(r!=="win32"){await h(e,448);const s=await c(e);if((s.mode&63)!==0)return{ok:!1,reasonCode:"story-worktree-root-unsafe"};if(typeof process.getuid=="function"&&s.uid!==process.getuid())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}}catch{return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}return{ok:!0,value:e}}export{T as STORY_WORKTREE_ID_ENV,O as STORY_WORKTREE_ROOT_ENV,R as STORY_WORKTREE_WIN32_MAX_PATH,$ as ensurePrivateStoryWorktreeRoot,I as resolveStoryWorktreePath,x as resolveStoryWorktreeRoot,v as storyWorktreeIdentity};
1
+ import{createHash as z}from"node:crypto";import{lstat as v,mkdir as D,chmod as K,readFile as X,realpath as Y,stat as P,symlink as F}from"node:fs/promises";import{posix as O,win32 as _}from"node:path";const M=80,U="NEOCORTEX_STORY_WORKTREE_ROOT",Q="NEOCORTEX_STORY_WORKTREE_ID",W=/^P[1-9][0-9]*(?:\.[0-9]+)*$/,V=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/;function ee(e){const{epicId:o,storyId:t,dispatchId:r}=e;if(typeof o!="string"||!W.test(o)||o.includes(".")||typeof t!="string"||!W.test(t)||!t.startsWith(`${o}.`)||typeof r!="string"||!V.test(r))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};const s=z("sha256").update(`${o}|${t}|${r}`).digest("hex"),n=s.slice(0,8);return{ok:!0,value:Object.freeze({epicId:o,storyId:t,dispatchId:r,hash8:n,temporaryBranch:`nx/${o}/${n}`,executionBranch:`epic/${o}`,leaseId:`swt-${s.slice(0,24)}`,worktreeId:`nxwt-${n}`,worktreeRef:`wt/${n}`})}}function $(e){return e==="win32"?_:O}function A(e){return e==="linux"||e==="darwin"||e==="win32"?e:void 0}function re(e={}){const o=A(e.platform??process.platform);if(!o)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const t=$(o),r=e.env??process.env,s=e.override??r[U];if(s!==void 0&&s!=="")return t.isAbsolute(s)?{ok:!0,value:t.normalize(s)}:{ok:!1,reasonCode:"story-worktree-root-invalid"};const n=e.homedir,i=l=>l&&t.isAbsolute(l)?l:void 0;let f;return o==="linux"?f=i(r.XDG_CACHE_HOME)??(i(n)?t.join(n,".cache"):void 0):o==="darwin"?f=i(n)?t.join(n,"Library","Caches"):void 0:f=i(r.LOCALAPPDATA)??(i(n)?t.join(n,"AppData","Local"):void 0),f?{ok:!0,value:t.join(f,"nx","wt")}:{ok:!1,reasonCode:"story-worktree-root-invalid"}}function S(e,o,t,r){const s=f=>r?f.toLowerCase():f,n=e.relative(s(o),s(t)),i=n===".."||n.startsWith(`..${e.sep}`);return n===""||!i&&!e.isAbsolute(n)}function oe(e){const o=A(e.platform??process.platform);if(!o)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const t=$(o);if(!/^[a-f0-9]{8}$/.test(e.hash8))return{ok:!1,reasonCode:"story-worktree-identity-invalid"};if(!t.isAbsolute(e.root)||!t.isAbsolute(e.repositoryRoot))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const r=t.join(t.normalize(e.root),e.hash8);if(o==="win32"&&r.length>M)return{ok:!1,reasonCode:"story-worktree-path-too-long"};const s=o!=="linux";return S(t,e.repositoryRoot,r,s)||S(t,r,e.repositoryRoot,s)?{ok:!1,reasonCode:"story-worktree-path-inside-repository"}:{ok:!0,value:r}}async function te(e,o=process.platform){const t=o==="win32"?_:O;if(!t.isAbsolute(e))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const r=[t.dirname(e),e];try{await D(e,{recursive:!0,mode:448});for(const s of r){const n=await v(s);if(n.isSymbolicLink()||!n.isDirectory())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}if(o!=="win32"){await K(e,448);const s=await v(e);if((s.mode&63)!==0)return{ok:!1,reasonCode:"story-worktree-root-unsafe"};if(typeof process.getuid=="function"&&s.uid!==process.getuid())return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}}catch{return{ok:!1,reasonCode:"story-worktree-root-unsafe"}}return{ok:!0,value:e}}const B="@neocortex/shared",G=process.platform!=="linux";async function k(e){try{return await v(e)}catch{return}}async function C(e){try{return await Y(e)}catch{return}}async function N(e,o){try{const[t,r]=await Promise.all([P(e),P(o)]);return t.dev===r.dev&&t.ino===r.ino}catch{return!1}}async function g(e){const o=await k(e);return o!==void 0&&!o.isSymbolicLink()&&o.isDirectory()}async function se(e,o={}){const t=A(e.platform??process.platform);if(!t)return{ok:!1,reasonCode:"story-worktree-platform-unsupported"};const r=process.platform==="win32"?_:O;if(typeof e.worktreePath!="string"||typeof e.repositoryRoot!="string"||!r.isAbsolute(e.worktreePath)||!r.isAbsolute(e.repositoryRoot))return{ok:!1,reasonCode:"story-worktree-root-invalid"};const s=await C(e.worktreePath),n=await C(e.repositoryRoot);if(!s||!n)return{ok:!1,reasonCode:"story-worktree-root-invalid"};if(await N(s,n))return{ok:!0,value:"unchanged"};const i=a=>S(r,s,a,G),f=r.join(s,"packages","shared"),l=r.join(f,"package.json"),x=await k(l);if(!await g(f)||!x||!x.isFile())return{ok:!1,reasonCode:"story-worktree-shared-source-missing"};try{if(JSON.parse(await X(l,"utf8"))?.name!==B)return{ok:!1,reasonCode:"story-worktree-shared-source-missing"}}catch{return{ok:!1,reasonCode:"story-worktree-shared-source-missing"}}const w=await C(f);if(!w||!i(w))return{ok:!1,reasonCode:"story-worktree-shared-source-missing"};const E=r.join(s,"node_modules"),y=r.join(E,"@neocortex"),d=r.join(y,"shared"),I=async()=>{for(let a=r.join(s,"packages","client");;a=r.dirname(a)){const h=r.join(a,"node_modules","@neocortex","shared");if(await k(h))return h;if(r.dirname(a)===a)return}},p=a=>N(a,w),c=await I(),L=c!==void 0&&i(c);let R;if(c!==void 0&&L&&c!==d){if(!await p(c))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"};R="already-linked"}else if(c===d&&await p(c))R="already-linked";else{for(const u of[E,y]){const m=await k(u);if(m&&(m.isSymbolicLink()||!m.isDirectory()))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"}}if(await k(d))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"};try{await D(y,{recursive:!0})}catch{return{ok:!1,reasonCode:"story-worktree-shared-link-failed"}}const a=await C(y);if(!await g(E)||!await g(y)||!a||!i(a))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"};const h=o.symlink??((u,m,H)=>F(u,m,H));try{t==="win32"?await h(w,d,"junction"):await h(r.join("..","..","packages","shared"),d,"dir")}catch(u){if(u?.code!=="EEXIST"||!await p(d))return{ok:!1,reasonCode:u?.code==="EEXIST"?"story-worktree-shared-link-unsafe":"story-worktree-shared-link-failed"}}const b=await C(d);if(!b||!i(b)||!await p(d))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"};R="linked"}const T=await I();if(T===void 0||!await p(T))return{ok:!1,reasonCode:"story-worktree-shared-link-unsafe"};const j=await k(r.join(w,"dist","index.js"));return!j||!j.isFile()?{ok:!1,reasonCode:"story-worktree-shared-build-missing"}:{ok:!0,value:R}}export{Q as STORY_WORKTREE_ID_ENV,U as STORY_WORKTREE_ROOT_ENV,M as STORY_WORKTREE_WIN32_MAX_PATH,te as ensurePrivateStoryWorktreeRoot,se as ensureStoryWorktreeSharedResolution,oe as resolveStoryWorktreePath,re as resolveStoryWorktreeRoot,ee as storyWorktreeIdentity};
@@ -10,6 +10,7 @@
10
10
  *
11
11
  * See the LICENSE file in the project root for full license text.
12
12
  */
13
+ import { type GitLifecyclePhysicalIntegrationLockWait } from './git-lifecycle-store.js';
13
14
  export interface StoryWriteSetExtensionValue {
14
15
  readonly storyId: string;
15
16
  readonly epicId: string;
@@ -35,6 +36,8 @@ export interface ExtendStoryWriteSetOptions {
35
36
  readonly nowIso?: string;
36
37
  /** Test seam between the authority read and the CAS write (race reproduction). */
37
38
  readonly beforeCas?: () => Promise<void>;
39
+ /** P227.06: bounded wait for the physical integration lock (default 2000 ms, max 5000 ms). */
40
+ readonly lockWait?: GitLifecyclePhysicalIntegrationLockWait;
38
41
  }
39
42
  /**
40
43
  * Root-only, idempotent: re-applying the same set is a no-op, a superset
@@ -1 +1 @@
1
- import{execFile as E}from"node:child_process";import{createHash as D}from"node:crypto";import{readFile as k,realpath as S}from"node:fs/promises";import{join as P,resolve as A}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLock as C,ensureRuntimeStory as L,isStoryWorktreeIntegrationReceiptRecord as b,isStoryWriteSetExtensionPath as T,mutateGitLifecycleRuntime as W,readGitLifecycleRuntime as j,readStoryWorktreeEvidence as O,releaseGitLifecyclePhysicalIntegrationLock as G,STORY_WRITE_SET_MAX_ENTRIES as I,storyWriteSetExtensionDigest as $,storyWriteSetExtensionPaths as z,verifyGitLifecyclePhysicalIntegrationLock as M}from"./git-lifecycle-store.js";const N=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class p extends Error{reasonCode;constructor(n){super(n),this.reasonCode=n}}function t(e){throw new p(e)}function _(e,n){return new Promise((i,r)=>{E("git",[...n],{cwd:e,encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(c,s)=>c?r(new p("story-write-set-extension-not-root")):i(String(s).trim()))})}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function q(e){return D("sha256").update([...e].sort().join("\0")).digest("hex")}function v(e,n,i,r,c){const s=g(g(n.stories)?.[i]);s||t("story-write-set-extension-story-missing");const d=typeof s.epic_id=="string"?s.epic_id:i.split(".")[0];i.startsWith(`${d}.`)||t("story-write-set-extension-story-missing");const y=e.stories[i];(O(e,d)?.receipts??[]).filter(b).some(a=>a.storyId===i&&a.outcome==="integrated")&&t("story-write-set-extension-story-integrated"),(y?.checkpoint||s.checkpoint)&&t("story-write-set-extension-checkpoint-accepted");const u=g(e.epics[d]?.branch_lease);u&&Date.parse(String(u.expiresAt))>c&&t("story-write-set-extension-writer-active");const f=z(y);y?.write_set_extension!==void 0&&f.length===0&&t("story-write-set-extension-invalid"),f.some(a=>!r.includes(a))&&t("story-write-set-extension-not-superset");const l=Array.isArray(s.files_to_modify)?s.files_to_modify.filter(a=>typeof a=="string"):[],w=[...new Set([...l,...r])].sort();return w.length>I&&t("story-write-set-extension-too-large"),{epicId:d,union:w,unchanged:f.length===r.length}}async function V(e){const n=A(e.projectRoot);let i;try{(typeof e.storyId!="string"||!N.test(e.storyId))&&t("story-write-set-extension-story-invalid"),(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>I||e.paths.some(o=>!T(o)))&&t("story-write-set-extension-path-invalid");const r=[...new Set(e.paths)].sort(),c=await S(await _(n,["rev-parse","--absolute-git-dir"])),s=await S(await _(n,["rev-parse","--path-format=absolute","--git-common-dir"]));c!==s&&t("story-write-set-extension-not-root");const d=new Date(e.nowIso??Date.now()).toISOString(),y=P(n,".neocortex","state.json"),h=await k(y,"utf8"),u=g(JSON.parse(h))??t("story-write-set-extension-state-invalid"),f=await j(n,{required:!0}),l=v(f,u,e.storyId,r,Date.now()),w=$(r),a=o=>({ok:!0,value:Object.freeze({storyId:e.storyId,epicId:l.epicId,outcome:o,extensionPathCount:r.length,extensionDigest:w,authorizedPathCount:l.union.length,claimRevision:q(l.union)})});if(l.unchanged)return a("unchanged");const x=`write-set-extension-${w.slice(0,40)}`;i=await C(n,{kind:"direct",storyId:e.storyId,sessionId:x,idempotencyKey:x,expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1}),i.ok||t(i.reasonCode==="git-lifecycle-integration-backpressure"?"story-write-set-extension-backpressure":"story-write-set-extension-lock-failed");const m=i;await e.beforeCas?.();const R={schemaVersion:1,kind:"root-write-set-extension",paths:r,digest:w,approvedAt:d,approvedBy:"root_agent"};try{await W(n,o=>{v(o,u,e.storyId,r,Date.now()).unchanged&&t("story-write-set-extension-raced"),L(o,e.storyId).write_set_extension=R},{expectedRevision:f.revision,preCommit:async()=>{await M(m.path,m.owner)||t("story-write-set-extension-lock-raced"),await k(y,"utf8")!==h&&t("story-write-set-extension-raced")}})}catch(o){throw o instanceof Error&&o.message==="git-lifecycle-runtime-revision-conflict"&&t("story-write-set-extension-raced"),o}return a("recorded")}catch(r){if(r instanceof p)return{ok:!1,reasonCode:r.reasonCode};const c=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(c)?{ok:!1,reasonCode:c}:{ok:!1,reasonCode:"story-write-set-extension-failed"}}finally{i?.ok&&await G(i.path,i.owner).catch(()=>{})}}export{V as extendStoryWriteSet};
1
+ import{execFile as C}from"node:child_process";import{createHash as L}from"node:crypto";import{readFile as S,realpath as I}from"node:fs/promises";import{join as W,resolve as b}from"node:path";import{acquireGitLifecyclePhysicalIntegrationLockWithin as T,ensureRuntimeStory as j,isStoryWorktreeIntegrationReceiptRecord as O,isStoryWriteSetExtension as G,isStoryWriteSetExtensionPath as $,mutateGitLifecycleRuntime as z,readGitLifecycleRuntime as B,readStoryWorktreeEvidence as M,releaseGitLifecyclePhysicalIntegrationLock as N,STORY_WRITE_SET_MAX_ENTRIES as _,storyWriteSetExtensionDigest as q,storyWriteSetExtensionPaths as F,verifyGitLifecyclePhysicalIntegrationLock as H}from"./git-lifecycle-store.js";const V=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class m extends Error{reasonCode;constructor(s){super(s),this.reasonCode=s}}function t(e){throw new m(e)}function v(e,s){return new Promise((i,r)=>{C("git",[...s],{cwd:e,encoding:"utf8",timeout:3e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(c,o)=>c?r(new m("story-write-set-extension-not-root")):i(String(o).trim()))})}function h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Y(e){try{return G(e)}catch{return!1}}function J(e){return L("sha256").update([...e].sort().join("\0")).digest("hex")}function R(e,s,i,r,c){const o=h(h(s.stories)?.[i]);o||t("story-write-set-extension-story-missing");const y=typeof o.epic_id=="string"?o.epic_id:i.split(".")[0];i.startsWith(`${y}.`)||t("story-write-set-extension-story-missing");const d=e.stories[i];(M(e,y)?.receipts??[]).filter(O).some(a=>a.storyId===i&&a.outcome==="integrated")&&t("story-write-set-extension-story-integrated"),(d?.checkpoint||o.checkpoint)&&t("story-write-set-extension-checkpoint-accepted");const f=h(e.epics[y]?.branch_lease);f&&Date.parse(String(f.expiresAt))>c&&t("story-write-set-extension-writer-active"),d?.write_set_extension!==void 0&&!Y(d.write_set_extension)&&t("story-write-set-extension-invalid");const l=F(d);l.some(a=>!r.includes(a))&&t("story-write-set-extension-not-superset");const g=Array.isArray(o.files_to_modify)?o.files_to_modify.filter(a=>typeof a=="string"):[],u=[...new Set([...g,...r])].sort();return u.length>_&&t("story-write-set-extension-too-large"),{epicId:y,union:u,unchanged:l.length===r.length}}async function ee(e){const s=b(e.projectRoot);let i;try{(typeof e.storyId!="string"||!V.test(e.storyId))&&t("story-write-set-extension-story-invalid"),(!Array.isArray(e.paths)||e.paths.length===0||e.paths.length>_||e.paths.some(n=>!$(n)))&&t("story-write-set-extension-path-invalid");const r=[...new Set(e.paths)].sort(),c=await I(await v(s,["rev-parse","--absolute-git-dir"])),o=await I(await v(s,["rev-parse","--path-format=absolute","--git-common-dir"]));c!==o&&t("story-write-set-extension-not-root");const y=new Date(e.nowIso??Date.now()).toISOString(),d=W(s,".neocortex","state.json"),p=async()=>{const n=await S(d,"utf8"),w=h(JSON.parse(n))??t("story-write-set-extension-state-invalid"),k=await B(s,{required:!0});return{trackedBytes:n,tracked:w,runtime:k,plan:R(k,w,e.storyId,r,Date.now())}},f=q(r),l=(n,w)=>({ok:!0,value:Object.freeze({storyId:e.storyId,epicId:n.epicId,outcome:w,extensionPathCount:r.length,extensionDigest:f,authorizedPathCount:n.union.length,claimRevision:J(n.union)})}),g=await p();if(g.plan.unchanged)return l(g.plan,"unchanged");const u=`write-set-extension-${f.slice(0,40)}`;i=await T(s,{kind:"direct",storyId:e.storyId,sessionId:u,idempotencyKey:u,expiresAt:new Date(Date.now()+300*1e3).toISOString(),persistent:!1},e.lockWait),i.ok||t(i.reasonCode==="git-lifecycle-integration-backpressure"?"story-write-set-extension-backpressure":"story-write-set-extension-lock-failed");const a=i,{trackedBytes:E,tracked:A,runtime:D,plan:x}=await p();if(x.unchanged)return l(x,"unchanged");await e.beforeCas?.();const P={schemaVersion:1,kind:"root-write-set-extension",paths:r,digest:f,approvedAt:y,approvedBy:"root_agent"};try{await z(s,n=>{R(n,A,e.storyId,r,Date.now()).unchanged&&t("story-write-set-extension-raced"),j(n,e.storyId).write_set_extension=P},{expectedRevision:D.revision,preCommit:async()=>{await H(a.path,a.owner)||t("story-write-set-extension-lock-raced"),await S(d,"utf8")!==E&&t("story-write-set-extension-raced")}})}catch(n){throw n instanceof Error&&n.message==="git-lifecycle-runtime-revision-conflict"&&t("story-write-set-extension-raced"),n}return l(x,"recorded")}catch(r){if(r instanceof m)return{ok:!1,reasonCode:r.reasonCode};const c=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(c)?{ok:!1,reasonCode:c}:{ok:!1,reasonCode:"story-write-set-extension-failed"}}finally{i?.ok&&await N(i.path,i.owner).catch(()=>{})}}export{ee as extendStoryWriteSet};
@@ -1 +1 @@
1
- import{execFileSync as z}from"node:child_process";import{createHash as N}from"node:crypto";import{lstatSync as y,readFileSync as E,readlinkSync as D,realpathSync as v}from"node:fs";import{join as O,resolve as l}from"node:path";import{rootProjectMemoryPaths as j}from"./shared-root-memory-types.js";import{parseRefreshMemoryArgs as x,refreshProjectMemoryTargets as M,verifyProjectMemoryTargets as J}from"../commands/refresh-memory.js";import{assertProjectMemoryPaths as w}from"../memory/project-memory-path-scope.js";import{classifyProjectMemoryUpdate as P}from"../memory/project-memory-writer.js";const d=r=>N("sha256").update(r).digest("hex"),h=new WeakMap,n=()=>{throw new Error("private-root-memory-writer-unverified")};function c(r,...e){return z("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.startsWith("GIT_"))),timeout:3e4,maxBuffer:2*1024*1024})}function m(r,e){if(!j().includes(e))return n();w(r,[e]);const i=O(r,e);let o;try{o=y(i)}catch(a){return a.code==="ENOENT"?{kind:"absent",sha256:null}:n()}if(o.uid!==process.getuid?.()||o.nlink!==1||(o.mode&18)!==0&&!o.isSymbolicLink())return n();if(o.isSymbolicLink()){const a=D(i);return l(r,e,"..",a)!==O(l(r),"NEOCORTEX.md")?n():{kind:"symlink",sha256:d(a),linkTarget:a}}return!o.isFile()||o.size>512*1024?n():{kind:"regular",sha256:d(E(i))}}function G(r){const e=l(r.snapshotRoot),i=l(r.backupDirectory),o=y(e),a=y(i);if(!o.isDirectory()||o.uid!==process.getuid?.()||(o.mode&63)!==0||v(e)!==e||!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0||v(i)!==i||i===e||i.startsWith(e+"/")||!/^[a-f0-9]{40,64}$/.test(r.expectedSnapshotSha)||!Array.isArray(r.notes)||r.notes.length<1||r.notes.length>8||r.notes.some(t=>typeof t!="string"||Buffer.byteLength(t)<1||Buffer.byteLength(t)>512)||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha||c(e,"status","--porcelain=v1","--untracked-files=all").length!==0)return n();for(const t of r.notes)P(t);const f=j(),g=new Map(f.map(t=>[t,m(e,t)])),S=x(["--project-root",e,...r.notes.flatMap(t=>["--note",t])]);if(M({...S,dryRun:!0}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();for(const[t,s]of g)if(JSON.stringify(m(e,t))!==JSON.stringify(s))return n();if(M({...S,backupDirectory:i}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();const R=J(x(["--project-root",e,"--verify"])),u=c(e,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(t=>t.slice(3));if(u.some(t=>!f.includes(t))||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha)return n();const p=f.flatMap(t=>{const s=g.get(t),k=m(e,t);return JSON.stringify(s)===JSON.stringify(k)?[]:[Object.freeze({path:t,before:Object.freeze(s),after:Object.freeze(k)})]});if(p.some(t=>!u.includes(t.path))||u.some(t=>!p.some(s=>s.path===t)))return n();const b=Object.freeze(Object.create(null));return h.set(b,Object.freeze({snapshotRoot:e,sourceSnapshotSha:r.expectedSnapshotSha,notesSha256:d(JSON.stringify(r.notes)),files:Object.freeze(p),verification:Object.freeze(R)})),b}function U(r){return h.get(r)}function X(r){const e=h.get(r);if(!e||c(e.snapshotRoot,"rev-parse","HEAD").trim()!==e.sourceSnapshotSha)return n();const i=c(e.snapshotRoot,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(o=>o.slice(3)).sort();return JSON.stringify(i)!==JSON.stringify(e.files.map(o=>o.path).sort())||e.files.some(o=>JSON.stringify(m(e.snapshotRoot,o.path))!==JSON.stringify(o.after))?n():e}export{G as executeRootMemoryWriter,U as projectRootMemoryWriterExecution,m as rootMemoryFileState,X as verifyRootMemoryWriterExecution};
1
+ import{execFileSync as z}from"node:child_process";import{createHash as N}from"node:crypto";import{lstatSync as y,readFileSync as E,readlinkSync as D,realpathSync as v}from"node:fs";import{join as O,resolve as l}from"node:path";import{rootProjectMemoryPaths as j}from"./shared-root-memory-types.js";import{parseRefreshMemoryArgs as x,refreshProjectMemoryTargets as M,verifyProjectMemoryTargets as J}from"../commands/refresh-memory.js";import{assertProjectMemoryPaths as w}from"../memory/project-memory-path-scope.js";import{classifyProjectMemoryUpdate as P}from"../memory/project-memory-writer.js";const d=r=>N("sha256").update(r).digest("hex"),h=new WeakMap,n=()=>{throw new Error("private-root-memory-writer-unverified")};function c(r,...e){return z("git",e,{cwd:r,encoding:"utf8",stdio:["ignore","pipe","ignore"],env:Object.fromEntries(Object.entries(process.env).filter(([i])=>!i.startsWith("GIT_"))),timeout:3e4,maxBuffer:2*1024*1024})}function m(r,e){if(!j().includes(e))return n();w(r,[e]);const i=O(r,e);let o;try{o=y(i)}catch(a){return a.code==="ENOENT"?{kind:"absent",sha256:null}:n()}if(o.uid!==process.getuid?.()||o.nlink!==1||(o.mode&18)!==0&&!o.isSymbolicLink())return n();if(o.isSymbolicLink()){const a=D(i);return l(r,e,"..",a)!==O(l(r),"NEOCORTEX.md")?n():{kind:"symlink",sha256:d(a),linkTarget:a}}return!o.isFile()||o.size>512*1024?n():{kind:"regular",sha256:d(E(i))}}function C(r){const e=l(r.snapshotRoot),i=l(r.backupDirectory),o=y(e),a=y(i);if(!o.isDirectory()||o.uid!==process.getuid?.()||(o.mode&63)!==0||v(e)!==e||!a.isDirectory()||a.isSymbolicLink()||a.uid!==process.getuid?.()||(a.mode&63)!==0||v(i)!==i||i===e||i.startsWith(e+"/")||!/^[a-f0-9]{40,64}$/.test(r.expectedSnapshotSha)||!Array.isArray(r.notes)||r.notes.length<1||r.notes.length>8||r.notes.some(t=>typeof t!="string"||Buffer.byteLength(t)<1||Buffer.byteLength(t)>512)||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha||c(e,"status","--porcelain=v1","--untracked-files=all").length!==0)return n();for(const t of r.notes)P(t);const f=j(),g=new Map(f.map(t=>[t,m(e,t)])),S=x(["--project-root",e,...r.notes.map(t=>`--note=${t}`)]);if(M({...S,dryRun:!0}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();for(const[t,s]of g)if(JSON.stringify(m(e,t))!==JSON.stringify(s))return n();if(M({...S,backupDirectory:i}).some(t=>t.files.some(s=>s.fallbackReason||s.remediationDebt||s.mode==="compatibility-materialized-fallback"||!f.includes(s.relativeFile))))return n();const R=J(x(["--project-root",e,"--verify"])),u=c(e,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(t=>t.slice(3));if(u.some(t=>!f.includes(t))||c(e,"rev-parse","HEAD").trim()!==r.expectedSnapshotSha)return n();const p=f.flatMap(t=>{const s=g.get(t),k=m(e,t);return JSON.stringify(s)===JSON.stringify(k)?[]:[Object.freeze({path:t,before:Object.freeze(s),after:Object.freeze(k)})]});if(p.some(t=>!u.includes(t.path))||u.some(t=>!p.some(s=>s.path===t)))return n();const b=Object.freeze(Object.create(null));return h.set(b,Object.freeze({snapshotRoot:e,sourceSnapshotSha:r.expectedSnapshotSha,notesSha256:d(JSON.stringify(r.notes)),files:Object.freeze(p),verification:Object.freeze(R)})),b}function G(r){return h.get(r)}function U(r){const e=h.get(r);if(!e||c(e.snapshotRoot,"rev-parse","HEAD").trim()!==e.sourceSnapshotSha)return n();const i=c(e.snapshotRoot,"status","--porcelain=v1","-z","--untracked-files=all").split("\0").filter(Boolean).map(o=>o.slice(3)).sort();return JSON.stringify(i)!==JSON.stringify(e.files.map(o=>o.path).sort())||e.files.some(o=>JSON.stringify(m(e.snapshotRoot,o.path))!==JSON.stringify(o.after))?n():e}export{C as executeRootMemoryWriter,G as projectRootMemoryWriterExecution,m as rootMemoryFileState,U as verifyRootMemoryWriterExecution};