@ornexus/neocortex 4.66.0 → 4.66.2

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 (94) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/docs/install/linux-global-install.md +21 -1
  4. package/install.js +22 -28
  5. package/install.ps1 +19 -24
  6. package/install.sh +26 -30
  7. package/package.json +2 -2
  8. package/packages/client/dist/commands/doctor.d.ts +26 -1
  9. package/packages/client/dist/commands/doctor.js +2 -2
  10. package/packages/client/dist/commands/invoke.d.ts +149 -1
  11. package/packages/client/dist/commands/invoke.js +88 -83
  12. package/packages/client/dist/commands/planning-qa.d.ts +57 -0
  13. package/packages/client/dist/commands/planning-qa.js +1 -1
  14. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
  15. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  16. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  17. package/packages/client/dist/commands/story-worktree.js +1 -1
  18. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
  19. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  20. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  21. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  22. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
  23. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  24. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  29. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  30. package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
  31. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  32. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  33. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  34. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  35. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  36. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  37. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  38. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  39. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  40. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  41. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  42. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  43. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  44. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  45. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  46. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  47. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  48. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  49. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  50. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  51. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  52. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  53. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  54. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  55. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  56. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  57. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  58. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  59. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  60. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  61. package/packages/client/dist/private-execution/harness-process.js +1 -0
  62. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  63. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  64. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  65. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -3
  66. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +7 -4
  67. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  68. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  69. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  70. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  71. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  72. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  73. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  74. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  75. package/packages/shared/dist/compatibility/index.js +28 -0
  76. package/targets-stubs/antigravity/gemini.md +1 -1
  77. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  78. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  79. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  80. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  81. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  82. package/targets-stubs/claude-code/neocortex.md +2 -2
  83. package/targets-stubs/codex/AGENTS.md +1 -1
  84. package/targets-stubs/cursor/agent.md +2 -2
  85. package/targets-stubs/gemini-cli/agent.md +2 -2
  86. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  87. package/targets-stubs/grok/SKILL.md +3 -3
  88. package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
  89. package/targets-stubs/grok/install-grok.sh +45 -8
  90. package/targets-stubs/lib/managed-config-merge.js +21 -1
  91. package/targets-stubs/lib/mcp-merge.js +18 -7
  92. package/targets-stubs/opencode/neocortex-root.md +1 -1
  93. package/targets-stubs/opencode/neocortex.md +1 -1
  94. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,4 +1,4 @@
1
- import{createHash as ke,randomBytes as Z}from"node:crypto";import{existsSync as M}from"node:fs";import{chmod as _e,open as ee,readFile as B,readdir as te,rename as Ae,rm as V,stat as $,unlink as Se}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,assertGitLifecyclePrivateFile as se,compactStoryWorktreeJournal as be,ensureGitLifecyclePrivateChildDirectory as De,ensureStoryWorktreeJournal as oe,gitLifecycleRuntimeDirectory as ne,isStoryWorktreeCleanupReceiptRecord as ae,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as j}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as de}from"./git-lifecycle-step-ids.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ce,runStoryWorktreeGit as S,storyWorktreePathAbsence as Te}from"./story-worktree-manager.js";const G="story-worktree-cleanup.json",Y="story-worktree-bundles",Ce=256,le=Object.freeze(["success","failure","abandon","orphan-recovery"]),Pe=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Le=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed",ORPHAN_PROGRESS_RESET:"story-worktree-orphan-progress-reset",ORPHAN_PROGRESS_PRESERVED:"story-worktree-orphan-progress-preserved"}),i=Le,ue=10080*60*1e3,Me=600*1e3,Be=64,Ve=512*1024*1024,he=3,Ue=50,xe=/^swt-[a-f0-9]{24}$/,K=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,fe=/^[a-f0-9]{64}$/,We=/^[a-f0-9]{16}$/,me=/^P[1-9][0-9]*$/,He=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,pe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ee=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,Re=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,z=["integrated","failed","abandoned","bundled","remove-pending"],Fe="last_step,status,steps_completed",je=new Set(["backlog","ready_to_start"]);function Ge(l){const{runtime:e,epicId:t,storyId:r}=l,s=O(e.stories[r]),n=s?Object.keys(s).filter(p=>p!=="write_set_extension").sort():[];if(n.length===0)return"none";const o=s.steps_completed;if(!(n.join(",")===Fe&&s.status==="branch-ready"&&s.last_step===de&&Array.isArray(o)&&o.length===1&&o[0]===de)||!l.loss.worktreeAbsent||!l.loss.branchGone||l.loss.bundled||Object.values(e.storyWorktrees?.entries??{}).some(p=>p.storyId===r&&p.leaseId!==l.recoveredLeaseId))return"preserved";let h;try{h=l.trackedText===void 0?void 0:O(JSON.parse(l.trackedText))}catch{return"preserved"}const a=O(h?.stories),d=O(a?.[r]),g=d?.steps_completed;if(!d||!je.has(String(d.status))||g!==void 0&&(!Array.isArray(g)||g.length>0)||d.branch_name||d.checkpoint||d.commit_sha)return"preserved";const E=O(O(e.epics[t])?.story_worktree_evidence);if(E!==void 0){const p=E.receipts,D=E.specAcceptances;if(p!==void 0&&!Array.isArray(p)||D!==void 0&&!Array.isArray(D))return"preserved";const c=R=>{const y=O(R);return!y||y.storyId===r||Array.isArray(y.storyIds)&&y.storyIds.includes(r)};if(p?.some(c)||D?.some(c))return"preserved"}return"reset"}class H extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function u(l){throw new H(l)}function x(l){return ke("sha256").update(l).digest("hex")}function q(l){return new Promise(e=>setTimeout(e,l))}function we(l){return[...new Set(l)]}function Ye(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function J(l,e){return`${l}-${e.slice(0,12)}.bundle`}function ge(l=Oe()){return x(`neocortex.p225.owner-host|${l}`)}function O(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0}const ye=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Ke=new Set([...ye,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Ie(l,e){const t=O(e);if(!t||Object.keys(t).some(n=>!Ke.has(n))||ye.some(n=>t[n]===void 0))return!1;const r=t.remotePush===void 0?void 0:O(t.remotePush);if(t.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!pe.test(r.remote)||typeof r.branch!="string"||!Ee.test(r.branch)||!r.branch.startsWith(`nx/${String(t.epicId)}/`)||typeof r.sha!="string"||!K.test(r.sha)))return!1;const s=n=>t[n]===void 0||typeof t[n]=="string"&&$e.test(t[n])&&Number.isFinite(Date.parse(t[n]));return t.schemaVersion===1&&t.leaseId===l&&xe.test(l)&&typeof t.epicId=="string"&&me.test(t.epicId)&&typeof t.storyId=="string"&&He.test(t.storyId)&&t.storyId.startsWith(`${t.epicId}.`)&&Pe.includes(t.state)&&Number.isSafeInteger(t.removeAttempts)&&t.removeAttempts>=0&&t.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&t.claimToken===void 0==(t.claimExpiresAt===void 0)&&(t.claimToken===void 0||typeof t.claimToken=="string"&&We.test(t.claimToken))&&(t.trigger===void 0||le.includes(t.trigger))&&(t.headSha===void 0||typeof t.headSha=="string"&&K.test(t.headSha))&&(t.bundleDigest===void 0||typeof t.bundleDigest=="string"&&fe.test(t.bundleDigest)&&t.headSha!==void 0&&t.bundleExpiresAt!==void 0)&&(t.bundleBytes===void 0||Number.isSafeInteger(t.bundleBytes)&&t.bundleBytes>0)&&(t.remoteBranchRemoved===void 0||typeof t.remoteBranchRemoved=="boolean")&&(t.ownerPid===void 0||Number.isSafeInteger(t.ownerPid)&&t.ownerPid>0)&&(t.ownerHostDigest===void 0||typeof t.ownerHostDigest=="string"&&fe.test(t.ownerHostDigest))}function Q(l){let e;try{e=JSON.parse(l)}catch{u(i.STATE_INVALID)}const t=O(e),r=O(t?.records);return(!t||Object.keys(t).length!==2||t.schemaVersion!==1||!r||Object.keys(r).length>Ce||!Object.entries(r).every(([s,n])=>Ie(s,n)))&&u(i.STATE_INVALID),{schemaVersion:1,records:r}}async function ve(l){const e=A(l,F),t=A(e,G);if(!M(t))return{schemaVersion:1,records:{}};try{await se(t,e)}catch{u(i.STATE_INVALID)}return Q(await B(t,"utf8"))}function P(l,e){return l?.claimToken!==void 0&&l.claimExpiresAt!==void 0&&Date.parse(l.claimExpiresAt)>e}async function at(l,e,t=Date.now()){try{const r=(await ve(l)).records[e];return r!==void 0&&(z.includes(r.state)||P(r,t))}catch{return!0}}class ze{options;manager;now;isProcessAlive;constructor(e){this.options=e,this.manager=e.manager??new Ne({projectRoot:e.projectRoot,...e.worktreeRoot?{worktreeRoot:e.worktreeRoot}:{},...e.now?{now:e.now}:{}}),this.now=e.now??(()=>new Date),this.isProcessAlive=e.isProcessAlive??Ye}async readState(e){return ve(e?.commonDir??(await this.facts()).commonDir)}async recordPush(e){return this.guard(async()=>{(typeof e.remote!="string"||!pe.test(e.remote))&&u("story-worktree-remote-invalid");const t=await this.probe(e.leaseId);(t.ownership!=="proven"||!t.headSha)&&u("story-worktree-ownership-unproven"),(t.entry.workspaceMechanism!=="client_managed_worktree"||!Ee.test(t.entry.temporaryBranch))&&u(i.ADOPTED_BRANCH),await this.gitOk(t.facts.mainRoot,["config","--get",`remote.${e.remote}.url`])||u(i.REMOTE_UNKNOWN);const r=await this.lsRemote(t.facts.mainRoot,e.remote,t.entry.temporaryBranch);r===null&&u(i.REMOTE_UNVERIFIED),r===void 0&&u(i.REMOTE_ABSENT),r!==t.headSha&&u(i.REMOTE_DIVERGED);const s={remote:e.remote,branch:t.entry.temporaryBranch,sha:r};return await this.update(t.entry,void 0,n=>{const o={...n,remotePush:s};return delete o.remoteBranchRemoved,o}),{ok:!0,value:{leaseId:t.entry.leaseId,...s}}})}async registerOwnerProcess(e){return this.guard(async()=>{(!Number.isSafeInteger(e.pid)||e.pid<=0)&&u("story-worktree-owner-pid-invalid");const t=await this.probe(e.leaseId);return await this.update(t.entry,void 0,r=>({...r,ownerPid:e.pid,ownerHostDigest:ge()})),{ok:!0,value:{leaseId:t.entry.leaseId}}})}async cleanup(e){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(e)}))}async sweep(e={}){return this.guard(async()=>{e.epicId!==void 0&&!me.test(e.epicId)&&u("story-worktree-identity-invalid");const t=e.dryRun===!0,r=await this.facts(),s=await j(this.options.projectRoot),n=Object.values(s.storyWorktrees?.entries??{}),o=n.filter(c=>e.epicId===void 0||c.epicId===e.epicId).sort((c,R)=>c.leaseId.localeCompare(R.leaseId)),f=await this.readState(r),m=this.now().getTime(),h=ge(),a=[],d=[];for(const c of o){const R=f.records[c.leaseId],y=R!==void 0&&z.includes(R.state),C=Date.parse(c.expiresAt)<=m,k=R?.ownerPid!==void 0&&R.ownerHostDigest===h&&this.isProcessAlive(R.ownerPid),L=!k&&!P(R,m)&&!y&&!C&&c.state==="active"&&await Te(c.worktreePath)==="enoent";if(!L&&(k||P(R,m)||!y&&!C)){const T=k?i.OWNER_ALIVE:P(R,m)?i.CLAIMED:i.LEASE_LIVE;a.push({leaseId:c.leaseId,action:"skipped",reasonCode:T});continue}const W=y?R?.trigger==="success"&&C?"orphan-recovery":R?.trigger??"orphan-recovery":"orphan-recovery";let v;try{v={ok:!0,value:await this.cleanupUnguarded({leaseId:c.leaseId,trigger:W,dryRun:t,...L?{requireVanished:!0}:{}})}}catch(T){v={ok:!1,reasonCode:T instanceof H?T.reasonCode:i.SWEEP_FAILED}}if(!v.ok&&L&&v.reasonCode===i.LEASE_LIVE){a.push({leaseId:c.leaseId,action:"skipped",reasonCode:i.LEASE_LIVE});continue}if(!v.ok){a.push({leaseId:c.leaseId,action:"preserved",reasonCode:v.reasonCode}),d.push(v.reasonCode);continue}const _=v.value,N=await this.reconcileOrphanProgress(c,_,r,t);_.outcome==="dry-run"?a.push({leaseId:c.leaseId,action:"planned",plannedActions:_.plannedActions??[]}):_.outcome==="remove-pending"?(a.push({leaseId:c.leaseId,action:"remove-pending",reasonCode:i.REMOVE_PENDING,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{}}),d.push(i.REMOVE_PENDING)):(a.push({leaseId:c.leaseId,action:"recovered",reasonCode:i.ORPHAN_RECOVERED,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{},..._.absenceProof?{absenceProof:_.absenceProof}:{}}),d.push(i.ORPHAN_RECOVERED)),N&&(a.push(N),N.reasonCode&&d.push(N.reasonCode))}const g=new Set(n.map(c=>c.leaseId));for(const c of Object.values(f.records).sort((R,y)=>R.leaseId.localeCompare(y.leaseId))){if(g.has(c.leaseId)||c.state==="removed"||P(c,m)||e.epicId!==void 0&&c.epicId!==e.epicId)continue;const R=await this.closeDetachedRecord(c,r,t);a.push({leaseId:c.leaseId,action:t?"planned":"record-closed",...R?{reasonCode:R}:{}}),R&&d.push(R)}const E=await this.expireBundles(f,r,m,t),p=await this.manager.registeredWorktrees();p.ok||u(p.reasonCode);const D=p.value.worktrees.filter(c=>!n.some(R=>this.manager.sameWorktreePath(R.worktreePath,c.path))).length;return D>0&&d.push(i.MANUAL_PRESERVED),{ok:!0,value:{dryRun:t,entriesScanned:o.length,recovered:a.filter(c=>c.action==="recovered").length,removePending:a.filter(c=>c.action==="remove-pending").length,preserved:a.filter(c=>c.action==="preserved").length,skipped:a.filter(c=>c.action==="skipped").length,manualWorktreesPreserved:D,bundlesExpired:E,items:a,reasonCodes:we(d)}}})}async cleanupUnguarded(e){le.includes(e.trigger)||u("story-worktree-trigger-invalid");const t=await this.probe(e.leaseId),{entry:r,facts:s}=t;e.requireVanished===!0&&(t.pathAbsence!=="enoent"||r.state!=="active")&&u(i.LEASE_LIVE);const o=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return e.trigger!=="orphan-recovery"&&u("story-worktree-ownership-unproven"),this.recoverCreating(t,e.dryRun===!0);const f=o!==void 0&&z.includes(o.state);let m=!1;t.pathExists||(t.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.trigger!=="orphan-recovery"&&!f&&u("story-worktree-ownership-unproven"),m=!0),!m&&t.ownership!=="proven"&&u("story-worktree-ownership-unproven"),!m&&t.clean!==!0&&u(e.trigger==="success"?"story-worktree-dirty":i.DIRTY_PRESERVED),t.epicHead||u("story-worktree-epic-branch-missing");const h=t.epicHead,a=m?t.branchSha:t.headSha;!m&&!a&&u("story-worktree-git-failed");const d=t.integrated===!0;e.trigger==="success"&&!d&&u("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",E=o?.bundleDigest!==void 0&&o.headSha!==void 0&&o.headSha===a&&await this.bundleMatches(s,r.leaseId,o.headSha,o.bundleDigest),p=!d&&a!==void 0&&(g||e.trigger==="orphan-recovery")&&!E,D=o?.remotePush!==void 0&&o.remoteBranchRemoved!==!0;if(e.dryRun===!0){const y=[...p?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&t.branchSha?["delete-local-branch"]:[],...D?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:e.trigger,state:o?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const c=await this.claim(r);let R=!1;try{let y=E?o?.bundleDigest:void 0;if(p){const I=await this.createBundle(t,a,h);y=I.digest,await this.update(r,c,w=>({...w,state:"bundled",trigger:e.trigger,headSha:a,bundleDigest:I.digest,bundleBytes:I.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ue)).toISOString()}))}else if(!E){const I=d?"integrated":e.trigger==="failure"?"failed":"abandoned";await this.update(r,c,w=>({...w,state:w.state==="remove-pending"?"remove-pending":I,trigger:e.trigger,...a?{headSha:a}:{}}))}if(m)await S(s.mainRoot,["worktree","remove",r.worktreePath]);else{const I=this.options.removeAttempts??he;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,I))return await this.update(r,c,w=>({...w,state:"remove-pending",trigger:e.trigger,removeAttempts:Math.min(1e3,w.removeAttempts+I)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:e.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[i.REMOVE_PENDING]}}await S(s.mainRoot,["worktree","prune"]);const C=await this.manager.registeredWorktrees();C.ok||u(C.reasonCode),C.value.worktrees.some(I=>this.manager.sameWorktreePath(I.path,r.worktreePath))&&u(i.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(i.ADOPTED_BRANCH);else if(t.branchSha){const I=a??t.branchSha,w=d||y!==void 0,b=C.value.worktrees.some(U=>U.branch===r.temporaryBranch);w?b?k.push(i.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,I])?L=!0:k.push(i.BRANCH_MOVED):k.push(i.ORPHAN_UNPROVEN)}const W=(await this.readState(s)).records[r.leaseId]??o,v=await this.deleteRemote(r,s,W,c,{epicHead:h,...a?{tip:a}:{},bundled:y!==void 0});v.reasonCode&&k.push(v.reasonCode);const _=W?.remotePush!==void 0&&!v.removed&&(v.reasonCode===i.REMOTE_UNVERIFIED||v.reasonCode===i.REMOTE_UNPRESERVED),N=this.now().toISOString(),T={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|${e.trigger}|${N}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:e.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:v.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:N};ae(T)||u("story-worktree-receipt-invalid"),await this.mutate(I=>{const w=oe(I),b=w.entries[r.leaseId];for((!b||b.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete w.entries[r.leaseId],w.cleanupReceipts.push({...T});w.cleanupReceipts.length>re;)w.cleanupReceipts.shift()},I=>{const w=I.records[r.leaseId];if(w)if(_&&w.remotePush!==void 0){const b=w.state==="removed"||w.state==="remove-pending"||w.state==="active"?w.bundleDigest?"bundled":"integrated":w.state,U={...w,state:b,updatedAt:N,remoteBranchRemoved:!1};delete U.claimToken,delete U.claimExpiresAt,I.records[r.leaseId]=U}else if(w.bundleDigest){const b={...w,state:"removed",updatedAt:N,remoteBranchRemoved:v.removed};delete b.claimToken,delete b.claimExpiresAt,I.records[r.leaseId]=b}else delete I.records[r.leaseId]}),R=!0;const X=m?{worktree:"enoent",branch:t.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:e.trigger,state:"removed",receipt:T,receiptDigest:ce(T),...y?{bundleDigest:y}:{},preservedReasonCodes:we(k),...X?{absenceProof:X}:{}}}finally{R||await this.releaseClaim(r,c).catch(()=>{})}}async recoverCreating(e,t){const{entry:r,facts:s}=e,n={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let o=!1;if(e.pathExists){const h=await S(r.worktreePath,["rev-parse","HEAD"]),a=await S(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),d=await S(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);e.registered&&h.ok&&h.stdout.trim()===r.baseSha&&a.ok&&a.stdout.trim()===r.temporaryBranch&&d.ok&&d.stdout.length===0||u(i.ORPHAN_UNPROVEN),o=!0}else e.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.branchCheckedOut&&u(i.ORPHAN_UNPROVEN);if(e.branchSha!==void 0&&e.branchSha!==r.baseSha&&u(i.ORPHAN_UNPROVEN),t)return{...n,outcome:"dry-run",state:"active",plannedActions:[...o?["remove-worktree"]:[],...e.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const f=await this.claim(r);let m=!1;try{o&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??he)&&u(i.REMOVE_PENDING),o&&await S(s.mainRoot,["worktree","prune"]);let h=!1;e.branchSha&&(h=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const a=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|creating|${a}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:o,localBranchRemoved:h,remoteBranchRemoved:!1,...e.branchSha&&!h?{preservedReasonCode:i.BRANCH_MOVED}:{},cleanedAt:a};return ae(d)||u("story-worktree-receipt-invalid"),await this.mutate(g=>{const E=oe(g),p=E.entries[r.leaseId];for((!p||p.state!=="creating"||p.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete E.entries[r.leaseId],E.cleanupReceipts.push({...d});E.cleanupReceipts.length>re;)E.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...n,outcome:"reclaimed",state:"removed",receipt:d,receiptDigest:ce(d),preservedReasonCodes:d.preservedReasonCode?[d.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,f).catch(()=>{})}}async closeDetachedRecord(e,t,r){let s,n=e.remoteBranchRemoved===!0;if(e.remotePush&&!n){const o=await S(t.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${e.epicId}^{commit}`]);if(!(o.ok&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",e.remotePush.sha,o.stdout.trim()])))s=i.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(t.mainRoot,e.remotePush);n=m.removed,s=m.reasonCode}}return r||s===i.REMOTE_UNPRESERVED||s===i.REMOTE_UNVERIFIED||await this.mutate(void 0,o=>{const f=o.records[e.leaseId];!f||f.state==="removed"||(f.bundleDigest?o.records[e.leaseId]={...f,state:"removed",remoteBranchRemoved:n,updatedAt:this.now().toISOString()}:delete o.records[e.leaseId])}),s}async deleteRemote(e,t,r,s,n){const o=r?.remotePush;if(!o)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(e.workspaceMechanism!=="client_managed_worktree"||o.branch!==e.temporaryBranch)return{removed:!1,reasonCode:i.ADOPTED_BRANCH};const f=await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.epicHead]),m=!f&&n.bundled&&n.tip!==void 0&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.tip]);if(!f&&!m)return{removed:!1,reasonCode:i.REMOTE_UNPRESERVED};const h=await this.deleteRecordedRemote(t.mainRoot,o);return h.removed&&await this.update(e,s,a=>({...a,remoteBranchRemoved:!0})),h}async deleteRecordedRemote(e,t){if(!await this.gitOk(e,["config","--get",`remote.${t.remote}.url`]))return{removed:!1,reasonCode:i.REMOTE_UNKNOWN};const r=await this.lsRemote(e,t.remote,t.branch);return r===null?{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:i.REMOTE_ABSENT}:r!==t.sha?{removed:!1,reasonCode:i.REMOTE_DIVERGED}:await this.gitOk(e,["push","--porcelain",`--force-with-lease=refs/heads/${t.branch}:${t.sha}`,t.remote,"--delete",`refs/heads/${t.branch}`])?await this.lsRemote(e,t.remote,t.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}}async lsRemote(e,t,r){const s=await S(e,["ls-remote","--heads",t,`refs/heads/${r}`]);if(!s.ok)return null;const n=s.stdout.split(`
1
+ import{createHash as ke,randomBytes as Z}from"node:crypto";import{existsSync as M}from"node:fs";import{chmod as _e,open as ee,readFile as B,readdir as te,rename as Ae,rm as V,stat as $,unlink as Se}from"node:fs/promises";import{hostname as Oe}from"node:os";import{join as A}from"node:path";import{GIT_LIFECYCLE_RUNTIME_DIRECTORY as F,STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as re,assertGitLifecyclePrivateFile as se,compactStoryWorktreeJournal as be,ensureGitLifecyclePrivateChildDirectory as De,ensureStoryWorktreeJournal as oe,gitLifecycleRuntimeDirectory as ne,isStoryWorktreeCleanupReceiptRecord as ae,mutateGitLifecycleRuntime as ie,readGitLifecycleRuntime as j}from"./git-lifecycle-store.js";import{GIT_LIFECYCLE_SETUP_BRANCH_STEP_ID as de}from"./git-lifecycle-step-ids.js";import{StoryWorktreeManager as Ne,digestStoryWorktreeReceiptLocal as ce,runStoryWorktreeGit as S,storyWorktreePathAbsence as Te}from"./story-worktree-manager.js";const G="story-worktree-cleanup.json",Y="story-worktree-bundles",Ce=256,le=Object.freeze(["success","failure","abandon","orphan-recovery"]),Pe=Object.freeze(["active","integrated","failed","abandoned","bundled","remove-pending","removed"]),Le=Object.freeze({MANUAL_PRESERVED:"manual-worktree-preserved",REMOVE_PENDING:"story-worktree-remove-pending",ORPHAN_RECOVERED:"story-worktree-orphan-recovered",ORPHAN_UNPROVEN:"story-worktree-orphan-unproven",OWNER_ALIVE:"story-worktree-owner-alive",LEASE_LIVE:"story-worktree-lease-live",CLAIMED:"story-worktree-cleanup-claimed",IN_PROGRESS:"story-worktree-cleanup-in-progress",DIRTY_PRESERVED:"story-worktree-dirty-preserved",BUNDLE_QUOTA:"story-worktree-bundle-quota-exceeded",BUNDLE_FAILED:"story-worktree-bundle-failed",BUNDLE_UNVERIFIED:"story-worktree-bundle-unverified",REMOTE_DIVERGED:"story-worktree-remote-sha-diverged",REMOTE_UNVERIFIED:"story-worktree-remote-unverified",REMOTE_ABSENT:"story-worktree-remote-absent",REMOTE_UNPRESERVED:"story-worktree-remote-unpreserved",REMOTE_UNKNOWN:"story-worktree-remote-unknown",BRANCH_MOVED:"story-worktree-branch-moved",BRANCH_CHECKED_OUT:"story-worktree-branch-checked-out",ADOPTED_BRANCH:"story-worktree-adopted-branch-preserved",ENTRY_CONFLICT:"story-worktree-entry-conflict",STATE_INVALID:"story-worktree-cleanup-state-invalid",SWEEP_FAILED:"story-worktree-sweep-failed",ORPHAN_PROGRESS_RESET:"story-worktree-orphan-progress-reset",ORPHAN_PROGRESS_PRESERVED:"story-worktree-orphan-progress-preserved"}),i=Le,ue=10080*60*1e3,Me=600*1e3,Be=64,Ve=512*1024*1024,he=3,Ue=50,xe=/^swt-[a-f0-9]{24}$/,K=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,fe=/^[a-f0-9]{64}$/,We=/^[a-f0-9]{16}$/,me=/^P[1-9][0-9]*$/,He=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,pe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,Ee=/^nx\/P[1-9][0-9]*\/[a-f0-9]{8}$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/,Re=/^swt-[a-f0-9]{24}-[a-f0-9]{12}\.bundle$/,z=["integrated","failed","abandoned","bundled","remove-pending"],Fe="last_step,status,steps_completed",je=new Set(["backlog","ready_to_start"]);function Ge(l){const{runtime:e,epicId:t,storyId:r}=l,s=O(e.stories[r]),n=s?Object.keys(s).filter(p=>p!=="write_set_extension").sort():[];if(n.length===0)return"none";const o=s.steps_completed;if(!(n.join(",")===Fe&&s.status==="branch-ready"&&s.last_step===de&&Array.isArray(o)&&o.length===1&&o[0]===de)||!l.loss.worktreeAbsent||!l.loss.branchGone||l.loss.bundled||Object.values(e.storyWorktrees?.entries??{}).some(p=>p.storyId===r&&p.leaseId!==l.recoveredLeaseId))return"preserved";let h;try{h=l.trackedText===void 0?void 0:O(JSON.parse(l.trackedText))}catch{return"preserved"}const a=O(h?.stories),d=O(a?.[r]),g=d?.steps_completed;if(!d||!je.has(String(d.status))||g!==void 0&&(!Array.isArray(g)||g.length>0)||d.branch_name||d.checkpoint||d.commit_sha)return"preserved";const E=O(O(e.epics[t])?.story_worktree_evidence);if(E!==void 0){const p=E.receipts,D=E.specAcceptances;if(p!==void 0&&!Array.isArray(p)||D!==void 0&&!Array.isArray(D))return"preserved";const c=R=>{const y=O(R);return y?.kind==="story-worktree-lease"?!1:!y||y.storyId===r||Array.isArray(y.storyIds)&&y.storyIds.includes(r)};if(p?.some(c)||D?.some(c))return"preserved"}return"reset"}class H extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function u(l){throw new H(l)}function x(l){return ke("sha256").update(l).digest("hex")}function q(l){return new Promise(e=>setTimeout(e,l))}function we(l){return[...new Set(l)]}function Ye(l){try{return process.kill(l,0),!0}catch(e){return e.code==="EPERM"}}function J(l,e){return`${l}-${e.slice(0,12)}.bundle`}function ge(l=Oe()){return x(`neocortex.p225.owner-host|${l}`)}function O(l){return l!==null&&typeof l=="object"&&!Array.isArray(l)?l:void 0}const ye=["schemaVersion","leaseId","epicId","storyId","state","removeAttempts","updatedAt"],Ke=new Set([...ye,"trigger","headSha","bundleDigest","bundleBytes","bundleExpiresAt","remotePush","remoteBranchRemoved","ownerPid","ownerHostDigest","claimToken","claimExpiresAt"]);function Ie(l,e){const t=O(e);if(!t||Object.keys(t).some(n=>!Ke.has(n))||ye.some(n=>t[n]===void 0))return!1;const r=t.remotePush===void 0?void 0:O(t.remotePush);if(t.remotePush!==void 0&&(!r||Object.keys(r).length!==3||typeof r.remote!="string"||!pe.test(r.remote)||typeof r.branch!="string"||!Ee.test(r.branch)||!r.branch.startsWith(`nx/${String(t.epicId)}/`)||typeof r.sha!="string"||!K.test(r.sha)))return!1;const s=n=>t[n]===void 0||typeof t[n]=="string"&&$e.test(t[n])&&Number.isFinite(Date.parse(t[n]));return t.schemaVersion===1&&t.leaseId===l&&xe.test(l)&&typeof t.epicId=="string"&&me.test(t.epicId)&&typeof t.storyId=="string"&&He.test(t.storyId)&&t.storyId.startsWith(`${t.epicId}.`)&&Pe.includes(t.state)&&Number.isSafeInteger(t.removeAttempts)&&t.removeAttempts>=0&&t.removeAttempts<=1e3&&s("updatedAt")&&s("bundleExpiresAt")&&s("claimExpiresAt")&&t.claimToken===void 0==(t.claimExpiresAt===void 0)&&(t.claimToken===void 0||typeof t.claimToken=="string"&&We.test(t.claimToken))&&(t.trigger===void 0||le.includes(t.trigger))&&(t.headSha===void 0||typeof t.headSha=="string"&&K.test(t.headSha))&&(t.bundleDigest===void 0||typeof t.bundleDigest=="string"&&fe.test(t.bundleDigest)&&t.headSha!==void 0&&t.bundleExpiresAt!==void 0)&&(t.bundleBytes===void 0||Number.isSafeInteger(t.bundleBytes)&&t.bundleBytes>0)&&(t.remoteBranchRemoved===void 0||typeof t.remoteBranchRemoved=="boolean")&&(t.ownerPid===void 0||Number.isSafeInteger(t.ownerPid)&&t.ownerPid>0)&&(t.ownerHostDigest===void 0||typeof t.ownerHostDigest=="string"&&fe.test(t.ownerHostDigest))}function Q(l){let e;try{e=JSON.parse(l)}catch{u(i.STATE_INVALID)}const t=O(e),r=O(t?.records);return(!t||Object.keys(t).length!==2||t.schemaVersion!==1||!r||Object.keys(r).length>Ce||!Object.entries(r).every(([s,n])=>Ie(s,n)))&&u(i.STATE_INVALID),{schemaVersion:1,records:r}}async function ve(l){const e=A(l,F),t=A(e,G);if(!M(t))return{schemaVersion:1,records:{}};try{await se(t,e)}catch{u(i.STATE_INVALID)}return Q(await B(t,"utf8"))}function P(l,e){return l?.claimToken!==void 0&&l.claimExpiresAt!==void 0&&Date.parse(l.claimExpiresAt)>e}async function at(l,e,t=Date.now()){try{const r=(await ve(l)).records[e];return r!==void 0&&(z.includes(r.state)||P(r,t))}catch{return!0}}class ze{options;manager;now;isProcessAlive;constructor(e){this.options=e,this.manager=e.manager??new Ne({projectRoot:e.projectRoot,...e.worktreeRoot?{worktreeRoot:e.worktreeRoot}:{},...e.now?{now:e.now}:{}}),this.now=e.now??(()=>new Date),this.isProcessAlive=e.isProcessAlive??Ye}async readState(e){return ve(e?.commonDir??(await this.facts()).commonDir)}async recordPush(e){return this.guard(async()=>{(typeof e.remote!="string"||!pe.test(e.remote))&&u("story-worktree-remote-invalid");const t=await this.probe(e.leaseId);(t.ownership!=="proven"||!t.headSha)&&u("story-worktree-ownership-unproven"),(t.entry.workspaceMechanism!=="client_managed_worktree"||!Ee.test(t.entry.temporaryBranch))&&u(i.ADOPTED_BRANCH),await this.gitOk(t.facts.mainRoot,["config","--get",`remote.${e.remote}.url`])||u(i.REMOTE_UNKNOWN);const r=await this.lsRemote(t.facts.mainRoot,e.remote,t.entry.temporaryBranch);r===null&&u(i.REMOTE_UNVERIFIED),r===void 0&&u(i.REMOTE_ABSENT),r!==t.headSha&&u(i.REMOTE_DIVERGED);const s={remote:e.remote,branch:t.entry.temporaryBranch,sha:r};return await this.update(t.entry,void 0,n=>{const o={...n,remotePush:s};return delete o.remoteBranchRemoved,o}),{ok:!0,value:{leaseId:t.entry.leaseId,...s}}})}async registerOwnerProcess(e){return this.guard(async()=>{(!Number.isSafeInteger(e.pid)||e.pid<=0)&&u("story-worktree-owner-pid-invalid");const t=await this.probe(e.leaseId);return await this.update(t.entry,void 0,r=>({...r,ownerPid:e.pid,ownerHostDigest:ge()})),{ok:!0,value:{leaseId:t.entry.leaseId}}})}async cleanup(e){return this.guard(async()=>({ok:!0,value:await this.cleanupUnguarded(e)}))}async sweep(e={}){return this.guard(async()=>{e.epicId!==void 0&&!me.test(e.epicId)&&u("story-worktree-identity-invalid");const t=e.dryRun===!0,r=await this.facts(),s=await j(this.options.projectRoot),n=Object.values(s.storyWorktrees?.entries??{}),o=n.filter(c=>e.epicId===void 0||c.epicId===e.epicId).sort((c,R)=>c.leaseId.localeCompare(R.leaseId)),f=await this.readState(r),m=this.now().getTime(),h=ge(),a=[],d=[];for(const c of o){const R=f.records[c.leaseId],y=R!==void 0&&z.includes(R.state),C=Date.parse(c.expiresAt)<=m,k=R?.ownerPid!==void 0&&R.ownerHostDigest===h&&this.isProcessAlive(R.ownerPid),L=!k&&!P(R,m)&&!y&&!C&&c.state==="active"&&await Te(c.worktreePath)==="enoent";if(!L&&(k||P(R,m)||!y&&!C)){const T=k?i.OWNER_ALIVE:P(R,m)?i.CLAIMED:i.LEASE_LIVE;a.push({leaseId:c.leaseId,action:"skipped",reasonCode:T});continue}const W=y?R?.trigger==="success"&&C?"orphan-recovery":R?.trigger??"orphan-recovery":"orphan-recovery";let v;try{v={ok:!0,value:await this.cleanupUnguarded({leaseId:c.leaseId,trigger:W,dryRun:t,...L?{requireVanished:!0}:{}})}}catch(T){v={ok:!1,reasonCode:T instanceof H?T.reasonCode:i.SWEEP_FAILED}}if(!v.ok&&L&&v.reasonCode===i.LEASE_LIVE){a.push({leaseId:c.leaseId,action:"skipped",reasonCode:i.LEASE_LIVE});continue}if(!v.ok){a.push({leaseId:c.leaseId,action:"preserved",reasonCode:v.reasonCode}),d.push(v.reasonCode);continue}const _=v.value,N=await this.reconcileOrphanProgress(c,_,r,t);_.outcome==="dry-run"?a.push({leaseId:c.leaseId,action:"planned",plannedActions:_.plannedActions??[]}):_.outcome==="remove-pending"?(a.push({leaseId:c.leaseId,action:"remove-pending",reasonCode:i.REMOVE_PENDING,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{}}),d.push(i.REMOVE_PENDING)):(a.push({leaseId:c.leaseId,action:"recovered",reasonCode:i.ORPHAN_RECOVERED,..._.bundleDigest?{bundleDigest:_.bundleDigest}:{},..._.absenceProof?{absenceProof:_.absenceProof}:{}}),d.push(i.ORPHAN_RECOVERED)),N&&(a.push(N),N.reasonCode&&d.push(N.reasonCode))}const g=new Set(n.map(c=>c.leaseId));for(const c of Object.values(f.records).sort((R,y)=>R.leaseId.localeCompare(y.leaseId))){if(g.has(c.leaseId)||c.state==="removed"||P(c,m)||e.epicId!==void 0&&c.epicId!==e.epicId)continue;const R=await this.closeDetachedRecord(c,r,t);a.push({leaseId:c.leaseId,action:t?"planned":"record-closed",...R?{reasonCode:R}:{}}),R&&d.push(R)}const E=await this.expireBundles(f,r,m,t),p=await this.manager.registeredWorktrees();p.ok||u(p.reasonCode);const D=p.value.worktrees.filter(c=>!n.some(R=>this.manager.sameWorktreePath(R.worktreePath,c.path))).length;return D>0&&d.push(i.MANUAL_PRESERVED),{ok:!0,value:{dryRun:t,entriesScanned:o.length,recovered:a.filter(c=>c.action==="recovered").length,removePending:a.filter(c=>c.action==="remove-pending").length,preserved:a.filter(c=>c.action==="preserved").length,skipped:a.filter(c=>c.action==="skipped").length,manualWorktreesPreserved:D,bundlesExpired:E,items:a,reasonCodes:we(d)}}})}async cleanupUnguarded(e){le.includes(e.trigger)||u("story-worktree-trigger-invalid");const t=await this.probe(e.leaseId),{entry:r,facts:s}=t;e.requireVanished===!0&&(t.pathAbsence!=="enoent"||r.state!=="active")&&u(i.LEASE_LIVE);const o=(await this.readState(s)).records[r.leaseId];if(r.state==="creating")return e.trigger!=="orphan-recovery"&&u("story-worktree-ownership-unproven"),this.recoverCreating(t,e.dryRun===!0);const f=o!==void 0&&z.includes(o.state);let m=!1;t.pathExists||(t.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.trigger!=="orphan-recovery"&&!f&&u("story-worktree-ownership-unproven"),m=!0),!m&&t.ownership!=="proven"&&u("story-worktree-ownership-unproven"),!m&&t.clean!==!0&&u(e.trigger==="success"?"story-worktree-dirty":i.DIRTY_PRESERVED),t.epicHead||u("story-worktree-epic-branch-missing");const h=t.epicHead,a=m?t.branchSha:t.headSha;!m&&!a&&u("story-worktree-git-failed");const d=t.integrated===!0;e.trigger==="success"&&!d&&u("story-worktree-not-integrated");const g=r.workspaceMechanism==="client_managed_worktree",E=o?.bundleDigest!==void 0&&o.headSha!==void 0&&o.headSha===a&&await this.bundleMatches(s,r.leaseId,o.headSha,o.bundleDigest),p=!d&&a!==void 0&&(g||e.trigger==="orphan-recovery")&&!E,D=o?.remotePush!==void 0&&o.remoteBranchRemoved!==!0;if(e.dryRun===!0){const y=[...p?["bundle-unintegrated-range"]:[],m?"drop-worktree-metadata":"remove-worktree",...g&&t.branchSha?["delete-local-branch"]:[],...D?["delete-remote-branch"]:[]];return{leaseId:r.leaseId,outcome:"dry-run",trigger:e.trigger,state:o?.state??"active",plannedActions:y,preservedReasonCodes:[]}}const c=await this.claim(r);let R=!1;try{let y=E?o?.bundleDigest:void 0;if(p){const I=await this.createBundle(t,a,h);y=I.digest,await this.update(r,c,w=>({...w,state:"bundled",trigger:e.trigger,headSha:a,bundleDigest:I.digest,bundleBytes:I.bytes,bundleExpiresAt:new Date(this.now().getTime()+(this.options.bundleTtlMs??ue)).toISOString()}))}else if(!E){const I=d?"integrated":e.trigger==="failure"?"failed":"abandoned";await this.update(r,c,w=>({...w,state:w.state==="remove-pending"?"remove-pending":I,trigger:e.trigger,...a?{headSha:a}:{}}))}if(m)await S(s.mainRoot,["worktree","remove",r.worktreePath]);else{const I=this.options.removeAttempts??he;if(!await this.removeWithRetry(s.mainRoot,r.worktreePath,I))return await this.update(r,c,w=>({...w,state:"remove-pending",trigger:e.trigger,removeAttempts:Math.min(1e3,w.removeAttempts+I)})),{leaseId:r.leaseId,outcome:"remove-pending",trigger:e.trigger,state:"remove-pending",...y?{bundleDigest:y}:{},preservedReasonCodes:[i.REMOVE_PENDING]}}await S(s.mainRoot,["worktree","prune"]);const C=await this.manager.registeredWorktrees();C.ok||u(C.reasonCode),C.value.worktrees.some(I=>this.manager.sameWorktreePath(I.path,r.worktreePath))&&u(i.ORPHAN_UNPROVEN);const k=[];let L=!1;if(!g)k.push(i.ADOPTED_BRANCH);else if(t.branchSha){const I=a??t.branchSha,w=d||y!==void 0,b=C.value.worktrees.some(U=>U.branch===r.temporaryBranch);w?b?k.push(i.BRANCH_CHECKED_OUT):await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,I])?L=!0:k.push(i.BRANCH_MOVED):k.push(i.ORPHAN_UNPROVEN)}const W=(await this.readState(s)).records[r.leaseId]??o,v=await this.deleteRemote(r,s,W,c,{epicHead:h,...a?{tip:a}:{},bundled:y!==void 0});v.reasonCode&&k.push(v.reasonCode);const _=W?.remotePush!==void 0&&!v.removed&&(v.reasonCode===i.REMOTE_UNVERIFIED||v.reasonCode===i.REMOTE_UNPRESERVED),N=this.now().toISOString(),T={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|${e.trigger}|${N}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:e.trigger,worktreeRemoved:!0,localBranchRemoved:L,remoteBranchRemoved:v.removed,...k[0]?{preservedReasonCode:k[0]}:{},cleanedAt:N};ae(T)||u("story-worktree-receipt-invalid"),await this.mutate(I=>{const w=oe(I),b=w.entries[r.leaseId];for((!b||b.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete w.entries[r.leaseId],w.cleanupReceipts.push({...T});w.cleanupReceipts.length>re;)w.cleanupReceipts.shift()},I=>{const w=I.records[r.leaseId];if(w)if(_&&w.remotePush!==void 0){const b=w.state==="removed"||w.state==="remove-pending"||w.state==="active"?w.bundleDigest?"bundled":"integrated":w.state,U={...w,state:b,updatedAt:N,remoteBranchRemoved:!1};delete U.claimToken,delete U.claimExpiresAt,I.records[r.leaseId]=U}else if(w.bundleDigest){const b={...w,state:"removed",updatedAt:N,remoteBranchRemoved:v.removed};delete b.claimToken,delete b.claimExpiresAt,I.records[r.leaseId]=b}else delete I.records[r.leaseId]}),R=!0;const X=m?{worktree:"enoent",branch:t.branchSha?"present":await this.branchAbsence(s,r.temporaryBranch),bundled:y!==void 0}:void 0;return{leaseId:r.leaseId,outcome:"removed",trigger:e.trigger,state:"removed",receipt:T,receiptDigest:ce(T),...y?{bundleDigest:y}:{},preservedReasonCodes:we(k),...X?{absenceProof:X}:{}}}finally{R||await this.releaseClaim(r,c).catch(()=>{})}}async recoverCreating(e,t){const{entry:r,facts:s}=e,n={leaseId:r.leaseId,trigger:"orphan-recovery",preservedReasonCodes:[]};let o=!1;if(e.pathExists){const h=await S(r.worktreePath,["rev-parse","HEAD"]),a=await S(r.worktreePath,["symbolic-ref","--quiet","--short","HEAD"]),d=await S(r.worktreePath,["status","--porcelain=v1","--untracked-files=all","-z"]);e.registered&&h.ok&&h.stdout.trim()===r.baseSha&&a.ok&&a.stdout.trim()===r.temporaryBranch&&d.ok&&d.stdout.length===0||u(i.ORPHAN_UNPROVEN),o=!0}else e.pathAbsence!=="enoent"&&u(i.ORPHAN_UNPROVEN),e.branchCheckedOut&&u(i.ORPHAN_UNPROVEN);if(e.branchSha!==void 0&&e.branchSha!==r.baseSha&&u(i.ORPHAN_UNPROVEN),t)return{...n,outcome:"dry-run",state:"active",plannedActions:[...o?["remove-worktree"]:[],...e.branchSha?["delete-local-branch"]:[],"drop-reservation"]};const f=await this.claim(r);let m=!1;try{o&&!await this.removeWithRetry(s.mainRoot,r.worktreePath,this.options.removeAttempts??he)&&u(i.REMOVE_PENDING),o&&await S(s.mainRoot,["worktree","prune"]);let h=!1;e.branchSha&&(h=await this.gitOk(s.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]));const a=this.now().toISOString(),d={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${r.leaseId}|${r.nonceDigest}|creating|${a}`).slice(0,24)}`,epicId:r.epicId,storyId:r.storyId,leaseId:r.leaseId,trigger:"orphan-recovery",worktreeRemoved:o,localBranchRemoved:h,remoteBranchRemoved:!1,...e.branchSha&&!h?{preservedReasonCode:i.BRANCH_MOVED}:{},cleanedAt:a};return ae(d)||u("story-worktree-receipt-invalid"),await this.mutate(g=>{const E=oe(g),p=E.entries[r.leaseId];for((!p||p.state!=="creating"||p.nonceDigest!==r.nonceDigest)&&u(i.ENTRY_CONFLICT),delete E.entries[r.leaseId],E.cleanupReceipts.push({...d});E.cleanupReceipts.length>re;)E.cleanupReceipts.shift()},g=>{delete g.records[r.leaseId]}),m=!0,{...n,outcome:"reclaimed",state:"removed",receipt:d,receiptDigest:ce(d),preservedReasonCodes:d.preservedReasonCode?[d.preservedReasonCode]:[]}}finally{m||await this.releaseClaim(r,f).catch(()=>{})}}async closeDetachedRecord(e,t,r){let s,n=e.remoteBranchRemoved===!0;if(e.remotePush&&!n){const o=await S(t.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/epic/${e.epicId}^{commit}`]);if(!(o.ok&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",e.remotePush.sha,o.stdout.trim()])))s=i.REMOTE_UNPRESERVED;else if(!r){const m=await this.deleteRecordedRemote(t.mainRoot,e.remotePush);n=m.removed,s=m.reasonCode}}return r||s===i.REMOTE_UNPRESERVED||s===i.REMOTE_UNVERIFIED||await this.mutate(void 0,o=>{const f=o.records[e.leaseId];!f||f.state==="removed"||(f.bundleDigest?o.records[e.leaseId]={...f,state:"removed",remoteBranchRemoved:n,updatedAt:this.now().toISOString()}:delete o.records[e.leaseId])}),s}async deleteRemote(e,t,r,s,n){const o=r?.remotePush;if(!o)return{removed:!1};if(r?.remoteBranchRemoved===!0)return{removed:!0};if(e.workspaceMechanism!=="client_managed_worktree"||o.branch!==e.temporaryBranch)return{removed:!1,reasonCode:i.ADOPTED_BRANCH};const f=await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.epicHead]),m=!f&&n.bundled&&n.tip!==void 0&&await this.gitOk(t.mainRoot,["merge-base","--is-ancestor",o.sha,n.tip]);if(!f&&!m)return{removed:!1,reasonCode:i.REMOTE_UNPRESERVED};const h=await this.deleteRecordedRemote(t.mainRoot,o);return h.removed&&await this.update(e,s,a=>({...a,remoteBranchRemoved:!0})),h}async deleteRecordedRemote(e,t){if(!await this.gitOk(e,["config","--get",`remote.${t.remote}.url`]))return{removed:!1,reasonCode:i.REMOTE_UNKNOWN};const r=await this.lsRemote(e,t.remote,t.branch);return r===null?{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:r===void 0?{removed:!1,reasonCode:i.REMOTE_ABSENT}:r!==t.sha?{removed:!1,reasonCode:i.REMOTE_DIVERGED}:await this.gitOk(e,["push","--porcelain",`--force-with-lease=refs/heads/${t.branch}:${t.sha}`,t.remote,"--delete",`refs/heads/${t.branch}`])?await this.lsRemote(e,t.remote,t.branch)===void 0?{removed:!0}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}:{removed:!1,reasonCode:i.REMOTE_UNVERIFIED}}async lsRemote(e,t,r){const s=await S(e,["ls-remote","--heads",t,`refs/heads/${r}`]);if(!s.ok)return null;const n=s.stdout.split(`
2
2
  `).map(f=>f.trim()).find(f=>f.endsWith(` refs/heads/${r}`));if(!n)return;const o=n.split(" ")[0]??"";return K.test(o)?o:null}async createBundle(e,t,r){const{entry:s,facts:n}=e,o=await De(await ne(this.options.projectRoot),Y),f=J(s.leaseId,t),h=(await te(o)).filter(c=>Re.test(c)).filter(c=>c!==f);h.length>=(this.options.maxBundles??Be)&&u(i.BUNDLE_QUOTA);let a=0;for(const c of h)a+=(await $(A(o,c))).size;const d=A(o,f);await V(d,{force:!0});const g=`refs/heads/${s.temporaryBranch}`;await this.gitOk(n.mainRoot,["bundle","create",d,g,`^${r}`])||(await V(d,{force:!0}),u(i.BUNDLE_FAILED)),process.platform!=="win32"&&await _e(d,384);const E=(await $(d)).size;a+E>(this.options.maxBundleBytes??Ve)&&(await V(d,{force:!0}),u(i.BUNDLE_QUOTA));const p=await S(n.mainRoot,["bundle","list-heads",d]);return(!await this.gitOk(n.mainRoot,["bundle","verify","--quiet",d])||!p.ok||!p.stdout.split(`
3
3
  `).some(c=>c.trim()===`${t} ${g}`))&&(await V(d,{force:!0}),u(i.BUNDLE_UNVERIFIED)),{digest:x(await B(d)),bytes:E}}async bundleMatches(e,t,r,s){try{const n=A(e.commonDir,F,Y,J(t,r));return x(await B(n))===s}catch{return!1}}async expireBundles(e,t,r,s){const n=A(t.commonDir,F,Y),o=Object.values(e.records).filter(a=>a.state==="removed"&&a.bundleExpiresAt!==void 0&&Date.parse(a.bundleExpiresAt)<=r),f=new Set(Object.values(e.records).filter(a=>a.bundleDigest!==void 0&&a.headSha!==void 0&&!o.some(d=>d.leaseId===a.leaseId)).map(a=>J(a.leaseId,a.headSha))),m=this.options.bundleTtlMs??ue,h=[];if(M(n))for(const a of(await te(n)).filter(d=>Re.test(d)&&!f.has(d))){const d=a.slice(0,28),g=e.records[d];(o.some(E=>E.leaseId===d)||!g&&r-(await $(A(n,a))).mtimeMs>=m)&&h.push(a)}if(s||h.length===0&&o.length===0)return h.length;await this.mutate(void 0,a=>{for(const d of o){const g=a.records[d.leaseId];g?.state==="removed"&&g.bundleExpiresAt===d.bundleExpiresAt&&delete a.records[d.leaseId]}});for(const a of h)await V(A(n,a),{force:!0});return h.length}async reconcileOrphanProgress(e,t,r,s){let n;if(t.outcome==="dry-run"){const h=t.plannedActions??[];if(!h.includes("drop-worktree-metadata"))return;const a=await this.branchAbsence(r,e.temporaryBranch);n={worktreeAbsent:!0,bundled:h.includes("bundle-unintegrated-range"),branchGone:a==="absent"||a==="present"&&h.includes("delete-local-branch")}}else{const h=t.absenceProof;if(t.outcome!=="removed"||!h)return;n={worktreeAbsent:h.worktree==="enoent",bundled:h.bundled,branchGone:h.branch==="absent"||h.branch==="present"&&t.receipt?.localBranchRemoved===!0}}const o={leaseId:e.leaseId,storyId:e.storyId},f={...o,action:"progress-preserved",reasonCode:i.ORPHAN_PROGRESS_PRESERVED},m=A(this.options.projectRoot,".neocortex","state.json");for(let h=1;h<=3;h++){let a,d;try{a=await j(this.options.projectRoot),d=M(m)?await B(m,"utf8"):void 0}catch{return f}const g=Ge({runtime:a,trackedText:d,epicId:e.epicId,storyId:e.storyId,recoveredLeaseId:e.leaseId,loss:n});if(g==="none")return;if(g==="preserved")return f;if(s)return{...o,action:"planned",reasonCode:i.ORPHAN_PROGRESS_RESET,plannedActions:["reset-story-phase-1-progress"]};try{return await ie(this.options.projectRoot,E=>{const p=E.stories[e.storyId];if(!p)throw new Error("git-lifecycle-runtime-revision-conflict");delete p.status,delete p.last_step,delete p.steps_completed,Object.keys(p).length===0&&delete E.stories[e.storyId]},{expectedRevision:a.revision,preCommit:async()=>{if((M(m)?await B(m,"utf8"):void 0)!==d)throw new Error("git-lifecycle-runtime-revision-conflict")}}),{...o,action:"progress-reset",reasonCode:i.ORPHAN_PROGRESS_RESET}}catch(E){if(!(E instanceof Error&&E.message==="git-lifecycle-runtime-revision-conflict"))return f}}return f}async branchAbsence(e,t){const r=await S(e.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${t}`]);return r.ok?"present":r.exitCode===1?"absent":"unknown"}async removeWithRetry(e,t,r){const s=this.options.removeWorktree??((o,f)=>this.gitOk(o,["worktree","remove",f])),n=this.options.removeDelayMs??Ue;for(let o=1;o<=r;o++){if(await s(e,t))return!0;o<r&&await q(n*o)}return!1}async probe(e){const t=await this.manager.probe(e);return t.ok||u(t.reasonCode),t.value}async facts(){const e=await this.manager.registeredWorktrees();return e.ok||u(e.reasonCode),e.value.facts}async gitOk(e,t){return(await S(e,t)).ok}async claim(e){const t=Z(8).toString("hex");return await this.mutate(r=>{const s=r.storyWorktrees?.entries[e.leaseId];(!s||s.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},r=>{const s=this.now().getTime(),n=r.records[e.leaseId]??this.emptyRecord(e);P(n,s)&&u(i.CLAIMED),r.records[e.leaseId]={...n,claimToken:t,claimExpiresAt:new Date(s+(this.options.claimTtlMs??Me)).toISOString(),updatedAt:new Date(s).toISOString()}}),t}async releaseClaim(e,t){await this.mutate(void 0,r=>{const s=r.records[e.leaseId];if(!s||s.claimToken!==t)return;const n={...s};delete n.claimToken,delete n.claimExpiresAt,s.state!=="active"||s.remotePush!==void 0||s.ownerPid!==void 0||s.bundleDigest!==void 0||s.removeAttempts>0?r.records[e.leaseId]=n:delete r.records[e.leaseId]})}emptyRecord(e){return{schemaVersion:1,leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,state:"active",removeAttempts:0,updatedAt:this.now().toISOString()}}async update(e,t,r){await this.mutate(s=>{const n=s.storyWorktrees?.entries[e.leaseId];(!n||n.nonceDigest!==e.nonceDigest)&&u(i.ENTRY_CONFLICT)},s=>{const n=s.records[e.leaseId]??this.emptyRecord(e);P(n,this.now().getTime())&&n.claimToken!==t&&u(i.CLAIMED);const o={...r(n),updatedAt:this.now().toISOString()};Ie(e.leaseId,o)||u(i.STATE_INVALID),s.records[e.leaseId]=o})}async mutate(e,t){const r=this.options.lockRetry?.attempts??40,s=this.options.lockRetry?.delayMs??25;for(let n=1;;n++)try{await ie(this.options.projectRoot,o=>{e?.(o),be(o)},{preCommit:async()=>{const o=await ne(this.options.projectRoot),f=A(o,G);let m={schemaVersion:1,records:{}};if(M(f)&&(await se(f,o),m={schemaVersion:1,records:{...Q(await B(f,"utf8")).records}}),t(m),Object.keys(m.records).length===0){M(f)&&await Se(f);return}const h=`${JSON.stringify(m,null,2)}
4
4
  `;Q(h),await qe(o,G,h)}});return}catch(o){if(!(o instanceof Error&&(o.message==="git-lifecycle-runtime-lock-active"||o.code==="ENOENT"&&o.message.includes("runtime.lock")))||n>=r)throw o;await q(s*Math.min(n,8)+Math.floor(Math.random()*s))}}async guard(e){try{return await e()}catch(t){if(t instanceof H)return{ok:!1,reasonCode:t.reasonCode};const r=t instanceof Error?t.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(r)?{ok:!1,reasonCode:r}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}}async function qe(l,e,t){const r=A(l,`.${e}.${Z(6).toString("hex")}.tmp`),s=await ee(r,"wx",384);try{await s.writeFile(t,"utf8"),await s.sync()}finally{await s.close()}try{await Ae(r,A(l,e))}catch(n){throw await V(r,{force:!0}),n}try{const n=await ee(l,"r");try{await n.sync()}finally{await n.close()}}catch(n){if(process.platform!=="win32")throw n}}const Je=new Set([i.MANUAL_PRESERVED]);async function Qe(l,e={}){let t;try{const s=await j(l);if(t=new ze({...e,projectRoot:l}),!(Object.keys(s.storyWorktrees?.entries??{}).length>0)&&Object.keys((await t.readState()).records).length===0)return{reasonCodes:[]}}catch(s){return{reasonCodes:s instanceof H?[s.reasonCode]:[]}}const r=await t.sweep({...e.epicId?{epicId:e.epicId}:{},...e.dryRun?{dryRun:!0}:{}});return r.ok?{reasonCodes:r.value.reasonCodes.filter(s=>!Je.has(s)),value:r.value}:{reasonCodes:[r.reasonCode]}}function it(l,e=r=>Qe(r),t=r=>{process.kill(process.pid,r)}){let r=!1;const s=o=>{r||(r=!0,n(),Promise.race([e(l),q(25e3)]).catch(()=>{}).finally(()=>t(o)))},n=()=>{process.removeListener("SIGINT",s),process.removeListener("SIGTERM",s)};return process.once("SIGINT",s),process.once("SIGTERM",s),n}export{Y as STORY_WORKTREE_BUNDLE_DIRECTORY,G as STORY_WORKTREE_CLEANUP_FILE,Ce as STORY_WORKTREE_CLEANUP_MAX_RECORDS,Le as STORY_WORKTREE_CLEANUP_REASON_CODES,Pe as STORY_WORKTREE_CLEANUP_STATES,le as STORY_WORKTREE_CLEANUP_TRIGGERS,ze as StoryWorktreeCleanup,Ge as classifyStoryWorktreeOrphanProgress,it as installStoryWorktreeSignalSweep,Ie as isStoryWorktreeCleanupRecord,Q as parseStoryWorktreeCleanupDocument,J as storyWorktreeBundleFileName,at as storyWorktreeCleanupInProgress,ge as storyWorktreeOwnerHostDigest,Qe as sweepStoryWorktreeOrphans};
@@ -1,3 +1,3 @@
1
- import{execFile as Qe}from"node:child_process";import{createHash as ut}from"node:crypto";import{readFile as mt,realpath as Ae}from"node:fs/promises";import{join as kt,resolve as Ee}from"node:path";import{yoloopDomainHash as It}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as Ze,directYoloCommitIdempotencyKey as et,directYoloWaveQaCoverage as vt,finalizeDirectYoloStoryCheckpoint as St,persistDirectYoloWaveStoryCheckpoint as bt,pushDirectYoloWaveHead as At,resolveDirectYoloIntegrationAuthority as tt,runDirectYoloWaveP205 as Et,validateDirectYoloWriteSet as Rt}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Ne,appendStoryWorktreeEvidence as xt,applyGitLifecycleRuntimeOverlay as _t,ensureRuntimeEpic as Re,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as pe,publicStoryReviewArtifactFromBytes as Ct,publicStoryReviewArtifactFromGit as Dt,readGitLifecycleRuntime as V,readStoryWorktreeEvidence as rt,releaseGitLifecyclePhysicalIntegrationLock as Me,verifyGitLifecyclePhysicalIntegrationLock as ot}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ot,STATE_JSON_FIELD_MERGE_MAX_BYTES as Pt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as it,GOVERNANCE_REASON_CODES as ce,readStoryGovernanceSync as Ht,storyReviewGovernancePath as Bt}from"./governance-runtime-store.js";import{StoryWorktreeManager as xe}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Nt}from"../private-execution/root-memory-git-evidence.js";const Mt="neocortex.p225.story-worktree-receipt.v1",Wt=200,ue="Neocortex-Story-Worktree-Tip",nt=3e4,de=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,zt=/^swt-[a-f0-9]{24}$/,_e=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class Te extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function o(e){throw new Te(e)}const at=32*1024*1024;function O(e,t,a){return new Promise(s=>{Qe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:at,timeout:nt,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(r,g)=>{const n=r?typeof r.code=="number"?r.code:128:0;s({code:n,stdout:String(g??"")})})})}function st(e,t,a){return new Promise(s=>{const r=Qe("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:at,timeout:nt,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(g,n)=>{const f=g?typeof g.code=="number"?g.code:128:0;s({code:f,stdout:String(n??"")})});r.stdin?.on("error",()=>{}),r.stdin?.end(a)})}async function h(e,t,a,s){const r=await O(e,t,s);return r.code!==0&&o(a),r.stdout.trim()}async function T(e,t){return(await O(e,t)).code===0}function fe(e){return ut("sha256").update(e).digest("hex")}function ct(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 $(e,t){const a=`${t}: `,s=e.split(`
2
- `).map(r=>r.trim()).filter(r=>r.startsWith(a));return s.length===1?s[0].slice(a.length):void 0}function We(e){return It(Mt,e)}function X(e,t){return(rt(e,t)?.receipts??[]).filter(Tt)}function me(e){const t=[...e].sort((a,s)=>a.integrationIndex-s.integrationIndex);t.forEach((a,s)=>{(a.integrationIndex!==s+1||s>0&&a.epicHeadBeforeSha!==t[s-1].epicHeadAfterSha)&&o("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((s,r)=>r.integrationIndex-s.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&o("story-worktree-integration-chain-invalid")}const jt=new Set(["done","merged","completed","released"]);function dt(e,t,a,s,r,g=new Set){(rt(e,a)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===s||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(s))||o("story-worktree-integration-unbound");const u=new Set(X(e,a).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of r){if(!d.startsWith(`${a}.`))continue;const S=t[d],m=!!e.stories[d]?.checkpoint||typeof S?.status=="string"&&jt.has(S.status);!u.has(d)&&!g.has(d)&&!m&&o("story-worktree-integration-dependency-waiting")}}function Lt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${fe(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function ze(e){return fe(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Ce(e){let t;return await pe(e.projectRoot,a=>{const s=X(a,e.epicId);me(s);const r=[...s].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];r&&r.epicHeadAfterSha!==e.before&&o("story-worktree-integration-chain-invalid"),[...s].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&o("story-worktree-integration-already-integrated"),t=Lt({epicId:e.epicId,storyId:e.storyId,index:s.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),xt(a,e.epicId,{receipts:[t]})},{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 T(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&o("story-worktree-integration-epic-head-raced")}}),t}function ke(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:We(e.receipt)})}}async function $t(e){let t,a,s="";const r=Ee(e.projectRoot);try{(typeof e.storyId!="string"||!_e.test(e.storyId))&&o("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!zt.test(e.leaseId)&&o("story-worktree-integration-lease-invalid");const g=await Ae(await h(r,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await Ae(await h(r,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==n&&o("story-worktree-integration-not-root");let f;try{f=await tt(r,e.storyId)}catch(y){o(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;s=l;const S=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,w=await h(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==w&&o("story-worktree-integration-root-head-mismatch");const D=f.originBinding;(!D||!await T(r,["merge-base","--is-ancestor",D.originHeadSha,w]))&&o("story-worktree-integration-origin-binding-invalid");const A=await V(r,{required:!0}),I=X(A,l);me(I);const P=I.filter(y=>y.storyId===d).sort((y,R)=>R.integrationIndex-y.integrationIndex),E=A.stories[d]?.checkpoint;if(P[0]?.outcome==="integrated")return ke({storyId:d,epicId:l,outcome:"already-integrated",receipt:P[0],...E?.headSha?{checkpointHeadSha:E.headSha}:{}});const G=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(y=>typeof y=="string"):[],x=await gt(r,A);dt(A,x,l,d,G);const H=Object.values(A.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));if(E&&typeof E.headSha=="string"){const y=E.headSha,R=await h(r,["show","--no-patch","--format=%B",y],"story-worktree-integration-git-failed");($(R,"Neocortex-Story")!==d||!$(R,ue))&&o("story-worktree-integration-checkpoint-not-worktree"),y!==w&&o("story-worktree-integration-epic-head-raced"),le(I,E.baseSha);const te=await yt(r,d,`recover-${y.slice(0,40)}`,()=>Ce({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:E.baseSha,after:y,checkpointDigest:ze(E),outcome:"integrated",integratedAt:S})),ne=H.length===1?await qe(r,H[0].leaseId,y):!1;return ke({storyId:d,epicId:l,outcome:"integrated",receipt:te,checkpointHeadSha:y,worktreeRealigned:ne})}const N=Object.values(A.storyWorktrees?.entries??{}).filter(y=>y.storyId===d&&y.epicId===l&&y.state==="active"&&(e.leaseId===void 0||y.leaseId===e.leaseId));N.length===0&&o("story-worktree-integration-lease-missing"),N.length>1&&o("story-worktree-integration-lease-ambiguous");const C=N[0];C.executionBranch!==u&&o("story-worktree-integration-lease-invalid");const b=await new xe({projectRoot:r}).probe(C.leaseId);(!b.ok||b.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),b.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const F=await h(r,["rev-parse",`refs/heads/${C.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");b.value.headSha!==F&&o("story-worktree-integration-worktree-dirty");const B=await h(r,["show","--no-patch","--format=%B",w],"story-worktree-integration-git-failed"),Q=$(B,ue)===F&&$(B,"Neocortex-Story")===d;let _,j,k,U=!1;if(Q){_=await h(r,["rev-parse",`${w}^`],"story-worktree-integration-git-failed"),j=w;const y=$(B,"Neocortex-Bundle-Digest")??"",R=$(B,"Neocortex-Claim-Revision")??"";k=et({storyId:d,epicId:l,executionBranch:u,baseSha:_,bundleDigest:y,graphRevision:f.graphRevision,claimRevision:R}),le(I,_)}else{le(I,w);const y=await lt(r,f,d,w,F);if(y.kind==="conflict")return await Ge({projectRoot:r,epicId:l,storyId:d,executionBranch:u,epicHead:w,tip:F,conflictPaths:y.conflictPaths,integratedAt:S,chain:P});const R=y.changedPaths;j=y.commitSha,k=y.idempotencyKey,_=w,U=!0,(!await T(r,["diff","--cached","--quiet"])||!await T(r,["diff","--quiet","HEAD","--",...R]))&&o("story-worktree-integration-root-dirty")}const Z=await V(r,{required:!0}),q=Z.epics[l]?.branch_lease,oe=q&&q.ownerStoryId===d&&q.sessionId===k&&q.idempotencyKey===k&&Date.parse(String(q.expiresAt))>Date.now()?q:void 0;q&&!oe&&Date.parse(String(q.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const K=oe??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:S,expiresAt:new Date(Date.parse(S)+Ze).toISOString()};t=await Ne(r,{kind:"direct",storyId:d,sessionId:k,idempotencyKey:k,expiresAt:String(K.expiresAt),persistent:!0,createdAt:String(K.acquiredAt)}),t.ok||o(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const Y=t;oe||(await pe(r,y=>{const R=Re(y,l),te=R.branch_lease;te&&Date.parse(String(te.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(R.origin_binding)!==JSON.stringify(D)&&o("story-worktree-integration-origin-binding-invalid"),R.graph_revision!==f.graphRevision&&o("story-worktree-integration-graph-revision-raced"),R.branch_lease=K},{expectedRevision:Z.revision,preCommit:async y=>{await ot(Y.path,Y.owner)||o("story-worktree-integration-lock-raced");const R=X(y,l);me(R),le(R,_),await h(r,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==w&&o("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await h(r,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==w||await h(r,["rev-parse",m],"story-worktree-integration-git-failed")!==w)&&o("story-worktree-integration-epic-head-raced"),await T(r,["merge","--ff-only","--no-edit",j])||o("story-worktree-integration-ff-refused"),await h(r,["rev-parse",m],"story-worktree-integration-git-failed")!==j&&o("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let ee;const ie=await St({projectRoot:r,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,afterCheckpointPersist:async()=>{const y=(await V(r,{required:!0})).stories[d]?.checkpoint;(!y||y.headSha!==j||y.baseSha!==_)&&o("story-worktree-integration-checkpoint-mismatch"),ee=await Ce({projectRoot:r,epicId:l,storyId:d,executionBranch:u,before:_,after:j,checkpointDigest:ze(y),outcome:"integrated",integratedAt:S})}});if(!ie.ok)return{ok:!1,reasonCode:ie.reasonCode};const L=ie.value;(L.headSha!==j||L.baseSha!==_||!ee)&&o("story-worktree-integration-checkpoint-mismatch");const ge=await qe(r,C.leaseId,j);return ke({storyId:d,epicId:l,outcome:"integrated",receipt:ee,checkpointHeadSha:j,worktreeRealigned:ge})}catch(g){if(g instanceof Te)return{ok:!1,reasonCode:g.reasonCode};const n=g instanceof Error?g.message:"";return/^(?:git-lifecycle|direct-yolo)-[a-z0-9-]{1,80}$/.test(n)?{ok:!1,reasonCode:n}:{ok:!1,reasonCode:"story-worktree-integration-failed"}}finally{if(t?.ok&&await Me(t.path,t.owner).catch(()=>{}),a&&s){const g=a;await pe(r,n=>{const f=Re(n,s),l=f.branch_lease;l&&l.sessionId===g.sessionId&&l.idempotencyKey===g.idempotencyKey&&l.acquiredAt===g.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const je=".neocortex/state.json",De=".neocortex",Oe="state.json",W="story-worktree-integration-state-merge-git-failed";function Pe(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const s=a.indexOf(" "),[r,g,n]=a.slice(0,s).split(" ");(s<0||!r||!g||!n)&&o(W),t.push({mode:r,type:g,oid:n,name:a.slice(s+1)})}return t}function qt(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function ft(e,t,a,s){const r=await O(e,["ls-tree","-z",t]);r.code!==0&&o(W);const g=Pe(r.stdout).filter(l=>l.name!==a),n=await st(e,["mktree","-z"],qt([...g,s])),f=n.stdout.trim();return(n.code!==0||!de.test(f))&&o(W),f}async function Le(e,t){const a=await O(e,["ls-tree","-z",t,"--",je]);a.code!==0&&o(W);const s=Pe(a.stdout).find(r=>r.name===je);return s?((s.type!=="blob"||s.mode!=="100644"&&s.mode!=="100755")&&o("state-merge-input-invalid"),de.test(s.oid)||o(W),s.oid):null}async function $e(e,t){t===null&&o("state-merge-input-invalid");const a=await O(e,["cat-file","-s",t]),s=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(s)||s<0||s>Pt)&&o(W);const r=await O(e,["cat-file","blob",t]);return r.code!==0&&o(W),r.stdout}async function Gt(e){try{const{projectRoot:t,mergeBase:a,epicHead:s,tip:r,tree:g,storyId:n,epicId:f}=e,l={ok:!0,tree:g,conflictPaths:[...e.conflictPaths],merged:!1},u=await Le(t,a),d=await Le(t,r);if(u===d)return l;const S=await $e(t,u),m=await $e(t,await Le(t,s)),w=await $e(t,d),D=await h(t,["show","--no-patch","--format=%cI",r],W),A=Ot({base:S,epic:m,story:w,storyId:n,epicId:f,aggregateTimestamp:D});if(!A.ok)return{ok:!1,reasonCode:A.reasonCode};const I=e.conflictPaths.filter(b=>b!==je),P=await O(t,["ls-tree","-z",g,"--",De]);P.code!==0&&o(W);const E=Pe(P.stdout).find(b=>b.name===De);if(!E||E.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const G=await O(t,["ls-tree","-z",E.oid,"--",Oe]);G.code!==0&&o(W);const x=Pe(G.stdout).find(b=>b.name===Oe);if(x&&(x.type!=="blob"||x.mode!=="100644"&&x.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const H=await st(t,["hash-object","-w","--stdin"],A.bytes),N=H.stdout.trim();if((H.code!==0||!de.test(N))&&o(W),x?.oid===N)return{ok:!0,tree:g,conflictPaths:I,merged:!0};const C=await ft(t,E.oid,Oe,{mode:x?.mode??"100644",type:"blob",oid:N,name:Oe});return{ok:!0,tree:await ft(t,g,De,{mode:E.mode,type:"tree",oid:C,name:De}),conflictPaths:I,merged:!0}}catch(t){return t instanceof Te?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:W}}}async function lt(e,t,a,s,r){const{epicId:g,executionBranch:n}=t;await T(e,["merge-base","--is-ancestor",r,s])&&o("story-worktree-integration-range-empty");const f=await h(e,["merge-base",s,r],"story-worktree-integration-unrelated-history"),l=await O(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,s,r]);l.code!==0&&l.code!==1&&o("story-worktree-integration-git-unsupported");const u=l.stdout.split("\0"),d=u[0]?.trim()??"";de.test(d)||o("story-worktree-integration-git-unsupported");const S=l.code===1?[...new Set(u.slice(1).filter(ct))].sort():[];l.code===1&&S.length===0&&o("story-worktree-integration-git-failed");const m=await Gt({projectRoot:e,mergeBase:f,epicHead:s,tip:r,tree:d,storyId:a,epicId:g,conflictPaths:S});m.ok||o(m.reasonCode);const w=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,Wt)};const D=(await h(e,["diff","--name-only","-z",s,w],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),A=Rt(D,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);A.ok||o(A.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":A.reasonCode===ce.WRITE_SET_FORBIDDEN?ce.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const I=t.governanceMode==="runtime-store"?await Ft(e,g,a,r):void 0,P=I?I.review:Dt(e,a,w);P?.verdict!=="approved"&&o("story-worktree-integration-review-not-approved");const E=await O(e,["diff","--binary","--full-index",s,w]);E.code!==0&&o("story-worktree-integration-git-failed");const G=E.stdout;G||o("story-worktree-integration-range-empty");const x=fe(G),H=fe([...t.authorizedWriteSet].sort().join("\0")),N=et({storyId:a,epicId:g,executionBranch:n,baseSha:s,bundleDigest:x,graphRevision:t.graphRevision,claimRevision:H}),C=(await h(e,["show","--no-patch","--format=%s",r],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,z=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${g}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${s}`,`Neocortex-Bundle-Digest: ${x}`,`Neocortex-Review-Artifact-Digest: ${P.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${H}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Nt(t.rootMemoryEffect)}`]:[],...I?[`${it}: ${I.governanceDigest}`]:[],`${ue}: ${r}`],b=(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");b.length!==6&&o("story-worktree-integration-git-failed");const F=await h(e,["commit-tree",w,"-p",s,"-m",C,"-m",`Story: ${a}`,"-m",z.join(`
3
- `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:b[0],GIT_AUTHOR_EMAIL:b[1],GIT_AUTHOR_DATE:b[2],GIT_COMMITTER_NAME:b[3],GIT_COMMITTER_EMAIL:b[4],GIT_COMMITTER_DATE:b[5]});return de.test(F)||o("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:F,changedPaths:D,idempotencyKey:N}}async function Ft(e,t,a,s){const r=await h(e,["show","--no-patch","--format=%B",s],"story-worktree-integration-git-failed"),g=$(r,it);g===void 0&&o("story-worktree-integration-governance-trailer-missing");const n=Ht({projectRoot:e,epicId:t,storyId:a});n.ok||o(n.reasonCode===ce.UNSAFE?n.reasonCode:ce.MISMATCH);const f=n.value.receipt.governanceDigest;g!==f&&o(ce.MISMATCH);const l=n.value.files.get(Bt(a));return l||o(ce.MISMATCH),{governanceDigest:f,review:Ct(a,l)}}async function gt(e,t){const a=JSON.parse(await mt(kt(e,".neocortex","state.json"),"utf8")),r=_t(a,t).stories;return r&&typeof r=="object"&&!Array.isArray(r)?r:{}}async function yt(e,t,a,s){const r=await Ne(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,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 s()}finally{await Me(r.path,r.owner).catch(()=>{})}}async function qe(e,t,a){const s=await new xe({projectRoot:e}).probe(t);return!s.ok||s.value.ownership!=="proven"||s.value.clean!==!0?!1:T(s.value.entry.worktreePath,["reset","--keep",a])}async function Ge(e){const t=fe(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const s=()=>Ce({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),r=e.lockHeld?await s():await yt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,s);return ke({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:r,conflictPaths:Object.freeze([...e.conflictPaths])})}const Kt=64,Yt="@ornexus/neocortex",Fe=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Fe)if(!ct(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Jt(e){return T(e,["clean","-X","-f","-q","--",...Fe])}async function Ut(e,t){const a=await O(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Yt?Fe:[]}catch{return[]}}function Vt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function cr(e){let t,a,s="",r=0,g;const n=Ee(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Kt||new Set(f).size!==f.length||f.some(i=>typeof i!="string"||!_e.test(i)))&&o("story-worktree-wave-stories-invalid");const l=await Ae(await h(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await Ae(await h(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==u&&o("story-worktree-integration-not-root");const d=new Map;for(const i of f)try{d.set(i,await tt(n,i))}catch(c){o(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:w}=S;for(const i of d.values())(i.epicId!==m||i.executionBranch!==w||i.graphRevision!==S.graphRevision||JSON.stringify(i.originBinding)!==JSON.stringify(S.originBinding))&&o("story-worktree-wave-epic-mixed");s=m;const D=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${w}`,I=await h(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==I||await h(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==w)&&o("story-worktree-integration-root-head-mismatch");const P=S.originBinding;(!P||!await T(n,["merge-base","--is-ancestor",P.originHeadSha,I]))&&o("story-worktree-integration-origin-binding-invalid");const E=i=>{const c=d.get(i).story;return Array.isArray(c.depends_on)?c.depends_on.filter(p=>typeof p=="string"):[]},G=new Map(f.map((i,c)=>[i,c]));f.forEach((i,c)=>{for(const p of E(i)){const v=G.get(p);v!==void 0&&v>=c&&o("story-worktree-wave-order-invalid")}});const x=await V(n,{required:!0}),H=X(x,m);me(H);const N=i=>H.filter(c=>c.storyId===i).sort((c,p)=>p.integrationIndex-c.integrationIndex)[0],C=f.filter(i=>N(i)?.outcome!=="integrated"),z=new Map(f.filter(i=>!C.includes(i)).map(i=>{const c=N(i),p=x.stories[i]?.checkpoint;return[i,Object.freeze({storyId:i,outcome:"already-integrated",receiptDigest:We(c),...p?.headSha?{checkpointHeadSha:p.headSha}:{}})]})),b=i=>({ok:!0,value:Object.freeze({epicId:m,...i,gateRuns:r,stories:Object.freeze(f.map(c=>z.get(c)??Object.freeze({storyId:c,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(C.length===0)return b({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0});const F=new Set(C),B=[];let Q=I;for(let i=0;i<C.length;i++){const c=await h(n,["show","--no-patch","--format=%B",Q],"story-worktree-integration-git-failed"),p=$(c,"Neocortex-Story");if(!p||!F.has(p)||!$(c,ue))break;B.unshift(Q),Q=await h(n,["rev-parse",`${Q}^`],"story-worktree-integration-git-failed")}const _=Q;le(H,_);const j=await gt(n,x),k=[];let U,Z=_;for(const[i,c]of C.entries()){const p=d.get(c);dt(x,j,m,c,E(c),new Set(C.slice(0,i)));const v=Object.values(x.storyWorktrees?.entries??{}).filter(J=>J.storyId===c&&J.epicId===m&&J.state==="active"),M=x.stories[c]?.checkpoint;if(M&&typeof M.headSha=="string"){const J=M.headSha,Xe=await h(n,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");($(Xe,"Neocortex-Story")!==c||!$(Xe,ue))&&o("story-worktree-integration-checkpoint-not-worktree"),(M.baseSha!==Z||B[i]!==J)&&o("story-worktree-integration-checkpoint-mismatch");const pt=(await h(n,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:c,sha:J,changedPaths:pt,...v.length===1?{leaseId:v[0].leaseId}:{}}),Z=J;continue}v.length===0&&o("story-worktree-integration-lease-missing"),v.length>1&&o("story-worktree-integration-lease-ambiguous");const Se=v[0];Se.executionBranch!==w&&o("story-worktree-integration-lease-invalid");const be=await new xe({projectRoot:n}).probe(Se.leaseId);(!be.ok||be.value.ownership!=="proven")&&o("story-worktree-integration-ownership-unproven"),be.value.clean!==!0&&o("story-worktree-integration-worktree-dirty");const Be=await h(n,["rev-parse",`refs/heads/${Se.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");be.value.headSha!==Be&&o("story-worktree-integration-worktree-dirty");const se=await lt(n,p,c,Z,Be);if(se.kind==="conflict"){i<B.length&&o("story-worktree-wave-resume-mismatch"),U={storyId:c,tip:Be,conflictPaths:se.conflictPaths};break}i<B.length&&B[i]!==se.commitSha&&o("story-worktree-wave-resume-mismatch"),k.push({storyId:c,sha:se.commitSha,changedPaths:se.changedPaths,leaseId:Se.leaseId}),Z=se.commitSha}if(k.length<B.length&&o("story-worktree-wave-resume-mismatch"),k.length===0){const i=U,c=await Ge({projectRoot:n,epicId:m,storyId:i.storyId,executionBranch:w,epicHead:I,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:D,chain:H.filter(p=>p.storyId===i.storyId).sort((p,v)=>v.integrationIndex-p.integrationIndex)});return c.ok?(z.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:c.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])})),b({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:I,epicHeadAfterSha:I,gateRunCap:0})):{ok:!1,reasonCode:c.reasonCode,gateRuns:r}}const q=k[k.length-1].sha,oe=[...new Set(k.flatMap(i=>i.changedPaths))].sort();(!await T(n,["diff","--cached","--quiet"])||!await T(n,["diff","--quiet","HEAD","--",...oe]))&&o("story-worktree-integration-root-dirty");const K=Vt(k.length),Y=fe(["p205-wave-lease-v1",m,w,_,...k.map(i=>i.sha)].join("\0")),ee=k[0].storyId,ie=await V(n,{required:!0}),L=ie.epics[m]?.branch_lease,ge=L&&L.ownerStoryId===ee&&L.sessionId===Y&&L.idempotencyKey===Y&&Date.parse(String(L.expiresAt))>Date.now()?L:void 0;L&&!ge&&Date.parse(String(L.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active");const y=ge??{schemaVersion:1,ownerStoryId:ee,sessionId:Y,idempotencyKey:Y,acquiredAt:D,expiresAt:new Date(Date.parse(D)+Ze*K).toISOString()};t=await Ne(n,{kind:"direct",storyId:ee,sessionId:Y,idempotencyKey:Y,expiresAt:String(y.expiresAt),persistent:!0,createdAt:String(y.acquiredAt)}),t.ok||o(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const R=t;ge||await pe(n,i=>{const c=Re(i,m),p=c.branch_lease;p&&Date.parse(String(p.expiresAt))>Date.now()&&o("story-worktree-integration-writer-active"),JSON.stringify(c.origin_binding)!==JSON.stringify(P)&&o("story-worktree-integration-origin-binding-invalid"),c.graph_revision!==S.graphRevision&&o("story-worktree-integration-graph-revision-raced"),c.branch_lease=y},{expectedRevision:ie.revision,preCommit:async i=>{await ot(R.path,R.owner)||o("story-worktree-integration-lock-raced");const c=X(i,m);me(c),le(c,_),await h(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==I&&o("story-worktree-integration-epic-head-raced")}}),a=y;const te=new Set(k.map(i=>i.sha));let ne=!0;if(e.push&&B.length>0){const i=(await O(n,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";de.test(i)&&await T(n,["merge-base","--is-ancestor",B[0],i])&&(ne=!1)}let ae=I;const Ie=async i=>{if((await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==ae||await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==ae||await h(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==w)&&o("story-worktree-integration-epic-head-raced"),ae===i)return;const c=await T(n,["merge-base","--is-ancestor",ae,i]);!c&&(!ne||!te.has(ae))&&o("story-worktree-wave-pushed-immovable"),(!(c?await T(n,["merge","--ff-only","--no-edit",i]):await T(n,["reset","--keep",i]))||await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==i||await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==i)&&o("story-worktree-integration-ff-refused"),ae=i};g=ne?{epicRef:A,base:_,owned:te}:void 0,await Ie(q),await e.afterWaveFastForward?.();const ht=[...new Set([S.graphRevision,...k.map(i=>x.stories[i.storyId]?.checkpoint?.graphRevision).filter(i=>typeof i=="string")])],wt=await Ut(n,_),He=async()=>{wt.length!==0&&(await(e.cleanBuildOutputs??Jt)(n)||o("story-worktree-wave-clean-failed"))},Ke=async i=>{const c=k[i];await Ie(c.sha),r>=K&&o("story-worktree-wave-gate-cap-exceeded"),r>0&&await He(),r++;const p=await Et({projectRoot:n,headSha:c.sha,storyId:c.storyId,graphRevisions:ht,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await h(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==c.sha||await h(n,["rev-parse",A],"story-worktree-integration-git-failed")!==c.sha||!await T(n,["diff","--cached","--quiet"])||!await T(n,["diff","--quiet","HEAD","--",...oe]))&&o("story-worktree-integration-epic-head-raced"),!p.ok&&p.kind==="infrastructure"&&o(p.reasonCode),p},ve=await Ke(k.length-1);let Ye=k.length-1,Je=ve.ok?ve.authorities:void 0,ye,he;if(!ve.ok){ne||o("story-worktree-wave-gate-failed-pushed");let i=-1,c=k.length-1;for(he=ve.reasonCode;c-i>1;){const v=Math.floor((i+c)/2),M=await Ke(v);M.ok?(i=v,Je=M.authorities):(c=v,he=M.reasonCode)}ye=c,Ye=i;const p=k[c].storyId;if(z.set(p,Object.freeze({storyId:p,outcome:"gate-failed",reasonCode:he})),i<0)return await Ie(_),await He(),g=void 0,b({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:p,failureReasonCode:he,epicHeadBeforeSha:I,epicHeadAfterSha:_,gateRunCap:K});await Ie(k[i].sha),await He()}const re=k.slice(0,Ye+1),we=re[re.length-1].sha,Ue=vt({epicId:m,executionBranch:w,waveHeadSha:we,waveStoryIds:re.map(i=>i.storyId),waveCommitShas:re.map(i=>i.sha)});e.push&&(g=void 0,await At(n,e.remote??"origin",w,we)||o("story-worktree-wave-remote-head-mismatch")),g=void 0;const Ve=[];for(const[i,c]of re.entries()){const p=i===0?_:re[i-1].sha,v=await bt({projectRoot:n,storyId:c.storyId,headSha:c.sha,coverage:Ue,authorities:Je,expectedLease:y,physicalLock:R,...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});v.ok||o(v.reasonCode),(v.value.headSha!==c.sha||v.value.baseSha!==p)&&o("story-worktree-integration-checkpoint-mismatch");const M=await Ce({projectRoot:n,epicId:m,storyId:c.storyId,executionBranch:w,before:p,after:c.sha,checkpointDigest:ze(v.value),outcome:"integrated",integratedAt:D,expectedEpicHead:we});Ve.push(c.storyId),z.set(c.storyId,Object.freeze({storyId:c.storyId,outcome:"integrated",checkpointHeadSha:c.sha,receiptDigest:We(M)})),await e.afterWaveStoryPersist?.(c.storyId)}if(U&&ye===void 0){const i=U,c=await V(n,{required:!0}),p=await Ge({projectRoot:n,epicId:m,storyId:i.storyId,executionBranch:w,epicHead:we,tip:i.tip,conflictPaths:i.conflictPaths,integratedAt:D,chain:X(c,m).filter(v=>v.storyId===i.storyId).sort((v,M)=>M.integrationIndex-v.integrationIndex),lockHeld:!0});p.ok||o(p.reasonCode),z.set(i.storyId,Object.freeze({storyId:i.storyId,outcome:"conflict-reopened",receiptDigest:p.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...i.conflictPaths])}))}for(const i of re){if(!i.leaseId)continue;const c=await qe(n,i.leaseId,i.sha);z.set(i.storyId,Object.freeze({...z.get(i.storyId),worktreeRealigned:c}))}return b({outcome:ye!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Ve),...ye!==void 0?{failedStoryId:k[ye].storyId,failureReasonCode:he}:{},epicHeadBeforeSha:I,epicHeadAfterSha:we,qaCoverage:Ue,gateRunCap:K})}catch(f){let l=f instanceof Te?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 O(n,["rev-parse",u.epicRef])).stdout.trim(),S=(await O(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==S||!u.owned.has(d)||!await T(n,["reset","--keep",u.base]))&&(l="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:l,gateRuns:r}}finally{if(t?.ok&&await Me(t.path,t.owner).catch(()=>{}),a&&s){const f=a;await pe(n,l=>{const u=Re(l,s),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function dr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(l=>typeof l!="string"||!_e.test(l)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??$t,s=new Set(e.readyStoryIds),r=Ee(e.projectRoot);let g;try{const l=await V(r,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));g=new Set([...u].flatMap(d=>X(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(!s.has(l))return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:S,...m}=e,w=await a({...m,projectRoot:r,storyId:l});if(n.push({storyId:l,result:w}),!w.ok)return{results:n,integratedStoryIds:f,stoppedAt:l,reasonCode:w.reasonCode};if(w.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 fr(e){const t=Ee(e.projectRoot),a=e.manager??new xe({projectRoot:t});let s;try{s=await V(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"&&_e.test(n.storyId)?n.storyId:"";if(!f){r.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const l=Object.values(s.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 a.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{Wt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,Mt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,je as STORY_WORKTREE_STATE_JSON_PATH,Fe as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Yt as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Kt as STORY_WORKTREE_WAVE_MAX_STORIES,We as digestStoryWorktreeIntegrationReceipt,$t as integrateStoryWorktree,cr as integrateStoryWorktreeWave,dr as integrateStoryWorktreesInOrder,Gt as resolveStoryWorktreeStateJsonMerge,Ut as storyWorktreeWaveBuildOutputPaths,Vt as storyWorktreeWaveGateRunCap,fr as syncReleasedDependents};
1
+ import{execFile as Ze}from"node:child_process";import{createHash as kt}from"node:crypto";import{readFile as It,realpath as Re}from"node:fs/promises";import{join as vt,resolve as xe}from"node:path";import{yoloopDomainHash as St}from"../../../shared/dist/yoloop/canonical.js";import{DIRECT_YOLO_STORY_CHECKPOINT_LEASE_MS as et,directYoloCommitIdempotencyKey as tt,directYoloWaveQaCoverage as bt,finalizeDirectYoloStoryCheckpoint as At,persistDirectYoloWaveStoryCheckpoint as Rt,pushDirectYoloWaveHead as xt,resolveDirectYoloIntegrationAuthority as rt,runDirectYoloWaveP205 as Et,validateDirectYoloWriteSet as _t,verifyDirectYoloIntegrationCommit as ot}from"./direct-yolo-checkpoint.js";import{acquireGitLifecyclePhysicalIntegrationLock as Me,appendStoryWorktreeEvidence as Ct,applyGitLifecycleRuntimeOverlay as Dt,ensureRuntimeEpic as Ee,isStoryWorktreeIntegrationReceiptRecord as Tt,mutateGitLifecycleRuntime as ue,publicStoryReviewArtifactFromBytes as Ot,publicStoryReviewArtifactFromGit as Pt,readGitLifecycleRuntime as V,readStoryWorktreeEvidence as it,releaseGitLifecyclePhysicalIntegrationLock as We,verifyGitLifecyclePhysicalIntegrationLock as nt}from"./git-lifecycle-store.js";import{mergeStateJsonFields as Ht,STATE_JSON_FIELD_MERGE_MAX_BYTES as Bt}from"./state-json-field-merge.js";import{GOVERNANCE_DIGEST_TRAILER as at,GOVERNANCE_REASON_CODES as de,readStoryGovernanceSync as Nt,storyReviewGovernancePath as Mt}from"./governance-runtime-store.js";import{StoryWorktreeManager as _e}from"./story-worktree-manager.js";import{rootMemoryEffectDigest as Wt}from"../private-execution/root-memory-git-evidence.js";const zt="neocortex.p225.story-worktree-receipt.v1",jt=200,me="Neocortex-Story-Worktree-Tip",st=3e4,fe=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,Lt=/^swt-[a-f0-9]{24}$/,Ce=/^P[1-9][0-9]*(?:\.[0-9]+)+$/;class De extends Error{reasonCode;constructor(t){super(t),this.reasonCode=t}}function i(e){throw new De(e)}const ct=32*1024*1024;function P(e,t,a){return new Promise(c=>{Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:ct,timeout:st,env:{...process.env,...a,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(o,l)=>{const n=o?typeof o.code=="number"?o.code:128:0;c({code:n,stdout:String(l??"")})})})}function dt(e,t,a){return new Promise(c=>{const o=Ze("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:ct,timeout:st,env:{...process.env,GIT_TERMINAL_PROMPT:"0",LC_ALL:"C"}},(l,n)=>{const f=l?typeof l.code=="number"?l.code:128:0;c({code:f,stdout:String(n??"")})});o.stdin?.on("error",()=>{}),o.stdin?.end(a)})}async function w(e,t,a,c){const o=await P(e,t,c);return o.code!==0&&i(a),o.stdout.trim()}async function C(e,t){return(await P(e,t)).code===0}function ge(e){return kt("sha256").update(e).digest("hex")}function ft(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 z(e,t){const a=`${t}: `,c=e.split(`
2
+ `).map(o=>o.trim()).filter(o=>o.startsWith(a));return c.length===1?c[0].slice(a.length):void 0}function ze(e){return St(zt,e)}function X(e,t){return(it(e,t)?.receipts??[]).filter(Tt)}function ke(e){const t=[...e].sort((a,c)=>a.integrationIndex-c.integrationIndex);t.forEach((a,c)=>{(a.integrationIndex!==c+1||c>0&&a.epicHeadBeforeSha!==t[c-1].epicHeadAfterSha)&&i("story-worktree-integration-chain-invalid")})}function le(e,t){const a=[...e].sort((c,o)=>o.integrationIndex-c.integrationIndex)[0];a&&a.epicHeadAfterSha!==t&&i("story-worktree-integration-chain-invalid")}const $t=new Set(["done","merged","completed","released"]);function gt(e,t,a,c,o,l=new Set){(it(e,a)?.receipts??[]).some(d=>d.kind==="phase-one-receipt"&&d.storyId===c||d.kind==="spec-barrier-receipt"&&Array.isArray(d.storyIds)&&d.storyIds.includes(c))||i("story-worktree-integration-unbound");const u=new Set(X(e,a).filter(d=>d.outcome==="integrated").map(d=>d.storyId));for(const d of o){if(!d.startsWith(`${a}.`))continue;const b=t[d],m=!!e.stories[d]?.checkpoint||typeof b?.status=="string"&&$t.has(b.status);!u.has(d)&&!l.has(d)&&!m&&i("story-worktree-integration-dependency-waiting")}}function Gt(e){const t=e.outcome==="integrated"?"integrated":"integration-conflict-reopened",a=`int-${ge(["p225-integration-receipt-v1",e.epicId,e.storyId,String(e.index),e.before,e.after,e.checkpointDigest,e.outcome].join("\0")).slice(0,32)}`;return Object.freeze({schemaVersion:1,kind:"integration-receipt",receiptId:a,epicId:e.epicId,storyId:e.storyId,integrationOwner:"root_agent",integrationIndex:e.index,epicHeadBeforeSha:e.before,epicHeadAfterSha:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,reasonCode:t,integratedAt:e.integratedAt})}function je(e){return ge(["p225-integration-checkpoint-v1",e.storyId,e.headSha,String(e.idempotencyKey),String(e.bundleDigest)].join("\0"))}async function Te(e){let t;return await ue(e.projectRoot,a=>{const c=X(a,e.epicId);ke(c);const o=[...c].sort((n,f)=>f.integrationIndex-n.integrationIndex)[0];o&&o.epicHeadAfterSha!==e.before&&i("story-worktree-integration-chain-invalid"),[...c].filter(n=>n.storyId===e.storyId).sort((n,f)=>f.integrationIndex-n.integrationIndex)[0]?.outcome==="integrated"&&i("story-worktree-integration-already-integrated"),t=Gt({epicId:e.epicId,storyId:e.storyId,index:c.length+1,before:e.before,after:e.after,checkpointDigest:e.checkpointDigest,outcome:e.outcome,integratedAt:e.integratedAt}),Ct(a,e.epicId,{receipts:[t]})},{preCommit:async()=>{await w(e.projectRoot,["rev-parse",`refs/heads/${e.executionBranch}`],"story-worktree-integration-epic-branch-missing")!==(e.expectedEpicHead??e.after)&&i("story-worktree-integration-epic-head-raced"),e.expectedEpicHead!==void 0&&e.expectedEpicHead!==e.after&&!await C(e.projectRoot,["merge-base","--is-ancestor",e.after,e.expectedEpicHead])&&i("story-worktree-integration-epic-head-raced")}}),t}function Ie(e){return{ok:!0,value:Object.freeze({...e,receiptDigest:ze(e.receipt)})}}async function qt(e){let t,a,c="";const o=xe(e.projectRoot);try{(typeof e.storyId!="string"||!Ce.test(e.storyId))&&i("story-worktree-integration-story-invalid"),e.leaseId!==void 0&&!Lt.test(e.leaseId)&&i("story-worktree-integration-lease-invalid");const l=await Re(await w(o,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),n=await Re(await w(o,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));l!==n&&i("story-worktree-integration-not-root");let f;try{f=await rt(o,e.storyId)}catch(h){i(h instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(h.message)?h.message:"story-worktree-integration-authority-invalid")}const{epicId:g,executionBranch:u,storyId:d}=f;c=g;const b=new Date(e.nowIso??Date.now()).toISOString(),m=`refs/heads/${u}`,p=await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing");await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p&&i("story-worktree-integration-root-head-mismatch");const T=f.originBinding;(!T||!await C(o,["merge-base","--is-ancestor",T.originHeadSha,p]))&&i("story-worktree-integration-origin-binding-invalid");const A=await V(o,{required:!0}),v=X(A,g);ke(v);const H=v.filter(h=>h.storyId===d).sort((h,x)=>x.integrationIndex-h.integrationIndex),R=A.stories[d]?.checkpoint;if(H[0]?.outcome==="integrated")return Ie({storyId:d,epicId:g,outcome:"already-integrated",receipt:H[0],...R?.headSha?{checkpointHeadSha:R.headSha}:{}});const q=Array.isArray(f.story.depends_on)?f.story.depends_on.filter(h=>typeof h=="string"):[],E=await yt(o,A);gt(A,E,g,d,q);const B=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));if(R&&typeof R.headSha=="string"){const h=R.headSha,x=await w(o,["show","--no-patch","--format=%B",h],"story-worktree-integration-git-failed");(z(x,"Neocortex-Story")!==d||!z(x,me))&&i("story-worktree-integration-checkpoint-not-worktree"),h!==p&&i("story-worktree-integration-epic-head-raced"),le(v,R.baseSha);const re=await wt(o,d,`recover-${h.slice(0,40)}`,()=>Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:R.baseSha,after:h,checkpointDigest:je(R),outcome:"integrated",integratedAt:b})),ae=B.length===1?await qe(o,B[0].leaseId,h):!1;return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:re,checkpointHeadSha:h,worktreeRealigned:ae})}const M=Object.values(A.storyWorktrees?.entries??{}).filter(h=>h.storyId===d&&h.epicId===g&&h.state==="active"&&(e.leaseId===void 0||h.leaseId===e.leaseId));M.length===0&&i("story-worktree-integration-lease-missing"),M.length>1&&i("story-worktree-integration-lease-ambiguous");const D=M[0];D.executionBranch!==u&&i("story-worktree-integration-lease-invalid");const S=await new _e({projectRoot:o}).probe(D.leaseId);(!S.ok||S.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),S.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const F=await w(o,["rev-parse",`refs/heads/${D.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");S.value.headSha!==F&&i("story-worktree-integration-worktree-dirty");const N=await w(o,["show","--no-patch","--format=%B",p],"story-worktree-integration-git-failed"),Q=z(N,me)===F&&z(N,"Neocortex-Story")===d;let _,W,k,U=!1;if(Q){_=await w(o,["rev-parse",`${p}^`],"story-worktree-integration-git-failed"),W=p;const h=z(N,"Neocortex-Bundle-Digest")??"",x=z(N,"Neocortex-Claim-Revision")??"";k=tt({storyId:d,epicId:g,executionBranch:u,baseSha:_,bundleDigest:h,graphRevision:f.graphRevision,claimRevision:x}),le(v,_)}else{le(v,p);const h=await ht(o,f,d,p,F);if(h.kind==="conflict")return await Fe({projectRoot:o,epicId:g,storyId:d,executionBranch:u,epicHead:p,tip:F,conflictPaths:h.conflictPaths,integratedAt:b,chain:H});const x=h.changedPaths;W=h.commitSha,k=h.idempotencyKey,_=p,U=!0,(!await C(o,["diff","--cached","--quiet"])||!await C(o,["diff","--quiet","HEAD","--",...x]))&&i("story-worktree-integration-root-dirty")}const Z=await ot(f,d,W);Z.ok||i(Z.reasonCode);const ee=await V(o,{required:!0}),G=ee.epics[g]?.branch_lease,ie=G&&G.ownerStoryId===d&&G.sessionId===k&&G.idempotencyKey===k&&Date.parse(String(G.expiresAt))>Date.now()?G:void 0;G&&!ie&&Date.parse(String(G.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const K=ie??{schemaVersion:1,ownerStoryId:d,sessionId:k,idempotencyKey:k,acquiredAt:b,expiresAt:new Date(Date.parse(b)+et).toISOString()};t=await Me(o,{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;ie||(await ue(o,h=>{const x=Ee(h,g),re=x.branch_lease;re&&Date.parse(String(re.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(x.origin_binding)!==JSON.stringify(T)&&i("story-worktree-integration-origin-binding-invalid"),x.graph_revision!==f.graphRevision&&i("story-worktree-integration-graph-revision-raced"),x.branch_lease=K},{expectedRevision:ee.revision,preCommit:async h=>{await nt(Y.path,Y.owner)||i("story-worktree-integration-lock-raced");const x=X(h,g);ke(x),le(x,_),await w(o,["rev-parse",m],"story-worktree-integration-epic-branch-missing")!==p&&i("story-worktree-integration-epic-head-raced")}}),a=K),U&&((await w(o,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==p||await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),await C(o,["merge","--ff-only","--no-edit",W])||i("story-worktree-integration-ff-refused"),await w(o,["rev-parse",m],"story-worktree-integration-git-failed")!==W&&i("story-worktree-integration-ff-refused")),await e.afterFastForward?.();let te;const ne=await At({projectRoot:o,storyId:d,push:e.push,remote:e.remote,nowIso:e.nowIso,qaRunner:e.qaRunner,preFastForwardAuthorizedWriteSet:f.authorizedWriteSet,afterCheckpointPersist:async()=>{const h=(await V(o,{required:!0})).stories[d]?.checkpoint;(!h||h.headSha!==W||h.baseSha!==_)&&i("story-worktree-integration-checkpoint-mismatch"),te=await Te({projectRoot:o,epicId:g,storyId:d,executionBranch:u,before:_,after:W,checkpointDigest:je(h),outcome:"integrated",integratedAt:b})}});if(!ne.ok)return{ok:!1,reasonCode:ne.reasonCode};const $=ne.value;($.headSha!==W||$.baseSha!==_||!te)&&i("story-worktree-integration-checkpoint-mismatch");const he=await qe(o,D.leaseId,W);return Ie({storyId:d,epicId:g,outcome:"integrated",receipt:te,checkpointHeadSha:W,worktreeRealigned:he})}catch(l){if(l instanceof De)return{ok:!1,reasonCode:l.reasonCode};const n=l instanceof Error?l.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 We(t.path,t.owner).catch(()=>{}),a&&c){const l=a;await ue(o,n=>{const f=Ee(n,c),g=f.branch_lease;g&&g.sessionId===l.sessionId&&g.idempotencyKey===l.idempotencyKey&&g.acquiredAt===l.acquiredAt&&(f.branch_lease=null)}).catch(()=>{})}}}const Le=".neocortex/state.json",Oe=".neocortex",Pe="state.json",j="story-worktree-integration-state-merge-git-failed";function He(e){const t=[];for(const a of e.split("\0")){if(!a)continue;const c=a.indexOf(" "),[o,l,n]=a.slice(0,c).split(" ");(c<0||!o||!l||!n)&&i(j),t.push({mode:o,type:l,oid:n,name:a.slice(c+1)})}return t}function Ft(e){return e.map(t=>`${t.mode} ${t.type} ${t.oid} ${t.name}\0`).join("")}async function lt(e,t,a,c){const o=await P(e,["ls-tree","-z",t]);o.code!==0&&i(j);const l=He(o.stdout).filter(g=>g.name!==a),n=await dt(e,["mktree","-z"],Ft([...l,c])),f=n.stdout.trim();return(n.code!==0||!fe.test(f))&&i(j),f}async function $e(e,t){const a=await P(e,["ls-tree","-z",t,"--",Le]);a.code!==0&&i(j);const c=He(a.stdout).find(o=>o.name===Le);return c?((c.type!=="blob"||c.mode!=="100644"&&c.mode!=="100755")&&i("state-merge-input-invalid"),fe.test(c.oid)||i(j),c.oid):null}async function Ge(e,t){t===null&&i("state-merge-input-invalid");const a=await P(e,["cat-file","-s",t]),c=Number.parseInt(a.stdout.trim(),10);(a.code!==0||!Number.isSafeInteger(c)||c<0||c>Bt)&&i(j);const o=await P(e,["cat-file","blob",t]);return o.code!==0&&i(j),o.stdout}async function Kt(e){try{const{projectRoot:t,mergeBase:a,epicHead:c,tip:o,tree:l,storyId:n,epicId:f}=e,g={ok:!0,tree:l,conflictPaths:[...e.conflictPaths],merged:!1},u=await $e(t,a),d=await $e(t,o);if(u===d)return g;const b=await Ge(t,u),m=await Ge(t,await $e(t,c)),p=await Ge(t,d),T=await w(t,["show","--no-patch","--format=%cI",o],j),A=Ht({base:b,epic:m,story:p,storyId:n,epicId:f,aggregateTimestamp:T});if(!A.ok)return{ok:!1,reasonCode:A.reasonCode};const v=e.conflictPaths.filter(S=>S!==Le),H=await P(t,["ls-tree","-z",l,"--",Oe]);H.code!==0&&i(j);const R=He(H.stdout).find(S=>S.name===Oe);if(!R||R.type!=="tree")return{ok:!1,reasonCode:"state-merge-input-invalid"};const q=await P(t,["ls-tree","-z",R.oid,"--",Pe]);q.code!==0&&i(j);const E=He(q.stdout).find(S=>S.name===Pe);if(E&&(E.type!=="blob"||E.mode!=="100644"&&E.mode!=="100755"))return{ok:!1,reasonCode:"state-merge-input-invalid"};const B=await dt(t,["hash-object","-w","--stdin"],A.bytes),M=B.stdout.trim();if((B.code!==0||!fe.test(M))&&i(j),E?.oid===M)return{ok:!0,tree:l,conflictPaths:v,merged:!0};const D=await lt(t,R.oid,Pe,{mode:E?.mode??"100644",type:"blob",oid:M,name:Pe});return{ok:!0,tree:await lt(t,l,Oe,{mode:R.mode,type:"tree",oid:D,name:Oe}),conflictPaths:v,merged:!0}}catch(t){return t instanceof De?{ok:!1,reasonCode:t.reasonCode}:{ok:!1,reasonCode:j}}}async function ht(e,t,a,c,o){const{epicId:l,executionBranch:n}=t;await C(e,["merge-base","--is-ancestor",o,c])&&i("story-worktree-integration-range-empty");const f=await w(e,["merge-base",c,o],"story-worktree-integration-unrelated-history"),g=await P(e,["merge-tree","--write-tree","-z","--name-only","--no-messages",`--merge-base=${f}`,c,o]);g.code!==0&&g.code!==1&&i("story-worktree-integration-git-unsupported");const u=g.stdout.split("\0"),d=u[0]?.trim()??"";fe.test(d)||i("story-worktree-integration-git-unsupported");const b=g.code===1?[...new Set(u.slice(1).filter(ft))].sort():[];g.code===1&&b.length===0&&i("story-worktree-integration-git-failed");const m=await Kt({projectRoot:e,mergeBase:f,epicHead:c,tip:o,tree:d,storyId:a,epicId:l,conflictPaths:b});m.ok||i(m.reasonCode);const p=m.tree;if(m.conflictPaths.length>0)return{kind:"conflict",conflictPaths:m.conflictPaths.slice(0,jt)};const T=(await w(e,["diff","--name-only","-z",c,p],"story-worktree-integration-git-failed")).split("\0").filter(Boolean),A=_t(T,t.authorizedWriteSet,a,t.rootMemoryEffect,t.governanceMode);A.ok||i(A.reasonCode==="direct-yolo-write-set-unauthorized"?"story-worktree-integration-write-set-unauthorized":A.reasonCode===de.WRITE_SET_FORBIDDEN?de.WRITE_SET_FORBIDDEN:"story-worktree-integration-write-set-invalid");const v=t.governanceMode==="runtime-store"?await Yt(e,l,a,o):void 0,H=v?v.review:Pt(e,a,p);H?.verdict!=="approved"&&i("story-worktree-integration-review-not-approved");const R=await P(e,["diff","--binary","--full-index",c,p]);R.code!==0&&i("story-worktree-integration-git-failed");const q=R.stdout;q||i("story-worktree-integration-range-empty");const E=ge(q),B=ge([...t.authorizedWriteSet].sort().join("\0")),M=tt({storyId:a,epicId:l,executionBranch:n,baseSha:c,bundleDigest:E,graphRevision:t.graphRevision,claimRevision:B}),D=(await w(e,["show","--no-patch","--format=%s",o],"story-worktree-integration-git-failed")).slice(0,200)||`feat(${a}): integrate story worktree`,L=[`Neocortex-Story: ${a}`,`Neocortex-Epic: ${l}`,`Neocortex-Execution-Branch: ${n}`,`Neocortex-Prepared-Base: ${c}`,`Neocortex-Bundle-Digest: ${E}`,`Neocortex-Review-Artifact-Digest: ${H.digest}`,`Neocortex-Graph-Revision: ${t.graphRevision}`,`Neocortex-Claim-Revision: ${B}`,...t.rootMemoryEffect?[`Neocortex-Root-Memory-Effect: ${Wt(t.rootMemoryEffect)}`]:[],...v?[`${at}: ${v.governanceDigest}`]:[],`${me}: ${o}`],S=(await w(e,["show","--no-patch","--format=%an%x00%ae%x00%aI%x00%cn%x00%ce%x00%cI",o],"story-worktree-integration-git-failed")).split("\0");S.length!==6&&i("story-worktree-integration-git-failed");const F=await w(e,["commit-tree",p,"-p",c,"-m",D,"-m",`Story: ${a}`,"-m",L.join(`
3
+ `)],"story-worktree-integration-commit-failed",{GIT_AUTHOR_NAME:S[0],GIT_AUTHOR_EMAIL:S[1],GIT_AUTHOR_DATE:S[2],GIT_COMMITTER_NAME:S[3],GIT_COMMITTER_EMAIL:S[4],GIT_COMMITTER_DATE:S[5]});return fe.test(F)||i("story-worktree-integration-commit-failed"),{kind:"commit",commitSha:F,changedPaths:T,idempotencyKey:M}}async function Yt(e,t,a,c){const o=await w(e,["show","--no-patch","--format=%B",c],"story-worktree-integration-git-failed"),l=z(o,at);l===void 0&&i("story-worktree-integration-governance-trailer-missing");const n=Nt({projectRoot:e,epicId:t,storyId:a});n.ok||i(n.reasonCode===de.UNSAFE?n.reasonCode:de.MISMATCH);const f=n.value.receipt.governanceDigest;l!==f&&i(de.MISMATCH);const g=n.value.files.get(Mt(a));return g||i(de.MISMATCH),{governanceDigest:f,review:Ot(a,g)}}async function yt(e,t){const a=JSON.parse(await It(vt(e,".neocortex","state.json"),"utf8")),o=Dt(a,t).stories;return o&&typeof o=="object"&&!Array.isArray(o)?o:{}}async function wt(e,t,a,c){const o=await Me(e,{kind:"direct",storyId:t,sessionId:a,idempotencyKey:a,expiresAt:new Date(Date.now()+3e5).toISOString(),persistent:!1});o.ok||i(o.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");try{return await c()}finally{await We(o.path,o.owner).catch(()=>{})}}async function qe(e,t,a){const c=await new _e({projectRoot:e}).probe(t);return!c.ok||c.value.ownership!=="proven"||c.value.clean!==!0?!1:C(c.value.entry.worktreePath,["reset","--keep",a])}async function Fe(e){const t=ge(["p225-integration-conflict-v1",e.storyId,e.epicHead,e.tip,...e.conflictPaths].join("\0")),a=e.chain[0];if(a?.outcome==="conflict-reopened"&&a.epicHeadAfterSha===e.epicHead&&a.checkpointDigest===t)return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:a,conflictPaths:Object.freeze([...e.conflictPaths])});const c=()=>Te({projectRoot:e.projectRoot,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,before:e.epicHead,after:e.epicHead,checkpointDigest:t,outcome:"conflict-reopened",integratedAt:e.integratedAt}),o=e.lockHeld?await c():await wt(e.projectRoot,e.storyId,`conflict-${t.slice(0,48)}`,c);return Ie({storyId:e.storyId,epicId:e.epicId,outcome:"conflict-reopened",receipt:o,conflictPaths:Object.freeze([...e.conflictPaths])})}const Jt=64,Ut="@ornexus/neocortex",Ke=Object.freeze(["dist","packages/shared/dist","packages/client/dist","packages/server/dist"]);for(const e of Ke)if(!ft(e)||/[*?[\]!:]/.test(e))throw new Error("story-worktree-wave-build-output-path-invalid");async function Vt(e){return C(e,["clean","-X","-f","-q","--",...Ke])}async function Xt(e,t){const a=await P(e,["show",`${t}:package.json`]);if(a.code!==0)return[];try{return JSON.parse(a.stdout)?.name===Ut?Ke:[]}catch{return[]}}function Qt(e){return 1+Math.ceil(Math.log2(Math.max(1,e)))+1}async function fr(e){let t,a,c="",o=0,l;const n=xe(e.projectRoot);try{const f=e.storyIds;(!Array.isArray(f)||f.length===0||f.length>Jt||new Set(f).size!==f.length||f.some(r=>typeof r!="string"||!Ce.test(r)))&&i("story-worktree-wave-stories-invalid");const g=await Re(await w(n,["rev-parse","--absolute-git-dir"],"story-worktree-integration-not-root")),u=await Re(await w(n,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-integration-not-root"));g!==u&&i("story-worktree-integration-not-root");const d=new Map;for(const r of f)try{d.set(r,await rt(n,r))}catch(s){i(s instanceof Error&&/^direct-yolo-[a-z0-9-]+$/.test(s.message)?s.message:"story-worktree-integration-authority-invalid")}const b=d.get(f[0]),{epicId:m,executionBranch:p}=b;for(const r of d.values())(r.epicId!==m||r.executionBranch!==p||r.graphRevision!==b.graphRevision||JSON.stringify(r.originBinding)!==JSON.stringify(b.originBinding))&&i("story-worktree-wave-epic-mixed");c=m;const T=new Date(e.nowIso??Date.now()).toISOString(),A=`refs/heads/${p}`,v=await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing");(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==v||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-root-head-mismatch")!==p)&&i("story-worktree-integration-root-head-mismatch");const H=b.originBinding;(!H||!await C(n,["merge-base","--is-ancestor",H.originHeadSha,v]))&&i("story-worktree-integration-origin-binding-invalid");const R=r=>{const s=d.get(r).story;return Array.isArray(s.depends_on)?s.depends_on.filter(y=>typeof y=="string"):[]},q=new Map(f.map((r,s)=>[r,s]));f.forEach((r,s)=>{for(const y of R(r)){const I=q.get(y);I!==void 0&&I>=s&&i("story-worktree-wave-order-invalid")}});const E=await V(n,{required:!0}),B=X(E,m);ke(B);const M=r=>B.filter(s=>s.storyId===r).sort((s,y)=>y.integrationIndex-s.integrationIndex)[0],D=f.filter(r=>M(r)?.outcome!=="integrated"),L=new Map(f.filter(r=>!D.includes(r)).map(r=>{const s=M(r),y=E.stories[r]?.checkpoint;return[r,Object.freeze({storyId:r,outcome:"already-integrated",receiptDigest:ze(s),...y?.headSha?{checkpointHeadSha:y.headSha}:{}})]})),S=r=>({ok:!0,value:Object.freeze({epicId:m,...r,gateRuns:o,stories:Object.freeze(f.map(s=>L.get(s)??Object.freeze({storyId:s,outcome:"not-integrated",reasonCode:"story-worktree-wave-not-attempted"})))})});if(D.length===0)return S({outcome:"integrated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0});const F=new Set(D),N=[];let Q=v;for(let r=0;r<D.length;r++){const s=await w(n,["show","--no-patch","--format=%B",Q],"story-worktree-integration-git-failed"),y=z(s,"Neocortex-Story");if(!y||!F.has(y)||!z(s,me))break;N.unshift(Q),Q=await w(n,["rev-parse",`${Q}^`],"story-worktree-integration-git-failed")}const _=Q;le(B,_);const W=await yt(n,E),k=[];let U,Z=_;for(const[r,s]of D.entries()){const y=d.get(s);gt(E,W,m,s,R(s),new Set(D.slice(0,r)));const I=Object.values(E.storyWorktrees?.entries??{}).filter(J=>J.storyId===s&&J.epicId===m&&J.state==="active"),O=E.stories[s]?.checkpoint;if(O&&typeof O.headSha=="string"){const J=O.headSha,Qe=await w(n,["show","--no-patch","--format=%B",J],"story-worktree-integration-git-failed");(z(Qe,"Neocortex-Story")!==s||!z(Qe,me))&&i("story-worktree-integration-checkpoint-not-worktree"),(O.baseSha!==Z||N[r]!==J)&&i("story-worktree-integration-checkpoint-mismatch");const mt=(await w(n,["diff-tree","--no-commit-id","--name-only","-r","-z",J],"story-worktree-integration-git-failed")).split("\0").filter(Boolean);k.push({storyId:s,sha:J,changedPaths:mt,...I.length===1?{leaseId:I[0].leaseId}:{},...typeof O.graphRevision=="string"?{checkpointGraphRevision:O.graphRevision}:{}}),Z=J;continue}I.length===0&&i("story-worktree-integration-lease-missing"),I.length>1&&i("story-worktree-integration-lease-ambiguous");const be=I[0];be.executionBranch!==p&&i("story-worktree-integration-lease-invalid");const Ae=await new _e({projectRoot:n}).probe(be.leaseId);(!Ae.ok||Ae.value.ownership!=="proven")&&i("story-worktree-integration-ownership-unproven"),Ae.value.clean!==!0&&i("story-worktree-integration-worktree-dirty");const Ne=await w(n,["rev-parse",`refs/heads/${be.temporaryBranch}^{commit}`],"story-worktree-integration-branch-missing");Ae.value.headSha!==Ne&&i("story-worktree-integration-worktree-dirty");const ce=await ht(n,y,s,Z,Ne);if(ce.kind==="conflict"){r<N.length&&i("story-worktree-wave-resume-mismatch"),U={storyId:s,tip:Ne,conflictPaths:ce.conflictPaths};break}r<N.length&&N[r]!==ce.commitSha&&i("story-worktree-wave-resume-mismatch"),k.push({storyId:s,sha:ce.commitSha,changedPaths:ce.changedPaths,leaseId:be.leaseId}),Z=ce.commitSha}if(k.length<N.length&&i("story-worktree-wave-resume-mismatch"),k.length===0){const r=U,s=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:v,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:B.filter(y=>y.storyId===r.storyId).sort((y,I)=>I.integrationIndex-y.integrationIndex)});return s.ok?(L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:s.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])})),S({outcome:"conflict-truncated",integratedStoryIds:Object.freeze([]),epicHeadBeforeSha:v,epicHeadAfterSha:v,gateRunCap:0})):{ok:!1,reasonCode:s.reasonCode,gateRuns:o}}const ee=new Map;for(const r of k){if(r.checkpointGraphRevision!==void 0){const y=await w(n,["show","--no-patch","--format=%B",r.sha],"story-worktree-integration-git-failed"),I=z(y,"Neocortex-Graph-Revision");I===void 0&&i("direct-yolo-trailer-missing:neocortex-graph-revision"),I!==r.checkpointGraphRevision&&i("direct-yolo-trailer-mismatch:neocortex-graph-revision"),ee.set(r.sha,I);continue}const s=await ot(d.get(r.storyId),r.storyId,r.sha);s.ok||i(s.reasonCode),ee.set(r.sha,s.value.graphRevision)}const G=k[k.length-1].sha,ie=[...new Set(k.flatMap(r=>r.changedPaths))].sort();(!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-root-dirty");const K=Qt(k.length),Y=ge(["p205-wave-lease-v1",m,p,_,...k.map(r=>r.sha)].join("\0")),te=k[0].storyId,ne=await V(n,{required:!0}),$=ne.epics[m]?.branch_lease,he=$&&$.ownerStoryId===te&&$.sessionId===Y&&$.idempotencyKey===Y&&Date.parse(String($.expiresAt))>Date.now()?$:void 0;$&&!he&&Date.parse(String($.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active");const h=he??{schemaVersion:1,ownerStoryId:te,sessionId:Y,idempotencyKey:Y,acquiredAt:T,expiresAt:new Date(Date.parse(T)+et*K).toISOString()};t=await Me(n,{kind:"direct",storyId:te,sessionId:Y,idempotencyKey:Y,expiresAt:String(h.expiresAt),persistent:!0,createdAt:String(h.acquiredAt)}),t.ok||i(t.reasonCode==="git-lifecycle-integration-backpressure"?"story-worktree-integration-backpressure":"story-worktree-integration-lock-failed");const x=t;he||await ue(n,r=>{const s=Ee(r,m),y=s.branch_lease;y&&Date.parse(String(y.expiresAt))>Date.now()&&i("story-worktree-integration-writer-active"),JSON.stringify(s.origin_binding)!==JSON.stringify(H)&&i("story-worktree-integration-origin-binding-invalid"),s.graph_revision!==b.graphRevision&&i("story-worktree-integration-graph-revision-raced"),s.branch_lease=h},{expectedRevision:ne.revision,preCommit:async r=>{await nt(x.path,x.owner)||i("story-worktree-integration-lock-raced");const s=X(r,m);ke(s),le(s,_),await w(n,["rev-parse",A],"story-worktree-integration-epic-branch-missing")!==v&&i("story-worktree-integration-epic-head-raced")}}),a=h;const re=new Set(k.map(r=>r.sha));let ae=!0;if(e.push&&N.length>0){const r=(await P(n,["ls-remote","--heads",e.remote??"origin",A])).stdout.split(/\s+/)[0]??"";fe.test(r)&&await C(n,["merge-base","--is-ancestor",N[0],r])&&(ae=!1)}let se=v;const ve=async r=>{if((await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==se||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==se||await w(n,["symbolic-ref","--quiet","--short","HEAD"],"story-worktree-integration-git-failed")!==p)&&i("story-worktree-integration-epic-head-raced"),se===r)return;const s=await C(n,["merge-base","--is-ancestor",se,r]);!s&&(!ae||!re.has(se))&&i("story-worktree-wave-pushed-immovable"),(!(s?await C(n,["merge","--ff-only","--no-edit",r]):await C(n,["reset","--keep",r]))||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==r||await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==r)&&i("story-worktree-integration-ff-refused"),se=r};l=ae?{epicRef:A,base:_,owned:re}:void 0,await ve(G),await e.afterWaveFastForward?.();const pt=[...new Set(k.map(r=>ee.get(r.sha)))],ut=await Xt(n,_),Be=async()=>{ut.length!==0&&(await(e.cleanBuildOutputs??Vt)(n)||i("story-worktree-wave-clean-failed"))},Ye=async r=>{const s=k[r];await ve(s.sha),o>=K&&i("story-worktree-wave-gate-cap-exceeded"),o>0&&await Be(),o++;const y=await Et({projectRoot:n,headSha:s.sha,storyId:s.storyId,graphRevisions:pt,...e.nowIso!==void 0?{nowIso:e.nowIso}:{},...e.qaRunner?{qaRunner:e.qaRunner}:{}});return(await w(n,["rev-parse","HEAD"],"story-worktree-integration-git-failed")!==s.sha||await w(n,["rev-parse",A],"story-worktree-integration-git-failed")!==s.sha||!await C(n,["diff","--cached","--quiet"])||!await C(n,["diff","--quiet","HEAD","--",...ie]))&&i("story-worktree-integration-epic-head-raced"),!y.ok&&y.kind==="infrastructure"&&i(y.reasonCode),y},Se=await Ye(k.length-1);let Je=k.length-1,Ue=Se.ok?Se.authorities:void 0,ye,we;if(!Se.ok){ae||i("story-worktree-wave-gate-failed-pushed");let r=-1,s=k.length-1;for(we=Se.reasonCode;s-r>1;){const I=Math.floor((r+s)/2),O=await Ye(I);O.ok?(r=I,Ue=O.authorities):(s=I,we=O.reasonCode)}ye=s,Je=r;const y=k[s].storyId;if(L.set(y,Object.freeze({storyId:y,outcome:"gate-failed",reasonCode:we})),r<0)return await ve(_),await Be(),l=void 0,S({outcome:"gate-failed",integratedStoryIds:Object.freeze([]),failedStoryId:y,failureReasonCode:we,epicHeadBeforeSha:v,epicHeadAfterSha:_,gateRunCap:K});await ve(k[r].sha),await Be()}const oe=k.slice(0,Je+1),pe=oe[oe.length-1].sha,Ve=bt({epicId:m,executionBranch:p,waveHeadSha:pe,waveStoryIds:oe.map(r=>r.storyId),waveCommitShas:oe.map(r=>r.sha)});e.push&&(l=void 0,await xt(n,e.remote??"origin",p,pe)||i("story-worktree-wave-remote-head-mismatch")),l=void 0;const Xe=[];for(const[r,s]of oe.entries()){const y=r===0?_:oe[r-1].sha,I=await Rt({projectRoot:n,storyId:s.storyId,headSha:s.sha,coverage:Ve,authorities:Ue,expectedLease:h,physicalLock:x,authorizedWriteSet:d.get(s.storyId).authorizedWriteSet,expectedGraphRevision:ee.get(s.sha),...e.push?{remote:e.remote??"origin"}:{},...e.nowIso!==void 0?{nowIso:e.nowIso}:{}});I.ok||i(I.reasonCode),(I.value.headSha!==s.sha||I.value.baseSha!==y)&&i("story-worktree-integration-checkpoint-mismatch");const O=await Te({projectRoot:n,epicId:m,storyId:s.storyId,executionBranch:p,before:y,after:s.sha,checkpointDigest:je(I.value),outcome:"integrated",integratedAt:T,expectedEpicHead:pe});Xe.push(s.storyId),L.set(s.storyId,Object.freeze({storyId:s.storyId,outcome:"integrated",checkpointHeadSha:s.sha,receiptDigest:ze(O)})),await e.afterWaveStoryPersist?.(s.storyId)}if(U&&ye===void 0){const r=U,s=await V(n,{required:!0}),y=await Fe({projectRoot:n,epicId:m,storyId:r.storyId,executionBranch:p,epicHead:pe,tip:r.tip,conflictPaths:r.conflictPaths,integratedAt:T,chain:X(s,m).filter(I=>I.storyId===r.storyId).sort((I,O)=>O.integrationIndex-I.integrationIndex),lockHeld:!0});y.ok||i(y.reasonCode),L.set(r.storyId,Object.freeze({storyId:r.storyId,outcome:"conflict-reopened",receiptDigest:y.value.receiptDigest,reasonCode:"integration-conflict-reopened",conflictPaths:Object.freeze([...r.conflictPaths])}))}for(const r of oe){if(!r.leaseId)continue;const s=await qe(n,r.leaseId,r.sha);L.set(r.storyId,Object.freeze({...L.get(r.storyId),worktreeRealigned:s}))}return S({outcome:ye!==void 0?"gate-failed":U?"conflict-truncated":"integrated",integratedStoryIds:Object.freeze(Xe),...ye!==void 0?{failedStoryId:k[ye].storyId,failureReasonCode:we}:{},epicHeadBeforeSha:v,epicHeadAfterSha:pe,qaCoverage:Ve,gateRunCap:K})}catch(f){let g=f instanceof De?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(l){const u=l,d=(await P(n,["rev-parse",u.epicRef])).stdout.trim(),b=(await P(n,["rev-parse","HEAD"])).stdout.trim();d!==u.base&&(d!==b||!u.owned.has(d)||!await C(n,["reset","--keep",u.base]))&&(g="story-worktree-wave-restore-failed")}return{ok:!1,reasonCode:g,gateRuns:o}}finally{if(t?.ok&&await We(t.path,t.owner).catch(()=>{}),a&&c){const f=a;await ue(n,g=>{const u=Ee(g,c),d=u.branch_lease;d&&d.sessionId===f.sessionId&&d.idempotencyKey===f.idempotencyKey&&d.acquiredAt===f.acquiredAt&&(u.branch_lease=null)}).catch(()=>{})}}}async function gr(e){const t=e.integrationOrder;if(!Array.isArray(t)||t.length===0||new Set(t).size!==t.length||t.some(g=>typeof g!="string"||!Ce.test(g)))return{results:[],integratedStoryIds:[],reasonCode:"story-worktree-integration-order-invalid"};const a=e.integrate??qt,c=new Set(e.readyStoryIds),o=xe(e.projectRoot);let l;try{const g=await V(o,{required:!0}),u=new Set(t.map(d=>d.split(".")[0]));l=new Set([...u].flatMap(d=>X(g,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 g of t){if(l.has(g))continue;if(!c.has(g))return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"story-worktree-integration-waiting"};const{integrationOrder:u,readyStoryIds:d,integrate:b,...m}=e,p=await a({...m,projectRoot:o,storyId:g});if(n.push({storyId:g,result:p}),!p.ok)return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:p.reasonCode};if(p.value.outcome==="conflict-reopened")return{results:n,integratedStoryIds:f,stoppedAt:g,reasonCode:"integration-conflict-reopened"};f.push(g),l.add(g)}return{results:n,integratedStoryIds:f}}async function lr(e){const t=xe(e.projectRoot),a=e.manager??new _e({projectRoot:t});let c;try{c=await V(t,{required:!0})}catch{return e.directives.map(()=>({storyId:"",ok:!1,reasonCode:"story-worktree-sync-evidence-invalid"}))}const o=[];for(const l of e.directives){const n=l&&typeof l=="object"&&!Array.isArray(l)?l:void 0,f=typeof n?.storyId=="string"&&Ce.test(n.storyId)?n.storyId:"";if(!f){o.push({storyId:"",ok:!1,reasonCode:"story-worktree-directive-invalid"});continue}const g=Object.values(c.storyWorktrees?.entries??{}).filter(d=>d.storyId===f&&d.state==="active");if(g.length!==1){o.push({storyId:f,ok:!1,reasonCode:g.length===0?"story-worktree-lease-missing":"story-worktree-lease-ambiguous"});continue}const u=await a.sync({leaseId:g[0].leaseId,directive:l});o.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 o}export{jt as STORY_WORKTREE_INTEGRATION_MAX_CONFLICT_PATHS,zt as STORY_WORKTREE_INTEGRATION_RECEIPT_DIGEST_DOMAIN,Le as STORY_WORKTREE_STATE_JSON_PATH,Ke as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PATHS,Ut as STORY_WORKTREE_WAVE_BUILD_OUTPUT_PROJECT,Jt as STORY_WORKTREE_WAVE_MAX_STORIES,ze as digestStoryWorktreeIntegrationReceipt,qt as integrateStoryWorktree,fr as integrateStoryWorktreeWave,gr as integrateStoryWorktreesInOrder,Kt as resolveStoryWorktreeStateJsonMerge,Xt as storyWorktreeWaveBuildOutputPaths,Qt as storyWorktreeWaveGateRunCap,lr as syncReleasedDependents};
@@ -192,9 +192,20 @@ export declare class StoryWorktreeManager {
192
192
  status(input: {
193
193
  readonly leaseId?: string;
194
194
  readonly epicId?: string;
195
+ readonly storyId?: string;
195
196
  }): Promise<StoryWorktreeResult<{
196
197
  readonly entries: readonly StoryWorktreeStatusValue[];
197
198
  }>>;
199
+ /**
200
+ * P230.03 (AC2, REQ-06): proof that a phase-2 child runs inside its own
201
+ * story worktree. The main worktree (first `worktree list` entry) refuses
202
+ * with `story-worktree-phase-two-root-checkout`; any other checkout that is
203
+ * not the active, owned worktree of the story refuses with
204
+ * `story-worktree-phase-two-lease-mismatch`. Read-only; path-free output.
205
+ */
206
+ assertPhaseTwo(input: {
207
+ readonly storyId: string;
208
+ }): Promise<StoryWorktreeResult<StoryWorktreeStatusValue>>;
198
209
  release(input: {
199
210
  readonly leaseId: string;
200
211
  }): Promise<StoryWorktreeResult<StoryWorktreeReleaseValue>>;
@@ -232,8 +243,36 @@ export declare class StoryWorktreeManager {
232
243
  private enableWindowsLongPaths;
233
244
  private ownershipProven;
234
245
  private ownedEntry;
246
+ /**
247
+ * P229.08 REQ-01 (P229-EX-05): committed bytes of the claims sidecar when the
248
+ * worktree's only difference is a reconciled sidecar, i.e. exactly one status
249
+ * entry ` M .neocortex/pending-epic-claims.json`, a regular file whose valid
250
+ * document keeps a strict subset of the committed operations with identical
251
+ * values (claim acknowledgement only removes entries). Anything else,
252
+ * including an untracked sidecar, a symlink or a merge in progress, is
253
+ * `undefined` so the caller keeps `native-worktree-dirty`. Never writes.
254
+ */
255
+ private reconciledClaimsSidecar;
256
+ /** Atomic restore of the committed sidecar bytes (temp file + rename, same directory). */
257
+ private restoreClaimsSidecar;
258
+ /**
259
+ * P229.08 REQ-05 (P229-EX-07): the epic's planning document exists in
260
+ * `probeRev` but not in the authorized base, so the epic branch was born
261
+ * before its planning commit. Only an existing base commit is probed.
262
+ */
263
+ private planningMissingFromBase;
264
+ /** Refuses `create`/`adopt` before any write when the root checkout's planning is not in the base. */
265
+ private assertPlanningInBase;
266
+ /**
267
+ * P229.08 REQ-05: a HEAD that is not an ancestor of the base and whose own
268
+ * commits (`merge-base..HEAD`) touch only this epic's planning artifacts,
269
+ * which the base lacks. Any Git failure or other path keeps the generic code.
270
+ */
271
+ private planningOnlyDrift;
235
272
  private clean;
236
273
  private project;
274
+ /** P230.09: bind the returned lease into the epic evidence; typed refusal on conflict. */
275
+ private bindLeaseEvidence;
237
276
  private leaseValue;
238
277
  /**
239
278
  * DEC-05 (P227.10 D-001): make `@neocortex/shared` resolve to the worktree's
@@ -1,3 +1,3 @@
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};
1
+ import{execFile as ee}from"node:child_process";import{createHash as te,randomBytes as re}from"node:crypto";import{chmod as ae,lstat as x,readFile as C,realpath as b,rename as se,unlink as B,writeFile as W}from"node:fs/promises";import{homedir as oe}from"node:os";import{isAbsolute as H,join as P,resolve as ie}from"node:path";import{isDeepStrictEqual as ne}from"node:util";import{yoloopDomainHash as ce}from"../../../shared/dist/yoloop/canonical.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as de,bindStoryWorktreeLeaseEvidence as he,compactStoryWorktreeJournal as le,ensureStoryWorktreeJournal as D,isStoryWorktreeCleanupReceiptRecord as fe,mutateGitLifecycleRuntime as we,readGitLifecycleRuntime as ue}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as pe,ensurePrivateStoryWorktreeRoot as me,ensureStoryWorktreeSharedResolution as ye,resolveStoryWorktreePath as N,resolveStoryWorktreeRoot as ke,storyWorktreeIdentity as ge}from"./story-worktree-paths.js";const T="nx-owner",ve="neocortex.p225.story-worktree-receipt.v1";function L(n){return ce(ve,n)}const z=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),Ie=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,$=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Re=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function be(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==z.length||!r.every(a=>z.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&q.test(e.directiveId)&&typeof e.epicId=="string"&&F.test(e.epicId)&&typeof e.storyId=="string"&&$.test(e.storyId)&&typeof e.releasedStepId=="string"&&Ie.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&$.test(a))&&typeof e.integratedEpicHeadSha=="string"&&A.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&G.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Re.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const V=1440*60*1e3,Se=3e4,Ee=200,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,G=/^[a-f0-9]{64}$/,j=/^swt-[a-f0-9]{24}$/,q=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,F=/^P[1-9][0-9]*$/,Pe=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,_=".neocortex/pending-epic-claims.json",J=128*1024,De=/^[a-f0-9]{64}$/;function U(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!De.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function Y(n){return`docs/epics/epic-${n}.md`}function Ae(n,e){if(e===Y(n)||e===".neocortex/state.json"||e===_||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class K extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new K(n)}function Oe(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Le(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ee("git",[...e],{cwd:n,encoding:"utf8",env:Oe(),maxBuffer:8*1024*1024,timeout:Se,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function m(n,e){return(await f(n,e)).ok}async function I(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}function O(n){return te("sha256").update(n).digest("hex")}async function xe(n){try{return await x(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function M(n){try{return await x(n),!0}catch{return!1}}function Z(n){return new Promise(e=>setTimeout(e,n))}function X(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function _e(n){return n.length>0&&n.length<=512&&!H(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class ze{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ie(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>re(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=ke({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??oe(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=N({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await me(a.value,this.platform);c.ok||o(c.reasonCode);const i=N({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const h=i.value,l=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(l){if(l.state==="active"&&l.baseSha===e.baseSha&&l.graphRevision===e.graphRevision&&await this.ownershipProven(l,t))return await this.assertNoCleanupInProgress(t,l.leaseId),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};await this.reclaimStaleReservation(l,t)||o("story-worktree-entry-conflict")}await M(h)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const d=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:h,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,d),nonceDigest:O(d),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??V)).toISOString()};await this.mutate(k=>{const y=D(k);(y.entries[w.leaseId]||Object.values(y.entries).some(g=>g.worktreePath===h))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let p=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,h,e.baseSha])||o("story-worktree-add-failed"),p=!0,this.platform!=="win32"?await ae(h,448):await this.enableWindowsLongPaths(t,h);const k=await this.prepareSharedResolution(t,h,e.baseSha),y=await this.worktreeGitDir(h,t);await W(P(y,T),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:d})}
2
+ `,{flag:"wx",mode:384});const g={...w,state:"active"};return await this.mutate(R=>{const v=D(R),S=v.entries[w.leaseId];(!S||S.state!=="creating"||S.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),v.entries[w.leaseId]=g}),{ok:!0,value:{...this.leaseValue(g,!1),sharedResolution:k},privatePath:h}}catch(k){throw await this.rollbackCreate(t,w,p),k}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!H(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(E=>this.samePath(E.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Pe.test(i.branch)||i.branch===s[0]?.branch||await m(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const l=(await this.readDocument()).storyWorktrees?.entries??{},d=l[r.leaseId];if(d){if(this.samePath(d.worktreePath,a)&&d.state==="active"&&await this.ownershipProven(d,t))return(d.graphRevision!==e.graphRevision||d.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await m(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,d.leaseId),await this.mutate(E=>{this.bindLeaseEvidence(E,d)}),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};o("story-worktree-entry-conflict")}Object.values(l).some(E=>this.samePath(E.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let w;await this.clean(a)||(w=await this.reconciledClaimsSidecar(a),w===void 0&&o("native-worktree-dirty"));const p=await I(a,["rev-parse","HEAD"],"story-worktree-git-failed");p!==e.baseSha&&!await m(a,["merge-base","--is-ancestor",p,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,p,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const k=await this.worktreeGitDir(a,t),y=P(k,T),g=await M(y);g&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let R;p!==e.baseSha&&(await this.alignWorktree(a,i.branch,p,e.baseSha),R=Object.freeze({mode:"fast-forward",fromSha:p,toSha:e.baseSha}));const v=P(a,"node_modules","@neocortex","shared"),S=await x(v).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:g,alignment:R})}catch(E){throw!S&&await x(v).then(Q=>Q.isSymbolicLink(),()=>!1)&&await B(v).catch(()=>{}),R&&await this.restoreAlignment(a,i.branch,p,e.baseSha),E}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),c=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!c.ok)&&o("native-worktree-align-failed");const i=c.stdout.split("\0").filter(Boolean).map(d=>d.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(d=>i.some(u=>d===u||d.startsWith(`${u}/`)||u.startsWith(`${d}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await m(e,["update-ref","-m","neocortex: adopt align",`refs/heads/${r}`,a,t])||((await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),o("native-worktree-align-failed")),(await I(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await m(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||o("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:s,temporaryBranch:c,markerPath:i,orphanMarker:h,alignment:l}=e,d=await this.prepareSharedResolution(r,s,a.baseSha);h&&await B(i);const u=this.randomNonce(),w=this.now(),p={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:O(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:c,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:O(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??V)).toISOString()};await W(i,`${JSON.stringify({schemaVersion:1,leaseId:p.leaseId,nonce:u})}
3
+ `,{flag:"wx",mode:384});try{await this.mutate(y=>{const g=D(y);(g.entries[p.leaseId]||Object.values(g.entries).some(R=>this.samePath(R.worktreePath,s)))&&o("story-worktree-entry-conflict"),g.entries[p.leaseId]=p,this.bindLeaseEvidence(y,p)})}catch(y){throw await this.removeOwnMarker(i,u),y}const k={...this.leaseValue(p,!1),sharedResolution:d};return{ok:!0,value:l?{...k,alignment:l}:k,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const h=e.directive;(!be(e.directive)||h.epicId!==t.epicId||h.storyId!==t.storyId||a!==void 0&&a!==h.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(h.integratedEpicHeadSha)}(typeof a!="string"||!A.test(a))&&o("story-worktree-sync-sha-invalid"),await this.clean(t.worktreePath)||o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(!await m(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const d=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(_e).sort().slice(0,Ee);return d.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}c="synced"}const i=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return await this.mutate(h=>{const l=D(h),d=l.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),l.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!j.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!F.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!$.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await I(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await I(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await m(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await m(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,h=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${h}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:h};return fe(l)||o("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=D(d),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...l});u.cleanupReceipts.length>de;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:l,receiptDigest:L(l)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((v,S)=>S>0&&this.samePath(v.path,t.worktreePath)),c=a.some(v=>v.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),h=i.ok&&A.test(i.stdout.trim())?i.stdout.trim():void 0,l=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=l.ok&&A.test(l.stdout.trim())?l.stdout.trim():void 0,u=await xe(t.worktreePath),w=u==="present",p=t.state==="active"&&w&&await this.ownershipProven(t,r);let k,y;if(p){const v=await f(t.worktreePath,["rev-parse","HEAD"]);v.ok&&A.test(v.stdout.trim())&&(k=v.stdout.trim()),y=await this.clean(t.worktreePath)}const g=k??(w?void 0:h),R=g&&d?await m(r.mainRoot,["merge-base","--is-ancestor",g,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:p?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...h?{branchSha:h}:{},branchCheckedOut:c,...k?{headSha:k}:{},...y!==void 0?{clean:y}:{},...d?{epicHead:d}:{},...R!==void 0?{integrated:R}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof K)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=ge(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!q.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=X(await I(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!G.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!A.test(t)||!await m(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await m(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return I(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await I(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await I(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=P(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await m(s,c))return;await Z(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await C(P(t,T),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!j.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${_}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=P(e,_);try{const a=await x(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>J)return;const s=await f(e,["show",`HEAD:${_}`]);if(!s.ok||s.stdout.length>J)return;const c=U(JSON.parse(await C(t,"utf8"))),i=U(JSON.parse(s.stdout));if(!c||!i)return;const h=Object.keys(c);return h.length>=Object.keys(i).length||!h.every(l=>Object.hasOwn(i,l)&&ne(c[l],i[l]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=P(e,_),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await x(t)).mode&511;await W(a,r,{encoding:"utf8",flag:"wx",mode:s}),await se(a,t)}catch{await B(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=Y(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(h=>Ae(r,h))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!A.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await m(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{he(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:L(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[pe]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await m(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await ye({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=D(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],le(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await C(e,"utf8")).nonce===r&&await B(e)}catch{}}async listWorktrees(e){const r=X(await I(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await C(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await M(e.worktreePath)&&!await m(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=D(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return ue(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await we(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await Z(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{T as STORY_WORKTREE_MARKER_FILE,ve as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,ze as StoryWorktreeManager,L as digestStoryWorktreeReceiptLocal,X as parseWorktreeList,Le as runStoryWorktreeGit,xe as storyWorktreePathAbsence};