@ornexus/neocortex 4.66.24 → 4.66.26

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 (37) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/invoke.d.ts +12 -2
  7. package/packages/client/dist/commands/invoke.js +97 -97
  8. package/packages/client/dist/continuity/sqlite-store.d.ts +46 -1
  9. package/packages/client/dist/continuity/sqlite-store.js +96 -67
  10. package/packages/client/dist/git/story-worktree-manager.d.ts +2 -0
  11. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  12. package/packages/client/dist/runner/headless/run-yolo.d.ts +4 -0
  13. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  14. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  15. package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
  16. package/packages/client/dist/runner/headless/types.d.ts +6 -0
  17. package/packages/client/dist/runner/headless/types.js +2 -2
  18. package/targets-stubs/antigravity/gemini.md +1 -1
  19. package/targets-stubs/antigravity/neocortex.md +1 -1
  20. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  21. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  22. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  23. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  24. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  25. package/targets-stubs/claude-code/neocortex.md +2 -2
  26. package/targets-stubs/codex/AGENTS.md +1 -1
  27. package/targets-stubs/codex/neocortex.toml +1 -1
  28. package/targets-stubs/cursor/agent.md +2 -2
  29. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  30. package/targets-stubs/gemini-cli/agent.md +2 -2
  31. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  32. package/targets-stubs/grok/SKILL.md +1 -1
  33. package/targets-stubs/kimi/neocortex.md +1 -1
  34. package/targets-stubs/openclaw/SKILL.md +1 -1
  35. package/targets-stubs/opencode/neocortex-root.md +2 -2
  36. package/targets-stubs/opencode/neocortex.md +2 -2
  37. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -148,6 +148,8 @@ export interface RepositoryFacts {
148
148
  }
149
149
  /** Bounded Git execution shared with the P225.06 cleanup module (exit code + stdout only). */
150
150
  export declare function runStoryWorktreeGit(cwd: string, args: readonly string[]): Promise<GitOutcome>;
151
+ /** Use Git's three-way result so an unreadable history cannot look divergent. */
152
+ export declare function storyWorktreeBaseAncestry(cwd: string, baseSha: string, headSha: string): Promise<'contained' | 'divergent' | 'unverified'>;
151
153
  /** P227.07: `lstat`-based absence classification (never follows symlinks). */
152
154
  export declare function storyWorktreePathAbsence(path: string): Promise<StoryWorktreePathAbsence>;
153
155
  export interface PorcelainWorktree {
@@ -1,3 +1,3 @@
1
- import{execFile as ie}from"node:child_process";import{createHash as ne,randomBytes as ce}from"node:crypto";import{chmod as de,lstat as P,mkdir as he,open as le,readFile as A,realpath as b,rename as W,rmdir as fe,unlink as C,writeFile as j}from"node:fs/promises";import{homedir as we}from"node:os";import{isAbsolute as z,join as S,resolve as ue}from"node:path";import{isDeepStrictEqual as pe}from"node:util";import{yoloopDomainHash as q}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as me,STATE_JSON_FIELD_MERGE_MAX_BYTES as ye}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ke,bindStoryWorktreeLeaseEvidence as ge,compactStoryWorktreeJournal as ve,ensureStoryWorktreeJournal as _,isStoryWorktreeCleanupReceiptRecord as Ie,mutateGitLifecycleRuntime as Re,readGitLifecycleRuntime as Se}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as be,ensurePrivateStoryWorktreeRoot as Ee,ensureStoryWorktreeSharedResolution as Pe,resolveStoryWorktreePath as G,resolveStoryWorktreeRoot as Ae,storyWorktreeIdentity as De}from"./story-worktree-paths.js";const H="nx-owner",_e="neocortex.p225.story-worktree-receipt.v1";function F(n){return q(_e,n)}const V=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),xe=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,B=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Oe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function J(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==V.length||!r.every(a=>V.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&K.test(e.directiveId)&&typeof e.epicId=="string"&&X.test(e.epicId)&&typeof e.storyId=="string"&&B.test(e.storyId)&&typeof e.releasedStepId=="string"&&xe.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&B.test(a))&&typeof e.integratedEpicHeadSha=="string"&&x.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&U.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Oe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const Y=1440*60*1e3,Ce="neocortex.p225.two-phase-release-directive-id.v1",T=".neocortex/state.json",M=".story-worktree-sync",Te=3e4,$e=200,x=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,U=/^[a-f0-9]{64}$/,N=/^swt-[a-f0-9]{24}$/,K=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,X=/^P[1-9][0-9]*$/,Be=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",Z=128*1024,We=/^[a-f0-9]{64}$/;function Q(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!We.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function ee(n){return`docs/epics/epic-${n}.md`}function je(n,e){if(e===ee(n)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class te extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new te(n)}function He(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Ze(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ie("git",[...e],{cwd:n,encoding:"utf8",env:He(),maxBuffer:8*1024*1024,timeout:Te,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function p(n,e){return(await f(n,e)).ok}async function R(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}async function re(n,e){return p(n,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function Me(n,e,r){const t=n.worktreePath,a=S(t,T),s=S(t,".neocortex"),c=S(s,M),i=S(c,"original.json"),d=S(c,"merged.json"),h=await P(a).catch(()=>{});if(!h?.isFile()||h.nlink!==1||h.size>ye||await b(a)!==a||!await p(t,["diff","--cached","--quiet"])||await p(t,["diff","--quiet","--",T])||await p(t,["cat-file","-e",`${r}:.neocortex/${M}`])||await R(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[l,u,w]=await Promise.all([f(t,["show",`${e}:${T}`]),f(t,["show",`${r}:${T}`]),f(t,["show","-s","--format=%cI",r])]);if(!l.ok||!u.ok||!w.ok||l.stdout===u.stdout)return!1;const m=await A(a),g=me({base:l.stdout,epic:u.stdout,story:m,storyId:n.storyId,epicId:n.epicId,aggregateTimestamp:w.stdout.trim()});if(g===void 0)return!1;try{await he(c,{mode:448})}catch{return!1}let y=!1,v=!1;try{const I=await le(d,"wx",h.mode&511);try{await I.writeFile(g,"utf8"),await I.sync()}finally{await I.close()}if(!(await A(a)).equals(m))return!1;await W(a,i),y=!0,(!(await A(i)).equals(m)||!await p(t,["checkout-index","--",T]))&&o("story-worktree-sync-state-backup-preserved"),await re(t,r);const k=await R(t,["rev-parse","HEAD"],"story-worktree-git-failed"),E=k===r?u.stdout:k===e?l.stdout:void 0;return(E===void 0||!(await A(a)).equals(Buffer.from(E)))&&o("story-worktree-sync-state-backup-preserved"),await W(k===r?d:i,a),v=!0,k===r}finally{(!y||v)&&(await C(i).catch(()=>{}),await C(d).catch(()=>{}),await fe(c).catch(()=>{}))}}function O(n){return ne("sha256").update(n).digest("hex")}async function Ne(n){try{return await P(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function L(n){try{return await P(n),!0}catch{return!1}}function ae(n){return new Promise(e=>setTimeout(e,n))}function se(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function Le(n){return n.length>0&&n.length<=512&&!z(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class Qe{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ue(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>ce(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=Ae({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??we(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=G({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await Ee(a.value,this.platform);c.ok||o(c.reasonCode);const i=G({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const d=i.value,h=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(h){if(h.state==="active"&&h.baseSha===e.baseSha&&h.graphRevision===e.graphRevision&&await this.ownershipProven(h,t))return await this.assertNoCleanupInProgress(t,h.leaseId),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};await this.reclaimStaleReservation(h,t)||o("story-worktree-entry-conflict")}await L(d)&&o("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const l=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:d,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,l),nonceDigest:O(l),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??Y)).toISOString()};await this.mutate(g=>{const y=_(g);(y.entries[w.leaseId]||Object.values(y.entries).some(v=>v.worktreePath===d))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let m=!1;try{await p(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha])||o("story-worktree-add-failed"),m=!0,this.platform!=="win32"?await de(d,448):await this.enableWindowsLongPaths(t,d);const g=await this.prepareSharedResolution(t,d,e.baseSha),y=await this.worktreeGitDir(d,t);await j(S(y,H),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:l})}
2
- `,{flag:"wx",mode:384});const v={...w,state:"active"};return await this.mutate(I=>{const k=_(I),E=k.entries[w.leaseId];(!E||E.state!=="creating"||E.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),k.entries[w.leaseId]=v}),{ok:!0,value:{...this.leaseValue(v,!1),sharedResolution:g},privatePath:d}}catch(g){throw await this.rollbackCreate(t,w,m),g}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!z(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(D=>this.samePath(D.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Be.test(i.branch)||i.branch===s[0]?.branch||await p(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const h=(await this.readDocument()).storyWorktrees?.entries??{},l=h[r.leaseId];if(l){if(this.samePath(l.worktreePath,a)&&l.state==="active"&&await this.ownershipProven(l,t))return(l.graphRevision!==e.graphRevision||l.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await p(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,l.leaseId),await this.mutate(D=>{this.bindLeaseEvidence(D,l)}),{ok:!0,value:this.leaseValue(l,!0),privatePath:l.worktreePath};o("story-worktree-entry-conflict")}Object.values(h).some(D=>this.samePath(D.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let w;await this.clean(a)||(w=await this.reconciledClaimsSidecar(a),w===void 0&&o("native-worktree-dirty"));const m=await R(a,["rev-parse","HEAD"],"story-worktree-git-failed");m!==e.baseSha&&!await p(a,["merge-base","--is-ancestor",m,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,m,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const g=await this.worktreeGitDir(a,t),y=S(g,H),v=await L(y);v&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let I;m!==e.baseSha&&(await this.alignWorktree(a,i.branch,m,e.baseSha),I=Object.freeze({mode:"fast-forward",fromSha:m,toSha:e.baseSha}));const k=S(a,"node_modules","@neocortex","shared"),E=await P(k).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:v,alignment:I})}catch(D){throw!E&&await P(k).then(oe=>oe.isSymbolicLink(),()=>!1)&&await C(k).catch(()=>{}),I&&await this.restoreAlignment(a,i.branch,m,e.baseSha),D}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),c=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!c.ok)&&o("native-worktree-align-failed");const i=c.stdout.split("\0").filter(Boolean).map(l=>l.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(l=>i.some(u=>l===u||l.startsWith(`${u}/`)||u.startsWith(`${l}/`)))&&o("native-worktree-align-failed"),(await f(e,["read-tree","-m","-u",t,a])).ok||o("native-worktree-align-failed"),await p(e,["update-ref","-m","neocortex: adopt align",`refs/heads/${r}`,a,t])||((await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),o("native-worktree-align-failed")),(await R(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await p(e,["update-ref","-m","neocortex: adopt align rollback",`refs/heads/${r}`,t,a])||o("native-worktree-align-restore-failed")}async adoptAligned(e){const{facts:r,identity:t,input:a,canonical:s,temporaryBranch:c,markerPath:i,orphanMarker:d,alignment:h}=e,l=await this.prepareSharedResolution(r,s,a.baseSha);d&&await C(i);const u=this.randomNonce(),w=this.now(),m={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:O(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:c,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,u),nonceDigest:O(u),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:w.toISOString(),expiresAt:new Date(w.getTime()+(this.options.ttlMs??Y)).toISOString()};await j(i,`${JSON.stringify({schemaVersion:1,leaseId:m.leaseId,nonce:u})}
3
- `,{flag:"wx",mode:384});try{await this.mutate(y=>{const v=_(y);(v.entries[m.leaseId]||Object.values(v.entries).some(I=>this.samePath(I.worktreePath,s)))&&o("story-worktree-entry-conflict"),v.entries[m.leaseId]=m,this.bindLeaseEvidence(y,m)})}catch(y){throw await this.removeOwnMarker(i,u),y}const g={...this.leaseValue(m,!1),sharedResolution:l};return{ok:!0,value:h?{...g,alignment:h}:g,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const d=e.directive;(!J(e.directive)||d.epicId!==t.epicId||d.storyId!==t.storyId||a!==void 0&&a!==d.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(d.integratedEpicHeadSha)}if(e.automatic){const d=e.directive;(!J(d)||d.graphRevision!==t.graphRevision||Array.isArray(d.dependsOn)&&d.dependsOn.includes(t.storyId)||d.directiveId!==q(Ce,{epicId:d.epicId,storyId:d.storyId,dependsOn:d.dependsOn,integratedEpicHeadSha:d.integratedEpicHeadSha,graphRevision:d.graphRevision}))&&o("story-worktree-directive-invalid");const h=await this.assertPhaseTwo({storyId:t.storyId});(!h.ok||h.value.leaseId!==t.leaseId)&&o("story-worktree-phase-two-lease-mismatch")}(typeof a!="string"||!x.test(a))&&o("story-worktree-sync-sha-invalid"),!e.automatic&&!await this.clean(t.worktreePath)&&o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(e.automatic){await P(S(t.worktreePath,".neocortex",M)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const d=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");d!==a&&(await p(t.worktreePath,["merge-base","--is-ancestor",d,a])||o("story-worktree-sync-not-fast-forward"),!await re(t.worktreePath,a)&&!await Me(t,d,a)&&o("story-worktree-sync-conflict-preserved"),c="synced")}if(!e.automatic&&!await p(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const l=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(Le).sort().slice(0,$e);return l.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:l}}c="synced"}const i=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&i!==a&&o("story-worktree-sync-head-raced"),await this.mutate(d=>{const h=_(d),l=h.entries[t.leaseId];(!l||l.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),h.entries[t.leaseId]={...l,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!N.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!X.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await R(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-not-integrated"),await p(r.mainRoot,["worktree","remove",t.worktreePath])||o("story-worktree-remove-failed"),await f(r.mainRoot,["worktree","prune"]);let c;t.workspaceMechanism==="native_subagent_worktree"?c="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(c="story-worktree-branch-moved");const i=c===void 0,d=this.now().toISOString(),h={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${d}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:d};return Ie(h)||o("story-worktree-receipt-invalid"),await this.mutate(l=>{const u=_(l),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...h});u.cleanupReceipts.length>ke;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:h,receiptDigest:F(h)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((k,E)=>E>0&&this.samePath(k.path,t.worktreePath)),c=a.some(k=>k.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),d=i.ok&&x.test(i.stdout.trim())?i.stdout.trim():void 0,h=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),l=h.ok&&x.test(h.stdout.trim())?h.stdout.trim():void 0,u=await Ne(t.worktreePath),w=u==="present",m=t.state==="active"&&w&&await this.ownershipProven(t,r);let g,y;if(m){const k=await f(t.worktreePath,["rev-parse","HEAD"]);k.ok&&x.test(k.stdout.trim())&&(g=k.stdout.trim()),y=await this.clean(t.worktreePath)}const v=g??(w?void 0:d),I=v&&l?await p(r.mainRoot,["merge-base","--is-ancestor",v,l]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:m?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...d?{branchSha:d}:{},branchCheckedOut:c,...g?{headSha:g}:{},...y!==void 0?{clean:y}:{},...l?{epicHead:l}:{},...I!==void 0?{integrated:I}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof te)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=De(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!K.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=se(await R(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!U.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!x.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r);await p(e.mainRoot,["merge-base","--is-ancestor",t,s])||o("story-worktree-base-divergent")}async epicHead(e,r){return R(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await R(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=S(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await p(s,c))return;await ae(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await A(S(t,H),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${$}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=S(e,$);try{const a=await P(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>Z)return;const s=await f(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>Z)return;const c=Q(JSON.parse(await A(t,"utf8"))),i=Q(JSON.parse(s.stdout));if(!c||!i)return;const d=Object.keys(c);return d.length>=Object.keys(i).length||!d.every(h=>Object.hasOwn(i,h)&&pe(c[h],i[h]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=S(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await P(t)).mode&511;await j(a,r,{encoding:"utf8",flag:"wx",mode:s}),await W(a,t)}catch{await C(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=ee(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(d=>je(r,d))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!x.test(s))return{...t,ownership:"proven"};const c=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),i=c.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",s,c.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:i}}bindLeaseEvidence(e,r){try{ge(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:F(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[be]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await p(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await Pe({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=_(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ve(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await A(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=se(await R(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await A(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await L(e.worktreePath)&&!await p(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=_(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return Se(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await Re(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await ae(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{H as STORY_WORKTREE_MARKER_FILE,_e as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,Qe as StoryWorktreeManager,F as digestStoryWorktreeReceiptLocal,se as parseWorktreeList,Ze as runStoryWorktreeGit,Ne as storyWorktreePathAbsence};
1
+ import{execFile as ie}from"node:child_process";import{createHash as ne,randomBytes as ce}from"node:crypto";import{chmod as de,lstat as A,mkdir as le,open as he,readFile as D,realpath as b,rename as W,rmdir as fe,unlink as C,writeFile as j}from"node:fs/promises";import{homedir as we}from"node:os";import{isAbsolute as z,join as S,resolve as ue}from"node:path";import{isDeepStrictEqual as pe}from"node:util";import{yoloopDomainHash as q}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as me,STATE_JSON_FIELD_MERGE_MAX_BYTES as ye}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ke,bindStoryWorktreeLeaseEvidence as ge,compactStoryWorktreeJournal as ve,ensureStoryWorktreeJournal as _,isStoryWorktreeCleanupReceiptRecord as Ie,mutateGitLifecycleRuntime as Re,readGitLifecycleRuntime as Se}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as be,ensurePrivateStoryWorktreeRoot as Ee,ensureStoryWorktreeSharedResolution as Pe,resolveStoryWorktreePath as G,resolveStoryWorktreeRoot as Ae,storyWorktreeIdentity as De}from"./story-worktree-paths.js";const H="nx-owner",xe="neocortex.p225.story-worktree-receipt.v1";function F(n){return q(xe,n)}const V=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),_e=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,B=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Oe=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function J(n){if(n===null||typeof n!="object"||Array.isArray(n))return!1;const e=n,r=Object.keys(e);if(r.length!==V.length||!r.every(a=>V.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&K.test(e.directiveId)&&typeof e.epicId=="string"&&X.test(e.epicId)&&typeof e.storyId=="string"&&B.test(e.storyId)&&typeof e.releasedStepId=="string"&&_e.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&B.test(a))&&typeof e.integratedEpicHeadSha=="string"&&P.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&U.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Oe.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const Y=1440*60*1e3,Ce="neocortex.p225.two-phase-release-directive-id.v1",T=".neocortex/state.json",M=".story-worktree-sync",Te=3e4,$e=200,P=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,U=/^[a-f0-9]{64}$/,N=/^swt-[a-f0-9]{24}$/,K=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,X=/^P[1-9][0-9]*$/,Be=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",Z=128*1024,We=/^[a-f0-9]{64}$/;function Q(n){if(!n||typeof n!="object"||Array.isArray(n))return;const e=n;if(Object.keys(e).length!==2||e.schemaVersion!==1)return;const t=e.operations;if(!(!t||typeof t!="object"||Array.isArray(t))){for(const[a,s]of Object.entries(t))if(!We.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function ee(n){return`docs/epics/epic-${n}.md`}function je(n,e){if(e===ee(n)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${n}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${n}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class te extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(n){throw new te(n)}function He(){const n={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete n[e];return n.GIT_TERMINAL_PROMPT="0",n}function Qe(n,e){return f(n,e)}function f(n,e){return new Promise(r=>{ie("git",[...e],{cwd:n,encoding:"utf8",env:He(),maxBuffer:8*1024*1024,timeout:Te,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function m(n,e){return(await f(n,e)).ok}async function Me(n,e,r){if(!P.test(e)||!P.test(r))return"unverified";const t=await f(n,["merge-base","--is-ancestor",e,r]);if(t.ok)return"contained";if(t.exitCode!==1)return"unverified";const a=await f(n,["rev-parse","--is-shallow-repository"]);return a.ok&&a.stdout.trim()==="false"?"divergent":"unverified"}async function R(n,e,r){const t=await f(n,e);return t.ok||o(r),t.stdout.trim()}async function re(n,e){return m(n,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function Ne(n,e,r){const t=n.worktreePath,a=S(t,T),s=S(t,".neocortex"),c=S(s,M),i=S(c,"original.json"),d=S(c,"merged.json"),l=await A(a).catch(()=>{});if(!l?.isFile()||l.nlink!==1||l.size>ye||await b(a)!==a||!await m(t,["diff","--cached","--quiet"])||await m(t,["diff","--quiet","--",T])||await m(t,["cat-file","-e",`${r}:.neocortex/${M}`])||await R(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[h,u,w]=await Promise.all([f(t,["show",`${e}:${T}`]),f(t,["show",`${r}:${T}`]),f(t,["show","-s","--format=%cI",r])]);if(!h.ok||!u.ok||!w.ok||h.stdout===u.stdout)return!1;const p=await D(a),g=me({base:h.stdout,epic:u.stdout,story:p,storyId:n.storyId,epicId:n.epicId,aggregateTimestamp:w.stdout.trim()});if(g===void 0)return!1;try{await le(c,{mode:448})}catch{return!1}let y=!1,v=!1;try{const I=await he(d,"wx",l.mode&511);try{await I.writeFile(g,"utf8"),await I.sync()}finally{await I.close()}if(!(await D(a)).equals(p))return!1;await W(a,i),y=!0,(!(await D(i)).equals(p)||!await m(t,["checkout-index","--",T]))&&o("story-worktree-sync-state-backup-preserved"),await re(t,r);const k=await R(t,["rev-parse","HEAD"],"story-worktree-git-failed"),E=k===r?u.stdout:k===e?h.stdout:void 0;return(E===void 0||!(await D(a)).equals(Buffer.from(E)))&&o("story-worktree-sync-state-backup-preserved"),await W(k===r?d:i,a),v=!0,k===r}finally{(!y||v)&&(await C(i).catch(()=>{}),await C(d).catch(()=>{}),await fe(c).catch(()=>{}))}}function O(n){return ne("sha256").update(n).digest("hex")}async function Le(n){try{return await A(n),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function L(n){try{return await A(n),!0}catch{return!1}}function ae(n){return new Promise(e=>setTimeout(e,n))}function se(n){const e=[];for(const r of n.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(i=>i.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(i=>i.startsWith("HEAD "))?.slice(5),c=t.find(i=>i.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...c?.startsWith("refs/heads/")?{branch:c.slice(11)}:{}})}return e}function ze(n){return n.length>0&&n.length<=512&&!z(n)&&!/^[A-Za-z]:/.test(n)&&!n.includes("\\")&&!n.split("/").some(e=>e===".."||e==="")}class et{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ue(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>ce(32).toString("hex")),this.platform=e.platform??process.platform}async create(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const a=Ae({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??we(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});a.ok||o(a.reasonCode);const s=G({root:a.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});s.ok||o(s.reasonCode);const c=await Ee(a.value,this.platform);c.ok||o(c.reasonCode);const i=G({root:await b(a.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});i.ok||o(i.reasonCode);const d=i.value,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 L(d)&&o("story-worktree-path-occupied"),await m(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const h=this.randomNonce(),u=this.now(),w={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:O(r.dispatchId),hash8:r.hash8,executionBranch:r.executionBranch,temporaryBranch:r.temporaryBranch,worktreeRef:r.worktreeRef,worktreePath:d,workspaceMechanism:"client_managed_worktree",ownerId:this.ownerId(e.ownerId,h),nonceDigest:O(h),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:u.toISOString(),expiresAt:new Date(u.getTime()+(this.options.ttlMs??Y)).toISOString()};await this.mutate(g=>{const y=_(g);(y.entries[w.leaseId]||Object.values(y.entries).some(v=>v.worktreePath===d))&&o("story-worktree-entry-conflict"),y.entries[w.leaseId]=w});let p=!1;try{await m(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha])||o("story-worktree-add-failed"),p=!0,this.platform!=="win32"?await de(d,448):await this.enableWindowsLongPaths(t,d);const g=await this.prepareSharedResolution(t,d,e.baseSha),y=await this.worktreeGitDir(d,t);await j(S(y,H),`${JSON.stringify({schemaVersion:1,leaseId:w.leaseId,nonce:h})}
2
+ `,{flag:"wx",mode:384});const v={...w,state:"active"};return await this.mutate(I=>{const k=_(I),E=k.entries[w.leaseId];(!E||E.state!=="creating"||E.nonceDigest!==w.nonceDigest)&&o("story-worktree-entry-conflict"),k.entries[w.leaseId]=v}),{ok:!0,value:{...this.leaseValue(v,!1),sharedResolution:g},privatePath:d}}catch(g){throw await this.rollbackCreate(t,w,p),g}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),(typeof e.worktreePath!="string"||!z(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await b(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),c=s.findIndex(x=>this.samePath(x.path,a));c===0&&o("story-worktree-adopt-main-refused"),c<0&&o("story-worktree-adopt-unregistered");const i=s[c];i.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(i.branch)||i.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Be.test(i.branch)||i.branch===s[0]?.branch||await m(t.mainRoot,["config","--get",`branch.${i.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const l=(await this.readDocument()).storyWorktrees?.entries??{},h=l[r.leaseId];if(h){if(this.samePath(h.worktreePath,a)&&h.state==="active"&&await this.ownershipProven(h,t))return(h.graphRevision!==e.graphRevision||h.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,h.leaseId),await this.mutate(x=>{this.bindLeaseEvidence(x,h)}),{ok:!0,value:this.leaseValue(h,!0),privatePath:h.worktreePath};o("story-worktree-entry-conflict")}Object.values(l).some(x=>this.samePath(x.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 R(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 g=await this.worktreeGitDir(a,t),y=S(g,H),v=await L(y);v&&await this.markerLeaseId(y)!==r.leaseId&&o("story-worktree-marker-exists"),w!==void 0&&(await this.restoreClaimsSidecar(a,w),await this.clean(a)||o("native-worktree-dirty"));let I;p!==e.baseSha&&(await this.alignWorktree(a,i.branch,p,e.baseSha),I=Object.freeze({mode:"fast-forward",fromSha:p,toSha:e.baseSha}));const k=S(a,"node_modules","@neocortex","shared"),E=await A(k).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:i.branch,markerPath:y,orphanMarker:v,alignment:I})}catch(x){throw!E&&await A(k).then(oe=>oe.isSymbolicLink(),()=>!1)&&await C(k).catch(()=>{}),I&&await this.restoreAlignment(a,i.branch,p,e.baseSha),x}})}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(h=>h.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(h=>i.some(u=>h===u||h.startsWith(`${u}/`)||u.startsWith(`${h}/`)))&&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 R(e,["rev-parse","HEAD"],"story-worktree-git-failed")!==a||!await this.clean(e))&&(await this.restoreAlignment(e,r,t,a),o("native-worktree-align-failed"))}async restoreAlignment(e,r,t,a){(await f(e,["read-tree","-m","-u",a,t])).ok||o("native-worktree-align-restore-failed"),await 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:d,alignment:l}=e,h=await this.prepareSharedResolution(r,s,a.baseSha);d&&await C(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??Y)).toISOString()};await j(i,`${JSON.stringify({schemaVersion:1,leaseId:p.leaseId,nonce:u})}
3
+ `,{flag:"wx",mode:384});try{await this.mutate(y=>{const v=_(y);(v.entries[p.leaseId]||Object.values(v.entries).some(I=>this.samePath(I.worktreePath,s)))&&o("story-worktree-entry-conflict"),v.entries[p.leaseId]=p,this.bindLeaseEvidence(y,p)})}catch(y){throw await this.removeOwnMarker(i,u),y}const g={...this.leaseValue(p,!1),sharedResolution:h};return{ok:!0,value:l?{...g,alignment:l}:g,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const d=e.directive;(!J(e.directive)||d.epicId!==t.epicId||d.storyId!==t.storyId||a!==void 0&&a!==d.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(d.integratedEpicHeadSha)}if(e.automatic){const d=e.directive;(!J(d)||d.graphRevision!==t.graphRevision||Array.isArray(d.dependsOn)&&d.dependsOn.includes(t.storyId)||d.directiveId!==q(Ce,{epicId:d.epicId,storyId:d.storyId,dependsOn:d.dependsOn,integratedEpicHeadSha:d.integratedEpicHeadSha,graphRevision:d.graphRevision}))&&o("story-worktree-directive-invalid");const l=await this.assertPhaseTwo({storyId:t.storyId});(!l.ok||l.value.leaseId!==t.leaseId)&&o("story-worktree-phase-two-lease-mismatch")}(typeof a!="string"||!P.test(a))&&o("story-worktree-sync-sha-invalid"),!e.automatic&&!await this.clean(t.worktreePath)&&o("story-worktree-dirty");const s=await this.epicHead(r,t.executionBranch);await m(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let c="already-synced";if(e.automatic){await A(S(t.worktreePath,".neocortex",M)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const d=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");d!==a&&(await m(t.worktreePath,["merge-base","--is-ancestor",d,a])||o("story-worktree-sync-not-fast-forward"),!await re(t.worktreePath,a)&&!await Ne(t,d,a)&&o("story-worktree-sync-conflict-preserved"),c="synced")}if(!e.automatic&&!await m(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await f(t.worktreePath,["merge","--no-edit",a])).ok){const h=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(ze).sort().slice(0,$e);return h.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:h}}c="synced"}const i=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&i!==a&&o("story-worktree-sync-head-raced"),await this.mutate(d=>{const l=_(d),h=l.entries[t.leaseId];(!h||h.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),l.entries[t.leaseId]={...h,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:c,integratedSha:a,headSha:i}}})}async status(e){return this.guard(async()=>{[e.leaseId,e.epicId,e.storyId].filter(s=>s!==void 0).length!==1&&o("story-worktree-status-selector-invalid"),e.leaseId!==void 0&&!N.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!X.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository(),t=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>e.leaseId?s.leaseId===e.leaseId:e.storyId?s.storyId===e.storyId:s.epicId===e.epicId).sort((s,c)=>s.leaseId.localeCompare(c.leaseId));e.leaseId&&t.length===0&&o("story-worktree-lease-unknown");const a=[];for(const s of t)a.push(await this.project(s,r));return{ok:!0,value:{entries:a}}})}async assertPhaseTwo(e){return this.guard(async()=>{(typeof e.storyId!="string"||!B.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await b(await R(this.projectRoot,["rev-parse","--show-toplevel"],"story-worktree-project-root-invalid"))}catch{o("story-worktree-project-root-invalid")}this.samePath(t,r.mainRoot)&&o("story-worktree-phase-two-root-checkout");const a=Object.values((await this.readDocument()).storyWorktrees?.entries??{}).filter(s=>s.storyId===e.storyId&&s.state==="active"&&this.samePath(s.worktreePath,t));return(a.length!==1||!await this.ownershipProven(a[0],r))&&o("story-worktree-phase-two-lease-mismatch"),{ok:!0,value:await this.project(a[0],r)}})}async release(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);await this.clean(t.worktreePath)||o("story-worktree-dirty");const a=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed"),s=await this.epicHead(r,t.executionBranch);await 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,d=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${d}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:i,remoteBranchRemoved:!1,...c?{preservedReasonCode:c}:{},cleanedAt:d};return Ie(l)||o("story-worktree-receipt-invalid"),await this.mutate(h=>{const u=_(h),w=u.entries[t.leaseId];for(w&&w.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...l});u.cleanupReceipts.length>ke;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:l,receiptDigest:F(l)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const r=await this.repository(),t=(await this.readDocument()).storyWorktrees?.entries[e];t||o("story-worktree-lease-unknown");const a=await this.listWorktrees(r),s=a.some((k,E)=>E>0&&this.samePath(k.path,t.worktreePath)),c=a.some(k=>k.branch===t.temporaryBranch),i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),d=i.ok&&P.test(i.stdout.trim())?i.stdout.trim():void 0,l=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),h=l.ok&&P.test(l.stdout.trim())?l.stdout.trim():void 0,u=await Le(t.worktreePath),w=u==="present",p=t.state==="active"&&w&&await this.ownershipProven(t,r);let g,y;if(p){const k=await f(t.worktreePath,["rev-parse","HEAD"]);k.ok&&P.test(k.stdout.trim())&&(g=k.stdout.trim()),y=await this.clean(t.worktreePath)}const v=g??(w?void 0:d),I=v&&h?await m(r.mainRoot,["merge-base","--is-ancestor",v,h]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:p?"proven":"unproven",pathExists:w,pathAbsence:u,registered:s,...d?{branchSha:d}:{},branchCheckedOut:c,...g?{headSha:g}:{},...y!==void 0?{clean:y}:{},...h?{epicHead:h}:{},...I!==void 0?{integrated:I}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof te)return{ok:!1,reasonCode:r.reasonCode};const t=r instanceof Error?r.message:"";return/^git-lifecycle-[a-z0-9-]{1,80}$/.test(t)?{ok:!1,reasonCode:t}:{ok:!1,reasonCode:"story-worktree-internal-error"}}}identity(e){const r=De(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!K.test(e.ownerId)&&o("story-worktree-owner-invalid"),r.value}async assertNoCleanupInProgress(e,r){const{storyWorktreeCleanupInProgress:t}=await import("./story-worktree-cleanup.js");await t(e.commonDir,r,this.now().getTime())&&o("story-worktree-cleanup-in-progress")}ownerId(e,r){return e??`owner-${O(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await b(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await b(r),s=se(await R(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await b(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!U.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!P.test(t)||!await m(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r),c=await Me(e.mainRoot,t,s);c!=="contained"&&o(c==="divergent"?"story-worktree-base-divergent":"story-worktree-base-unverified")}async epicHead(e,r){return R(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await b(await R(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await b(await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=S(r.commonDir,"worktrees");return(a!==r.commonDir||!t.startsWith(`${s}/`)&&!t.startsWith(`${s}\\`))&&o("story-worktree-foreign-repository"),t}async enableWindowsLongPaths(e,r){const t=async(s,c)=>{for(let i=1;i<=8;i++){if(await m(s,c))return;await ae(25*i)}o("story-worktree-config-failed")},a=await f(e.mainRoot,["config","--get","extensions.worktreeConfig"]);(!a.ok||a.stdout.trim()!=="true")&&await t(e.mainRoot,["config","extensions.worktreeConfig","true"]),await t(r,["config","--worktree","core.longPaths","true"])}async ownershipProven(e,r){try{if(await b(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await D(S(t,H),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||O(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),c=s.findIndex(i=>this.samePath(i.path,e.worktreePath));return c>0&&s[c].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!N.test(e))&&o("story-worktree-lease-invalid");const t=(await this.readDocument()).storyWorktrees?.entries[e];return t||o("story-worktree-lease-unknown"),(t.state!=="active"||!await this.ownershipProven(t,r))&&o("story-worktree-ownership-unproven"),t}async reconciledClaimsSidecar(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${$}\0`||(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=S(e,$);try{const a=await A(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>Z)return;const s=await f(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>Z)return;const c=Q(JSON.parse(await D(t,"utf8"))),i=Q(JSON.parse(s.stdout));if(!c||!i)return;const d=Object.keys(c);return d.length>=Object.keys(i).length||!d.every(l=>Object.hasOwn(i,l)&&pe(c[l],i[l]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=S(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await A(t)).mode&511;await j(a,r,{encoding:"utf8",flag:"wx",mode:s}),await W(a,t)}catch{await C(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=ee(r);return(await f(e,["cat-file","-e",`${t}:${s}`])).ok?!(await f(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await f(e.mainRoot,["rev-parse","--verify","--quiet","HEAD^{commit}"]);a.ok&&await this.planningMissingFromBase(e.mainRoot,r,a.stdout.trim(),t)&&o("epic-planning-not-in-base")}async planningOnlyDrift(e,r,t,a){if(!await this.planningMissingFromBase(e,r,t,a))return!1;const s=await f(e,["merge-base",t,a]);if(!s.ok)return!1;const c=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!c.ok)return!1;const i=c.stdout.split("\0").filter(Boolean);return i.length>0&&i.every(d=>je(r,d))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!P.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{ge(e,this.leaseValue(r,!1).lease)}catch(t){const a=t instanceof Error?t.message:"";o(a==="git-lifecycle-runtime-story-worktree-evidence-conflict"?"story-worktree-lease-evidence-conflict":"story-worktree-lease-evidence-invalid")}}leaseValue(e,r){const t={schemaVersion:1,kind:"story-worktree-lease",leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,executionBranch:e.executionBranch,temporaryBranch:e.temporaryBranch,worktreeRef:e.worktreeRef,workspaceMechanism:e.workspaceMechanism,ownerId:e.ownerId,baseSha:e.baseSha,graphRevision:e.graphRevision,acquiredAt:e.acquiredAt,expiresAt:e.expiresAt},a=`nxwt-${e.hash8}`;return{lease:t,leaseDigest:F(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[be]:a}}}async prepareSharedResolution(e,r,t){const a=await f(r,["show",`${t}:packages/shared/package.json`]);if(!a.ok)return"not-applicable";try{if(JSON.parse(a.stdout)?.name!=="@neocortex/shared")return"not-applicable"}catch{return"not-applicable"}await m(r,["check-ignore","-q","node_modules/@neocortex/shared"])||o("story-worktree-shared-link-not-ignored");const s=await Pe({worktreePath:r,repositoryRoot:e.mainRoot,platform:this.platform});if(s.ok)return s.value;if(s.reasonCode==="story-worktree-shared-build-missing")return"build-missing";o(s.reasonCode)}async rollbackCreate(e,r,t){t&&(await f(e.mainRoot,["worktree","remove",r.worktreePath]),await f(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await f(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const c=_(s),i=c.entries[r.leaseId];i&&i.nonceDigest===r.nonceDigest&&delete c.entries[r.leaseId],ve(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await D(e,"utf8")).nonce===r&&await C(e)}catch{}}async listWorktrees(e){const r=se(await R(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await b(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await D(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await L(e.worktreePath)&&!await m(r.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${e.temporaryBranch}`])))return!1;let a=!1;return await this.mutate(s=>{const c=_(s),i=c.entries[e.leaseId];i&&i.state==="creating"&&i.nonceDigest===e.nonceDigest&&(delete c.entries[e.leaseId],a=!0)}),a}async readDocument(){return Se(this.projectRoot)}async mutate(e){const r=this.options.lockRetry?.attempts??40,t=this.options.lockRetry?.delayMs??25;for(let a=1;;a++)try{await Re(this.projectRoot,e);return}catch(s){if(!(s instanceof Error&&(s.message==="git-lifecycle-runtime-lock-active"||s.code==="ENOENT"&&s.message.includes("runtime.lock")))||a>=r)throw s;await ae(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{H as STORY_WORKTREE_MARKER_FILE,xe as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,et as StoryWorktreeManager,F as digestStoryWorktreeReceiptLocal,se as parseWorktreeList,Qe as runStoryWorktreeGit,Me as storyWorktreeBaseAncestry,Le as storyWorktreePathAbsence};
@@ -40,6 +40,10 @@ export interface RunYoloExecutionPhaseOptions {
40
40
  */
41
41
  readonly storyWorktreeBinding?: {
42
42
  readonly worktreePath: string;
43
+ readonly completion?: {
44
+ readonly attemptId: string;
45
+ readonly digest: string;
46
+ };
43
47
  };
44
48
  }
45
49
  /** P227.23 (M1): public reason code for a phase mode without its worktree binding. */
@@ -1 +1 @@
1
- import{createHash as ee,randomBytes as te}from"node:crypto";import{isAbsolute as re,resolve as A}from"node:path";import{P205_RELEASE_GATE_BUDGETS as oe,P205_ROOT_INVOKE_TIMEOUT_MS as K}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as ae,AUTONOMOUS_GOVERNANCE_REASON_CODES as $,autonomousGovernanceMetadata as H,buildAutonomousGovernanceEnvelope as ne,readAutonomousGovernanceEnvelopeFromMetadata as L,recordAutonomousGovernance as se}from"../../continuity/autonomous-governance.js";import{createDefaultHeadlessAdapterRegistry as de}from"./adapters.js";import{loadHeadlessRuntimeDefaults as ie,resolveHeadlessRuntime as ce}from"./resolver.js";import{HEADLESS_REASON_CODES as m,boundPublicSummary as k,hashPublicValue as R,redaction as i}from"./types.js";const ue=K+60*1e3,me=30*1e3,le=30*1e3,fe=K,pe=1,ye=3,F=m.STORY_WORKTREE_PHASE_BINDING_REQUIRED;function B(e){return e==="story_worktree_phase_1"||e==="story_worktree_phase_2"}function V(e){const t=e.binding?.worktreePath;return typeof t!="string"||!re(t)||typeof e.cwd!="string"?!1:A(t)===A(e.cwd)&&A(t)!==A(e.projectRoot)}const x=Object.freeze({branchless_child_preparation:" branchless-preparation",story_worktree_phase_1:" story-worktree-phase-1",story_worktree_phase_2:" story-worktree-phase-2"}),_e=Object.freeze({branchless_child_preparation:"yolo-branchless-preparation",story_worktree_phase_1:"yolo-story-worktree-phase-1",story_worktree_phase_2:"yolo-story-worktree-phase-2"});function z(e){return e!==void 0&&Object.prototype.hasOwnProperty.call(x,e)}const w=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,Ie=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,he=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),Se=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),T=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,y=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i,E=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function Fe(e){const t=e.adapterRegistry??de(),r=b(e.limit??pe,1,10),a=b(e.leaseMs??ue,1e3,oe.terminalWorkflowMaxDurationMs),n=b(e.staleLeaseAfterMs??me,0,1440*60*1e3),s=b(e.maxAttempts??ye,1,10),o=[],c=[],d=e.now(),u=Ee({store:e.store,metadata:e.metadata,nowIso:d,maxAttempts:s,queueCap:e.queueCap,storyWorktreeBindingValid:V({projectRoot:e.projectRoot,...e.adapterOptions?.cwd?{cwd:e.adapterOptions.cwd}:{},...e.storyWorktreeBinding?{binding:e.storyWorktreeBinding}:{}})});o.push(...u.reasonCodes);const p=e.store.recoverStaleHeadlessExecutionAttempts({nowIso:d,staleAfterMs:n,limit:r*2});p.recoveredAttemptIds.length>0&&(o.push(m.EXECUTION_BACKOFF),p.failedAttemptIds.length>0&&o.push(m.EXECUTION_TIMEOUT));const I=new Set(e.attemptIds??[]),_=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(l=>l.directive_kind==="run_yolo").filter(l=>I.size===0||I.has(l.attempt_id)).slice(0,r);for(const l of _){const h=await be({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:l,registry:t,now:e.now,leaseMs:a,timeoutMs:b(e.timeoutMs??fe,1e3,72e5),backoffMs:b(e.backoffMs??le,1e3,36e5),maxAttempts:s,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??je,storyWorktreeBindingValid:V({projectRoot:e.projectRoot,...e.adapterOptions?.cwd?{cwd:e.adapterOptions.cwd}:{},...e.storyWorktreeBinding?{binding:e.storyWorktreeBinding}:{}})});c.push(h),o.push(h.reasonCode)}return{ok:c.every(l=>l.outcome!=="failed")&&u.rejectedCount===0,enqueuedAttemptCount:u.enqueuedCount,dueAttemptCount:_.length,processedAttemptCount:c.filter(l=>l.outcome!=="ignored").length,recoveredAttemptIds:p.recoveredAttemptIds,receipts:c,reasonCodes:G(o.length>0?o:[m.OK]),publicSafe:!0}}function Ee(e){let t=0,r=0;const a=[];for(const n of Oe(e.metadata)){if(!S(n)||n.kind!=="run_yolo")continue;const s=ke(n);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(B(o.executionMode)&&!e.storyWorktreeBindingValid){r+=1,a.push(F);continue}if(!e.store.jobExists(o.jobId)){r+=1,a.push($.BYPASS_BLOCKED);continue}const c=ve(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(c)){a.push(m.EXECUTION_COMPLETED);continue}const d=ne({autonomousKind:"run_yolo",source:Re(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??v(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:R(o.commandRef)}),u=se(e.store,d,e.nowIso,{requireExistingJob:!0});if(!u.ok){r+=1,a.push(u.reasonCode);continue}const p=W("attempt",o.idempotencyKey),I=W("exec",o.operationId),_=e.store.enqueueHeadlessExecutionAttempt({attemptId:p,executionId:I,jobId:o.jobId,directiveHash:c,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??v(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:we(o.runtime?.source),reasonCode:o.reasonCode,publicSummary:o.publicSummary,enqueuedAt:e.nowIso,notBeforeAt:e.nowIso,maxAttempts:e.maxAttempts,queueCap:e.queueCap,operationId:`${o.operationId}:enqueue`,idempotencyKey:o.idempotencyKey,counts:{directives:1},hashes:{directive:c},redactionSummary:o.redactionSummary,relativePaths:[o.targetRef],metadata:H(d,{schemaVersion:1,contractVersion:"continuity-v1",jobId:o.jobId,operationId:o.operationId,reasonCode:o.reasonCode??m.OK,targetRef:o.targetRef,directiveHash:c,...o.executionMode?{executionMode:o.executionMode}:{}})});if(!_.accepted){r+=1,a.push(_.reasonCode??"queue-cap-reached");continue}_.inserted&&(t+=1),a.push(m.OK)}return{enqueuedCount:t,rejectedCount:r,reasonCodes:G(a)}}async function be(e){const t=e.now(),r=e.idFactory("lease",e.attempt.attempt_id),a=q(t,e.leaseMs);if(!e.store.claimHeadlessExecutionAttempt({attemptId:e.attempt.attempt_id,leaseId:r,runnerId:e.runnerId,claimedAt:t,leaseExpiresAt:a,reasonCode:m.OK}).inserted)return{attemptId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,status:e.attempt.status,outcome:"ignored",reasonCode:"lease-conflict",timestamp:t,redactionSummary:[],publicSafe:!0};if(e.store.hasCompletedHeadlessExecutionDirectiveHash(e.attempt.directive_hash,e.attempt.attempt_id))return C(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"skipped",receiptStatus:"ignored",reasonCode:m.EXECUTION_COMPLETED,publicSummary:"Skipped duplicate run_yolo directive because the directive hash is already completed.",completedAt:e.now(),counts:{duplicateDirectiveHashes:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});if(e.attempt.attempt_count>0)return C(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:"headless-resume-effect-unverified",publicSummary:"Headless run_yolo stopped before redispatch because a prior execution has no verified applied receipt.",completedAt:e.now(),counts:{unverifiedPriorExecutions:e.attempt.attempt_count},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});const o=ge(e);if(!o.ok)return C(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:o.status,receiptStatus:o.receiptStatus,reasonCode:o.reasonCode,publicSummary:o.publicSummary,completedAt:e.now(),counts:{rejectedDirectives:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:o.redactionSummary,relativePaths:Y(e.attempt)});const c=e.registry.getAdapter(o.input.runtimeId);if(!c.ok)return C(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:c.reasonCode,publicSummary:c.publicSummary,completedAt:e.now(),counts:{rejectedAdapters:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:c.redactionSummary,relativePaths:[e.attempt.target_ref],runtimeId:o.input.runtimeId,modelId:o.input.modelId,runtimeSource:o.input.runtimeSource});let d;try{d=await c.adapter.execute(o.input,{...e.adapterOptions,cwd:e.adapterOptions?.cwd??e.projectRoot})}catch{d={status:"failed",adapterId:o.input.runtimeId,runtimeId:o.input.runtimeId,...o.input.modelId?{modelId:o.input.modelId}:{},...o.input.runtimeSource?{runtimeSource:o.input.runtimeSource}:{},reasonCode:m.EXECUTION_FAILED,reasonCodes:[m.EXECUTION_FAILED,m.RECEIPT_REDACTED],exitCode:1,signal:null,durationMs:0,counts:{adapterExceptions:1},hashes:{directive:e.attempt.directive_hash},publicSummary:"Headless adapter failed with public-safe exception summary.",redactionSummary:[i("adapter","raw_log","value-denied")],relativePaths:[e.attempt.target_ref],receipt:o.input.receipt,publicSafe:!0}}const u=Te(e.attempt,d,e.maxAttempts,e.backoffMs,e.now()),p=u.retry?"backoff":d.status,I=u.retry?m.EXECUTION_BACKOFF:d.reasonCode,_=p==="completed"?"applied":p==="backoff"?"deferred":p==="skipped"?"ignored":"failed";return C(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:p,receiptStatus:_,reasonCode:I,publicSummary:u.retry?"Headless run_yolo execution scheduled bounded retry after transient adapter outcome.":d.publicSummary,completedAt:e.now(),durationMs:d.durationMs,notBeforeAt:u.notBeforeAt,retryCount:u.retryCount,counts:d.counts,hashes:{...d.hashes,directive:e.attempt.directive_hash},redactionSummary:d.redactionSummary,relativePaths:d.relativePaths.length>0?d.relativePaths:[e.attempt.target_ref],runtimeId:d.runtimeId,modelId:d.modelId,runtimeSource:d.runtimeSource})}function ge(e){const t=L(e.attempt.metadata_json,{autonomousKind:"run_yolo",jobId:e.attempt.job_id,targetKind:"story",targetRef:e.attempt.target_ref});if(!t.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:t.publicSummary,redactionSummary:t.redactionSummary};const r=R(`*yolo @${e.attempt.target_ref}`),a=Object.keys(x).find(o=>t.envelope.hashes.command===R(`*yolo @${e.attempt.target_ref}${x[o]}`));if(a&&B(a)&&!e.storyWorktreeBindingValid)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:F,publicSummary:"Headless run_yolo refused a story-worktree phase attempt without its explicit worktree binding.",redactionSummary:[i("executionMode","unsafe_key","operation-denied")]};if(!a&&t.envelope.hashes.command!==r)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.DIRECTIVE_REJECTED,publicSummary:"Headless run_yolo governance command does not match an authorized execution mode.",redactionSummary:[i("autonomousGovernance.commandHash","prompt_body","operation-denied")]};const n=Ae(e.attempt);if(!n.ok)return n;const s=Ce(e);return s.ok?{ok:!0,input:{promptKind:a?_e[a]:"yolo",targetKind:"story",targetRef:e.attempt.target_ref,...e.attempt.story_id?{storyId:e.attempt.story_id}:{},runtimeId:s.runtimeId,...s.modelId?{modelId:s.modelId}:{},runtimeSource:s.runtimeSource,timeoutMs:e.timeoutMs,receipt:{attemptId:e.attempt.attempt_id,subagentId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,operationId:e.attempt.execution_id,idempotencyKey:e.attempt.directive_hash,runnerId:e.runnerId},publicSummary:k(e.attempt.public_summary??"Headless run_yolo execution attempt."),publicSafe:!0}}:{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:s.reasonCode,publicSummary:s.publicSummary,redactionSummary:s.redactionSummary}}function Ce(e){const t=e.runtimeDefaults!==void 0?e.runtimeDefaults:ie({projectRoot:e.projectRoot});if(S(t)&&t.ok===!1)return{ok:!1,reasonCode:m.RUNTIME_UNTRUSTED,publicSummary:typeof t.publicSummary=="string"?t.publicSummary:"Headless runtime defaults failed public-safety validation.",redactionSummary:Array.isArray(t.redactionSummary)?t.redactionSummary:[]};const r=Me(e.attempt.runtime_source)??"explicit",a=e.attempt.runtime_id||e.attempt.model_id?{...e.attempt.runtime_id?{runtimeId:e.attempt.runtime_id}:{},...e.attempt.model_id?{modelId:e.attempt.model_id}:{},source:r,publicSafe:!0}:void 0,n={registry:e.registry,defaults:t,fallback:e.runtimeFallback};a&&(r==="origin"?n.origin=a:r==="default"?n.projectDefault=a:r==="fallback"?n.fallback=a:n.explicit=a);const s=ce(n);return s.ok?{ok:!0,runtimeId:s.runtimeId,...s.modelId?{modelId:s.modelId}:{},runtimeSource:s.runtimeSource}:{ok:!1,reasonCode:s.reasonCode,publicSummary:s.publicSummary,redactionSummary:s.redactionSummary}}function Ae(e){const t=[];e.directive_kind!=="run_yolo"&&t.push(i("directiveKind","unsafe_key","value-denied")),e.target_kind!=="story"&&t.push(i("targetKind","prompt_body","value-denied")),(!w.test(e.target_ref)||E.test(e.target_ref)||y.test(e.target_ref))&&t.push(i("targetRef","prompt_body","value-denied"));const r=v(e.target_ref);return e.story_id&&e.story_id!==r&&t.push(i("storyId","prompt_body","value-denied")),t.length>0?{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:m.PROMPT_REJECTED,publicSummary:"Headless run_yolo attempt did not match the canonical public story prompt shape.",redactionSummary:t}:{ok:!0,input:{promptKind:"yolo",targetKind:"story",targetRef:e.target_ref,...e.story_id?{storyId:e.story_id}:{},runtimeId:"fake",publicSafe:!0}}}function ke(e){const t=[];for(const g of Object.keys(e))(!he.has(g)||T.test(g))&&t.push(i(g,D(g),"key-denied"));e.publicSafe!==!0&&t.push(i("publicSafe","unsafe_key","value-denied"));const r=f(e,"kind"),a=f(e,"commandClass"),n=f(e,"jobId"),s=f(e,"operationId"),o=f(e,"idempotencyKey"),c=f(e,"targetKind"),d=f(e,"targetRef"),u=f(e,"commandRef"),p=f(e,"publicSummary"),I=f(e,"storyId"),_=f(e,"executionMode");r!=="run_yolo"&&t.push(i("kind","unsafe_key","value-denied")),a!=="goal-tick"&&a!=="loop-tick"&&t.push(i("commandClass","unsafe_key","value-denied")),N(n)||t.push(i("jobId","unsafe_key","value-denied")),N(s)||t.push(i("operationId","unsafe_key","value-denied")),N(o)||t.push(i("idempotencyKey","unsafe_key","value-denied")),(c!=="story"||!d||!w.test(d)||y.test(d))&&t.push(i("targetRef","prompt_body","value-denied")),_!==void 0&&!z(_)&&t.push(i("executionMode","unsafe_key","value-denied"));const l=S(e.metadata)?e.metadata:void 0,h=z(_)?_:void 0,Z=h==="branchless_child_preparation"?"branchless_sandbox":"story_worktree";h&&(l?.governanceSource!=="delegated-subagent"||l.childWorkspace!==Z||l.integrationOwner!=="root_agent"||l.maxDepth!==1||typeof l.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(l.graphRevision))&&t.push(i("executionMode","unsafe_key","value-denied"));const J=d?`*yolo @${d}${h?x[h]:""}`:void 0;(!u||u!==J||u.includes("@neocortex")||E.test(u)||y.test(u))&&t.push(i("commandRef","prompt_body","value-denied")),I&&d&&I!==v(d)&&t.push(i("storyId","prompt_body","value-denied")),(!p||p.length>240||y.test(p))&&t.push(i("publicSummary","unbounded_text","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("reasonCode","unsafe_key","value-denied"));const P=xe(e.runtime,t);e.attempts!==void 0&&O(e.attempts,"attempts",t),e.metadata!==void 0&&O(e.metadata,"metadata",t);const U=De(e.redactionSummary,t);return t.length>0||r!=="run_yolo"||!a||!n||!s||!o||!d||!u||!p?{ok:!1,reasonCode:t.some(Q=>Q.reason==="prompt_body")?m.PROMPT_REJECTED:m.DIRECTIVE_REJECTED,redactionSummary:t}:{ok:!0,directive:{kind:"run_yolo",commandClass:a,jobId:n,operationId:s,idempotencyKey:o,targetKind:"story",targetRef:d,commandRef:u,...I?{storyId:I}:{},...h?{executionMode:h}:{},...P?{runtime:P}:{},publicSummary:p,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...l?{metadata:l}:{},...U.length>0?{redactionSummary:U}:{},publicSafe:!0}}}function Re(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function xe(e,t){if(e===void 0)return;if(!S(e)){t.push(i("runtime","unsafe_key","value-denied"));return}for(const s of Object.keys(e))(!Se.has(s)||T.test(s))&&t.push(i(`runtime.${s}`,D(s),"key-denied"));e.publicSafe!==!0&&t.push(i("runtime.publicSafe","unsafe_key","value-denied"));const r=f(e,"runtimeId"),a=f(e,"modelId"),n=f(e,"source");if(r&&(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(r)||y.test(r)||E.test(r))&&t.push(i("runtime.runtimeId","unsafe_key","value-denied")),a&&(!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(a)||y.test(a)||E.test(a))&&t.push(i("runtime.modelId","unsafe_key","value-denied")),n!==void 0&&n!=="explicit"&&n!=="origin"&&n!=="default"&&n!=="fallback"&&n!=="unspecified"&&t.push(i("runtime.source","unsafe_key","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||y.test(e.reasonCode))&&t.push(i("runtime.reasonCode","unsafe_key","value-denied")),e.publicSafe===!0)return{...r?{runtimeId:r}:{},...a?{modelId:a}:{},...n==="explicit"||n==="origin"||n==="default"||n==="fallback"||n==="unspecified"?{source:n}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0}}function C(e,t,r){const a=r.redactionSummary??[],n=r.relativePaths??Y(t),s=X(r.counts),o=X(r.hashes),c={schemaVersion:1,contractVersion:"continuity-v1",attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,directiveHash:t.directive_hash,status:r.status,reasonCode:r.reasonCode,...r.runtimeId?{runtimeId:r.runtimeId}:{},...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},...r.retryCount!==void 0?{retryCount:r.retryCount}:{},...r.reasonCode===$.BYPASS_BLOCKED?{governanceEvidence:ae}:{},publicSummary:k(r.publicSummary)},d=L(t.metadata_json,{autonomousKind:"run_yolo",jobId:t.job_id,targetKind:"story",targetRef:t.target_ref}),u=d.ok?H(d.envelope,c):c;return e.completeHeadlessExecutionAttempt({attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,leaseId:r.leaseId,runnerId:r.runnerId,status:r.status,completedAt:r.completedAt,durationMs:r.durationMs,reasonCode:r.reasonCode,publicSummary:k(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:u}),e.recordHeadlessExecutionReceipt({receiptId:`receipt-${M("headless",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.receiptStatus,reasonCode:r.reasonCode,createdAt:r.completedAt,operationId:`${t.execution_id}:${r.status}:receipt`,idempotencyKey:`${t.directive_hash}:${r.status}:receipt`,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:u}),e.recordHeadlessExecutionSummary({eventId:`event-${M("headless-summary",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,runtimeId:r.runtimeId,modelId:r.modelId,publicSummary:k(r.publicSummary),reasonCode:r.reasonCode,createdAt:r.completedAt,durationMs:r.durationMs,counts:s,hashes:o,redactionSummary:a,relativePaths:n,metadata:u}),{attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,outcome:r.receiptStatus,reasonCode:r.reasonCode,timestamp:r.completedAt,redactionSummary:a,publicSafe:!0}}function Te(e,t,r,a,n){if(!(t.status==="timed_out"||t.reasonCode===m.EXECUTION_FAILED||t.reasonCode===m.ADAPTER_UNAVAILABLE))return{retry:!1};const o=e.retry_count+1;if(o>=Math.max(1,e.max_attempts||r))return{retry:!1,retryCount:o};const c=Math.min(8,2**Math.max(0,e.retry_count));return{retry:!0,retryCount:o,notBeforeAt:q(n,a*c)}}function Oe(e){const t=Array.isArray(e)?e:e?[e]:[],r=[];for(const a of t){const n=a.continuityExecutionDirectives;Array.isArray(n)&&r.push(...n)}return r}function ve(e){return R(j({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,runtime:e.runtime}))}function j(e){return Array.isArray(e)?`[${e.map(j).join(",")}]`:S(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${j(e[t])}`).join(",")}}`:JSON.stringify(e)}function O(e,t,r){if(typeof e=="string"){(y.test(e)||E.test(e))&&r.push(i(t,D(t),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((a,n)=>O(a,`${t}.${n}`,r));return}if(S(e)){for(const[a,n]of Object.entries(e)){const s=`${t}.${a}`;T.test(a)&&r.push(i(s,D(a),"key-denied")),O(n,s,r)}return}r.push(i(t,"unsafe_key","value-denied"))}}function De(e,t){if(e===void 0)return[];if(!Array.isArray(e))return t.push(i("redactionSummary","unsafe_key","value-denied")),[];const r=[];for(const[a,n]of e.entries()){if(!S(n)||n.publicSafe!==!0){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}const s=f(n,"field"),o=f(n,"reason"),c=f(n,"evidence");if(!s||!o||!c||y.test(s)||y.test(o)||y.test(c)){t.push(i(`redactionSummary.${a}`,"unsafe_key","value-denied"));continue}r.push({field:s,reason:o,evidence:c,publicSafe:!0})}return r}function Y(e){return w.test(e.target_ref)?[e.target_ref]:[]}function X(e){if(!e)return;const t={};for(const[r,a]of Object.entries(e))!/^[A-Za-z0-9_.:-]{1,80}$/.test(r)||T.test(r)||y.test(r)||typeof a=="string"&&y.test(a)||(t[r]=a);return Object.keys(t).length>0?t:void 0}function v(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function Me(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function we(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback"||e==="unspecified")return e}function D(e){return/prompt|commandRef/i.test(e)?"prompt_body":/std(?:out|err)|raw|log|transcript|stack/i.test(e)?"raw_log":/url/i.test(e)?"private_url":/path|cwd|argv|args|shell|command|binary|executable/i.test(e)?"executable_path":/secret|token|password|authorization|api[_-]?key|license/i.test(e)?"secret_or_pii":"unsafe_key"}function f(e,t){return typeof e[t]=="string"?e[t]:void 0}function N(e){return!!(e&&Ie.test(e)&&!y.test(e)&&!E.test(e))}function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,t){const r=`${e}-${t}`.replace(/[^A-Za-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0&&r.length<=120?r:`${e}-${ee("sha256").update(t).digest("hex").slice(0,32)}`}function W(e,t){return M(e,t)}function je(e,t){return M(e,`${t}-${Date.now()}-${te(4).toString("hex")}`)}function q(e,t){const r=Date.parse(e);return new Date((Number.isFinite(r)?r:Date.now())+t).toISOString()}function b(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function G(e){return Array.from(new Set(e))}export{le as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,ue as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,pe as DEFAULT_HEADLESS_EXECUTION_LIMIT,ye as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,me as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,fe as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,F as RUN_YOLO_STORY_WORKTREE_BINDING_REQUIRED,W as headlessExecutionEntityId,Fe as runYoloExecutionPhase};
1
+ import{createHash as ee,randomBytes as te}from"node:crypto";import{isAbsolute as re,resolve as R}from"node:path";import{P205_RELEASE_GATE_BUDGETS as oe,P205_ROOT_INVOKE_TIMEOUT_MS as H}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as ae,AUTONOMOUS_GOVERNANCE_REASON_CODES as L,autonomousGovernanceMetadata as B,buildAutonomousGovernanceEnvelope as ne,readAutonomousGovernanceEnvelopeFromMetadata as F,recordAutonomousGovernance as se}from"../../continuity/autonomous-governance.js";import{createDefaultHeadlessAdapterRegistry as de}from"./adapters.js";import{loadHeadlessRuntimeDefaults as ie,resolveHeadlessRuntime as ce}from"./resolver.js";import{HEADLESS_REASON_CODES as l,boundPublicSummary as x,hashPublicValue as T,redaction as c}from"./types.js";const ue=H+60*1e3,me=30*1e3,le=30*1e3,fe=H,pe=1,ye=3,V=l.STORY_WORKTREE_PHASE_BINDING_REQUIRED;function z(e){return e==="story_worktree_phase_1"||e==="story_worktree_phase_2"}function Y(e){const t=e.binding?.worktreePath;return typeof t!="string"||!re(t)||typeof e.cwd!="string"?!1:R(t)===R(e.cwd)&&R(t)!==R(e.projectRoot)}const v=Object.freeze({branchless_child_preparation:" branchless-preparation",story_worktree_phase_1:" story-worktree-phase-1",story_worktree_phase_2:" story-worktree-phase-2"}),_e=Object.freeze({branchless_child_preparation:"yolo-branchless-preparation",story_worktree_phase_1:"yolo-story-worktree-phase-1",story_worktree_phase_2:"yolo-story-worktree-phase-2"});function X(e){return e!==void 0&&Object.prototype.hasOwnProperty.call(v,e)}const N=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,Ie=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,he=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),Se=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),O=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,_=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_-]?(?:logs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|workflow body|step body|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY))/i,b=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function Fe(e){const t=e.adapterRegistry??de(),r=g(e.limit??pe,1,10),n=g(e.leaseMs??ue,1e3,oe.terminalWorkflowMaxDurationMs),a=g(e.staleLeaseAfterMs??me,0,1440*60*1e3),d=g(e.maxAttempts??ye,1,10),s=[],o=[],i=e.now(),u=Ee({store:e.store,metadata:e.metadata,nowIso:i,maxAttempts:d,queueCap:e.queueCap,storyWorktreeBindingValid:Y({projectRoot:e.projectRoot,...e.adapterOptions?.cwd?{cwd:e.adapterOptions.cwd}:{},...e.storyWorktreeBinding?{binding:e.storyWorktreeBinding}:{}})});s.push(...u.reasonCodes),o.push(...u.recoveredReceipts);const f=e.store.recoverStaleHeadlessExecutionAttempts({nowIso:i,staleAfterMs:a,limit:r*2});f.recoveredAttemptIds.length>0&&(s.push(l.EXECUTION_BACKOFF),f.failedAttemptIds.length>0&&s.push(l.EXECUTION_TIMEOUT));const I=new Set(e.attemptIds??[]),h=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(m=>m.directive_kind==="run_yolo").filter(m=>I.size===0||I.has(m.attempt_id)).slice(0,r);for(const m of h){const y=await ge({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:m,registry:t,now:e.now,leaseMs:n,timeoutMs:g(e.timeoutMs??fe,1e3,72e5),backoffMs:g(e.backoffMs??le,1e3,36e5),maxAttempts:d,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??Ne,phaseTwoCompletion:e.storyWorktreeBinding?.completion,storyWorktreeBindingValid:Y({projectRoot:e.projectRoot,...e.adapterOptions?.cwd?{cwd:e.adapterOptions.cwd}:{},...e.storyWorktreeBinding?{binding:e.storyWorktreeBinding}:{}})});o.push(y),s.push(y.reasonCode)}return{ok:o.every(m=>m.outcome!=="failed")&&u.rejectedCount===0,enqueuedAttemptCount:u.enqueuedCount,dueAttemptCount:h.length,processedAttemptCount:o.slice(u.recoveredReceipts.length).filter(m=>m.outcome!=="ignored").length,recoveredAttemptIds:f.recoveredAttemptIds,receipts:o,reasonCodes:J(s.length>0?s:[l.OK]),publicSafe:!0}}function Ee(e){let t=0,r=0;const n=[],a=[];for(const d of Oe(e.metadata)){if(!E(d)||d.kind!=="run_yolo")continue;const s=Re(d);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(z(o.executionMode)&&!e.storyWorktreeBindingValid){r+=1,a.push(V);continue}if(!e.store.jobExists(o.jobId)){r+=1,a.push(L.BYPASS_BLOCKED);continue}const i=De(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(i)){const y=o.storyId??k(o.targetRef),S=e.store.reconcileCompletedHeadlessExecutionReceipt({directiveHash:i,directiveKind:"run_yolo",jobId:o.jobId,targetKind:"story",targetRef:o.targetRef,...y?{storyId:y}:{}});if(!S.verified){r+=1,a.push(S.reasonCode);continue}n.some(j=>j.attemptId===S.attempt.attempt_id)||n.push(be(S.attempt)),a.push(S.reasonCode,l.EXECUTION_COMPLETED);continue}const u=ne({autonomousKind:"run_yolo",source:xe(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??k(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:T(o.commandRef)}),f=se(e.store,u,e.nowIso,{requireExistingJob:!0});if(!f.ok){r+=1,a.push(f.reasonCode);continue}const I=G("attempt",o.idempotencyKey),h=G("exec",o.operationId),m=e.store.enqueueHeadlessExecutionAttempt({attemptId:I,executionId:h,jobId:o.jobId,directiveHash:i,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??k(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:je(o.runtime?.source),reasonCode:o.reasonCode,publicSummary:o.publicSummary,enqueuedAt:e.nowIso,notBeforeAt:e.nowIso,maxAttempts:e.maxAttempts,queueCap:e.queueCap,operationId:`${o.operationId}:enqueue`,idempotencyKey:o.idempotencyKey,counts:{directives:1},hashes:{directive:i},redactionSummary:o.redactionSummary,relativePaths:[o.targetRef],metadata:B(u,{schemaVersion:1,contractVersion:"continuity-v1",jobId:o.jobId,operationId:o.operationId,reasonCode:o.reasonCode??l.OK,targetRef:o.targetRef,directiveHash:i,...o.executionMode?{executionMode:o.executionMode}:{}})});if(!m.accepted){r+=1,a.push(m.reasonCode??"queue-cap-reached");continue}m.inserted&&(t+=1),a.push(l.OK)}return{enqueuedCount:t,rejectedCount:r,recoveredReceipts:n,reasonCodes:J(a)}}function be(e){return{attemptId:e.attempt_id,executionId:e.execution_id,jobId:e.job_id,status:"completed",outcome:"applied",reasonCode:e.reason_code??l.EXECUTION_COMPLETED,timestamp:e.completed_at??e.enqueued_at,redactionSummary:[],publicSafe:!0}}async function ge(e){const t=e.now(),r=e.idFactory("lease",e.attempt.attempt_id),n=Z(t,e.leaseMs);if(!e.store.claimHeadlessExecutionAttempt({attemptId:e.attempt.attempt_id,leaseId:r,runnerId:e.runnerId,claimedAt:t,leaseExpiresAt:n,reasonCode:l.OK}).inserted)return{attemptId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,status:e.attempt.status,outcome:"ignored",reasonCode:"lease-conflict",timestamp:t,redactionSummary:[],publicSafe:!0};if(e.store.hasCompletedHeadlessExecutionDirectiveHash(e.attempt.directive_hash,e.attempt.attempt_id))return A(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"skipped",receiptStatus:"ignored",reasonCode:l.EXECUTION_COMPLETED,publicSummary:"Skipped duplicate run_yolo directive because the directive hash is already completed.",completedAt:e.now(),counts:{duplicateDirectiveHashes:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});if(e.attempt.attempt_count>0)return A(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:"headless-resume-effect-unverified",publicSummary:"Headless run_yolo stopped before redispatch because a prior execution has no verified applied receipt.",completedAt:e.now(),counts:{unverifiedPriorExecutions:e.attempt.attempt_count},hashes:{directive:e.attempt.directive_hash},redactionSummary:[],relativePaths:[e.attempt.target_ref]});const s=Ce(e);if(!s.ok)return A(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:s.status,receiptStatus:s.receiptStatus,reasonCode:s.reasonCode,publicSummary:s.publicSummary,completedAt:e.now(),counts:{rejectedDirectives:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:s.redactionSummary,relativePaths:W(e.attempt)});const o=e.registry.getAdapter(s.input.runtimeId);if(!o.ok)return A(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:"failed",receiptStatus:"failed",reasonCode:o.reasonCode,publicSummary:o.publicSummary,completedAt:e.now(),counts:{rejectedAdapters:1},hashes:{directive:e.attempt.directive_hash},redactionSummary:o.redactionSummary,relativePaths:[e.attempt.target_ref],runtimeId:s.input.runtimeId,modelId:s.input.modelId,runtimeSource:s.input.runtimeSource});let i;try{i=await o.adapter.execute(s.input,{...e.adapterOptions,cwd:e.adapterOptions?.cwd??e.projectRoot})}catch{i={status:"failed",adapterId:s.input.runtimeId,runtimeId:s.input.runtimeId,...s.input.modelId?{modelId:s.input.modelId}:{},...s.input.runtimeSource?{runtimeSource:s.input.runtimeSource}:{},reasonCode:l.EXECUTION_FAILED,reasonCodes:[l.EXECUTION_FAILED,l.RECEIPT_REDACTED],exitCode:1,signal:null,durationMs:0,counts:{adapterExceptions:1},hashes:{directive:e.attempt.directive_hash},publicSummary:"Headless adapter failed with public-safe exception summary.",redactionSummary:[c("adapter","raw_log","value-denied")],relativePaths:[e.attempt.target_ref],receipt:s.input.receipt,publicSafe:!0}}const u=ve(e.attempt,i,e.maxAttempts,e.backoffMs,e.now()),f=u.retry?"backoff":i.status,I=u.retry?l.EXECUTION_BACKOFF:i.reasonCode,h=f==="completed"?"applied":f==="backoff"?"deferred":f==="skipped"?"ignored":"failed",{phaseTwoCompletion:m}=e,y=f==="completed"&&e.storyWorktreeBindingValid&&s.input.promptKind==="yolo-story-worktree-phase-2"&&m?.attemptId===e.attempt.attempt_id&&/^[a-f0-9]{64}$/.test(m.digest)?m.digest:void 0,S={...i.hashes,directive:e.attempt.directive_hash};return delete S.phaseTwoBinding,y&&(S.phaseTwoBinding=y),A(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:f,receiptStatus:h,reasonCode:I,publicSummary:u.retry?"Headless run_yolo execution scheduled bounded retry after transient adapter outcome.":i.publicSummary,completedAt:e.now(),durationMs:i.durationMs,notBeforeAt:u.notBeforeAt,retryCount:u.retryCount,counts:i.counts,hashes:S,redactionSummary:i.redactionSummary,relativePaths:i.relativePaths.length>0?i.relativePaths:[e.attempt.target_ref],runtimeId:i.runtimeId,modelId:i.modelId,runtimeSource:i.runtimeSource})}function Ce(e){const t=F(e.attempt.metadata_json,{autonomousKind:"run_yolo",jobId:e.attempt.job_id,targetKind:"story",targetRef:e.attempt.target_ref});if(!t.ok)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:l.DIRECTIVE_REJECTED,publicSummary:t.publicSummary,redactionSummary:t.redactionSummary};const r=T(`*yolo @${e.attempt.target_ref}`),n=Object.keys(v).find(s=>t.envelope.hashes.command===T(`*yolo @${e.attempt.target_ref}${v[s]}`));if(n&&z(n)&&!e.storyWorktreeBindingValid)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:V,publicSummary:"Headless run_yolo refused a story-worktree phase attempt without its explicit worktree binding.",redactionSummary:[c("executionMode","unsafe_key","operation-denied")]};if(!n&&t.envelope.hashes.command!==r)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:l.DIRECTIVE_REJECTED,publicSummary:"Headless run_yolo governance command does not match an authorized execution mode.",redactionSummary:[c("autonomousGovernance.commandHash","prompt_body","operation-denied")]};const a=ke(e.attempt);if(!a.ok)return a;const d=Ae(e);return d.ok?{ok:!0,input:{promptKind:n?_e[n]:"yolo",targetKind:"story",targetRef:e.attempt.target_ref,...e.attempt.story_id?{storyId:e.attempt.story_id}:{},runtimeId:d.runtimeId,...d.modelId?{modelId:d.modelId}:{},runtimeSource:d.runtimeSource,timeoutMs:e.timeoutMs,receipt:{attemptId:e.attempt.attempt_id,subagentId:e.attempt.attempt_id,executionId:e.attempt.execution_id,jobId:e.attempt.job_id,operationId:e.attempt.execution_id,idempotencyKey:e.attempt.directive_hash,runnerId:e.runnerId},publicSummary:x(e.attempt.public_summary??"Headless run_yolo execution attempt."),publicSafe:!0}}:{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:d.reasonCode,publicSummary:d.publicSummary,redactionSummary:d.redactionSummary}}function Ae(e){const t=e.runtimeDefaults!==void 0?e.runtimeDefaults:ie({projectRoot:e.projectRoot});if(E(t)&&t.ok===!1)return{ok:!1,reasonCode:l.RUNTIME_UNTRUSTED,publicSummary:typeof t.publicSummary=="string"?t.publicSummary:"Headless runtime defaults failed public-safety validation.",redactionSummary:Array.isArray(t.redactionSummary)?t.redactionSummary:[]};const r=we(e.attempt.runtime_source)??"explicit",n=e.attempt.runtime_id||e.attempt.model_id?{...e.attempt.runtime_id?{runtimeId:e.attempt.runtime_id}:{},...e.attempt.model_id?{modelId:e.attempt.model_id}:{},source:r,publicSafe:!0}:void 0,a={registry:e.registry,defaults:t,fallback:e.runtimeFallback};n&&(r==="origin"?a.origin=n:r==="default"?a.projectDefault=n:r==="fallback"?a.fallback=n:a.explicit=n);const d=ce(a);return d.ok?{ok:!0,runtimeId:d.runtimeId,...d.modelId?{modelId:d.modelId}:{},runtimeSource:d.runtimeSource}:{ok:!1,reasonCode:d.reasonCode,publicSummary:d.publicSummary,redactionSummary:d.redactionSummary}}function ke(e){const t=[];e.directive_kind!=="run_yolo"&&t.push(c("directiveKind","unsafe_key","value-denied")),e.target_kind!=="story"&&t.push(c("targetKind","prompt_body","value-denied")),(!N.test(e.target_ref)||b.test(e.target_ref)||_.test(e.target_ref))&&t.push(c("targetRef","prompt_body","value-denied"));const r=k(e.target_ref);return e.story_id&&e.story_id!==r&&t.push(c("storyId","prompt_body","value-denied")),t.length>0?{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:l.PROMPT_REJECTED,publicSummary:"Headless run_yolo attempt did not match the canonical public story prompt shape.",redactionSummary:t}:{ok:!0,input:{promptKind:"yolo",targetKind:"story",targetRef:e.target_ref,...e.story_id?{storyId:e.story_id}:{},runtimeId:"fake",publicSafe:!0}}}function Re(e){const t=[];for(const C of Object.keys(e))(!he.has(C)||O.test(C))&&t.push(c(C,M(C),"key-denied"));e.publicSafe!==!0&&t.push(c("publicSafe","unsafe_key","value-denied"));const r=p(e,"kind"),n=p(e,"commandClass"),a=p(e,"jobId"),d=p(e,"operationId"),s=p(e,"idempotencyKey"),o=p(e,"targetKind"),i=p(e,"targetRef"),u=p(e,"commandRef"),f=p(e,"publicSummary"),I=p(e,"storyId"),h=p(e,"executionMode");r!=="run_yolo"&&t.push(c("kind","unsafe_key","value-denied")),n!=="goal-tick"&&n!=="loop-tick"&&t.push(c("commandClass","unsafe_key","value-denied")),K(a)||t.push(c("jobId","unsafe_key","value-denied")),K(d)||t.push(c("operationId","unsafe_key","value-denied")),K(s)||t.push(c("idempotencyKey","unsafe_key","value-denied")),(o!=="story"||!i||!N.test(i)||_.test(i))&&t.push(c("targetRef","prompt_body","value-denied")),h!==void 0&&!X(h)&&t.push(c("executionMode","unsafe_key","value-denied"));const m=E(e.metadata)?e.metadata:void 0,y=X(h)?h:void 0,S=y==="branchless_child_preparation"?"branchless_sandbox":"story_worktree";y&&(m?.governanceSource!=="delegated-subagent"||m.childWorkspace!==S||m.integrationOwner!=="root_agent"||m.maxDepth!==1||typeof m.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(m.graphRevision))&&t.push(c("executionMode","unsafe_key","value-denied"));const j=i?`*yolo @${i}${y?v[y]:""}`:void 0;(!u||u!==j||u.includes("@neocortex")||b.test(u)||_.test(u))&&t.push(c("commandRef","prompt_body","value-denied")),I&&i&&I!==k(i)&&t.push(c("storyId","prompt_body","value-denied")),(!f||f.length>240||_.test(f))&&t.push(c("publicSummary","unbounded_text","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||_.test(e.reasonCode))&&t.push(c("reasonCode","unsafe_key","value-denied"));const U=Te(e.runtime,t);e.attempts!==void 0&&D(e.attempts,"attempts",t),e.metadata!==void 0&&D(e.metadata,"metadata",t);const $=Me(e.redactionSummary,t);return t.length>0||r!=="run_yolo"||!n||!a||!d||!s||!i||!u||!f?{ok:!1,reasonCode:t.some(Q=>Q.reason==="prompt_body")?l.PROMPT_REJECTED:l.DIRECTIVE_REJECTED,redactionSummary:t}:{ok:!0,directive:{kind:"run_yolo",commandClass:n,jobId:a,operationId:d,idempotencyKey:s,targetKind:"story",targetRef:i,commandRef:u,...I?{storyId:I}:{},...y?{executionMode:y}:{},...U?{runtime:U}:{},publicSummary:f,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...m?{metadata:m}:{},...$.length>0?{redactionSummary:$}:{},publicSafe:!0}}}function xe(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function Te(e,t){if(e===void 0)return;if(!E(e)){t.push(c("runtime","unsafe_key","value-denied"));return}for(const d of Object.keys(e))(!Se.has(d)||O.test(d))&&t.push(c(`runtime.${d}`,M(d),"key-denied"));e.publicSafe!==!0&&t.push(c("runtime.publicSafe","unsafe_key","value-denied"));const r=p(e,"runtimeId"),n=p(e,"modelId"),a=p(e,"source");if(r&&(!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,79}$/.test(r)||_.test(r)||b.test(r))&&t.push(c("runtime.runtimeId","unsafe_key","value-denied")),n&&(!/^[A-Za-z0-9][A-Za-z0-9._:+/-]{0,119}$/.test(n)||_.test(n)||b.test(n))&&t.push(c("runtime.modelId","unsafe_key","value-denied")),a!==void 0&&a!=="explicit"&&a!=="origin"&&a!=="default"&&a!=="fallback"&&a!=="unspecified"&&t.push(c("runtime.source","unsafe_key","value-denied")),e.reasonCode!==void 0&&(typeof e.reasonCode!="string"||_.test(e.reasonCode))&&t.push(c("runtime.reasonCode","unsafe_key","value-denied")),e.publicSafe===!0)return{...r?{runtimeId:r}:{},...n?{modelId:n}:{},...a==="explicit"||a==="origin"||a==="default"||a==="fallback"||a==="unspecified"?{source:a}:{},...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},publicSafe:!0}}function A(e,t,r){const n=r.redactionSummary??[],a=r.relativePaths??W(t),d=q(r.counts),s=q(r.hashes),o={schemaVersion:1,contractVersion:"continuity-v1",attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,directiveHash:t.directive_hash,status:r.status,reasonCode:r.reasonCode,...r.runtimeId?{runtimeId:r.runtimeId}:{},...r.modelId?{modelId:r.modelId}:{},...r.runtimeSource?{runtimeSource:r.runtimeSource}:{},...r.retryCount!==void 0?{retryCount:r.retryCount}:{},...r.reasonCode===L.BYPASS_BLOCKED?{governanceEvidence:ae}:{},publicSummary:x(r.publicSummary)},i=F(t.metadata_json,{autonomousKind:"run_yolo",jobId:t.job_id,targetKind:"story",targetRef:t.target_ref}),u=i.ok?B(i.envelope,o):o;return e.finalizeHeadlessExecutionAttempt({completion:{attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,leaseId:r.leaseId,runnerId:r.runnerId,status:r.status,completedAt:r.completedAt,durationMs:r.durationMs,reasonCode:r.reasonCode,publicSummary:x(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:u},receipt:{receiptId:`receipt-${w("headless",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.receiptStatus,reasonCode:r.reasonCode,createdAt:r.completedAt,operationId:`${t.execution_id}:${r.status}:receipt`,idempotencyKey:`${t.directive_hash}:${r.status}:receipt`,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:u}}),e.recordHeadlessExecutionSummary({eventId:`event-${w("headless-summary",`${t.attempt_id}-${r.status}`)}`,attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,runtimeId:r.runtimeId,modelId:r.modelId,publicSummary:x(r.publicSummary),reasonCode:r.reasonCode,createdAt:r.completedAt,durationMs:r.durationMs,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:u}),{attemptId:t.attempt_id,executionId:t.execution_id,jobId:t.job_id,status:r.status,outcome:r.receiptStatus,reasonCode:r.reasonCode,timestamp:r.completedAt,redactionSummary:n,publicSafe:!0}}function ve(e,t,r,n,a){if(!(t.status==="timed_out"||t.reasonCode===l.EXECUTION_FAILED||t.reasonCode===l.ADAPTER_UNAVAILABLE))return{retry:!1};const s=e.retry_count+1;if(s>=Math.max(1,e.max_attempts||r))return{retry:!1,retryCount:s};const o=Math.min(8,2**Math.max(0,e.retry_count));return{retry:!0,retryCount:s,notBeforeAt:Z(a,n*o)}}function Oe(e){const t=Array.isArray(e)?e:e?[e]:[],r=[];for(const n of t){const a=n.continuityExecutionDirectives;Array.isArray(a)&&r.push(...a)}return r}function De(e){return T(P({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,runtime:e.runtime}))}function P(e){return Array.isArray(e)?`[${e.map(P).join(",")}]`:E(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${P(e[t])}`).join(",")}}`:JSON.stringify(e)}function D(e,t,r){if(typeof e=="string"){(_.test(e)||b.test(e))&&r.push(c(t,M(t),"value-denied"));return}if(!(e==null||typeof e=="number"||typeof e=="boolean")){if(Array.isArray(e)){e.forEach((n,a)=>D(n,`${t}.${a}`,r));return}if(E(e)){for(const[n,a]of Object.entries(e)){const d=`${t}.${n}`;O.test(n)&&r.push(c(d,M(n),"key-denied")),D(a,d,r)}return}r.push(c(t,"unsafe_key","value-denied"))}}function Me(e,t){if(e===void 0)return[];if(!Array.isArray(e))return t.push(c("redactionSummary","unsafe_key","value-denied")),[];const r=[];for(const[n,a]of e.entries()){if(!E(a)||a.publicSafe!==!0){t.push(c(`redactionSummary.${n}`,"unsafe_key","value-denied"));continue}const d=p(a,"field"),s=p(a,"reason"),o=p(a,"evidence");if(!d||!s||!o||_.test(d)||_.test(s)||_.test(o)){t.push(c(`redactionSummary.${n}`,"unsafe_key","value-denied"));continue}r.push({field:d,reason:s,evidence:o,publicSafe:!0})}return r}function W(e){return N.test(e.target_ref)?[e.target_ref]:[]}function q(e){if(!e)return;const t={};for(const[r,n]of Object.entries(e))!/^[A-Za-z0-9_.:-]{1,80}$/.test(r)||O.test(r)||_.test(r)||typeof n=="string"&&_.test(n)||(t[r]=n);return Object.keys(t).length>0?t:void 0}function k(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function we(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function je(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback"||e==="unspecified")return e}function M(e){return/prompt|commandRef/i.test(e)?"prompt_body":/std(?:out|err)|raw|log|transcript|stack/i.test(e)?"raw_log":/url/i.test(e)?"private_url":/path|cwd|argv|args|shell|command|binary|executable/i.test(e)?"executable_path":/secret|token|password|authorization|api[_-]?key|license/i.test(e)?"secret_or_pii":"unsafe_key"}function p(e,t){return typeof e[t]=="string"?e[t]:void 0}function K(e){return!!(e&&Ie.test(e)&&!_.test(e)&&!b.test(e))}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function w(e,t){const r=`${e}-${t}`.replace(/[^A-Za-z0-9_.:-]+/g,"-").replace(/^-+|-+$/g,"");return r.length>0&&r.length<=120?r:`${e}-${ee("sha256").update(t).digest("hex").slice(0,32)}`}function G(e,t){return w(e,t)}function Ne(e,t){return w(e,`${t}-${Date.now()}-${te(4).toString("hex")}`)}function Z(e,t){const r=Date.parse(e);return new Date((Number.isFinite(r)?r:Date.now())+t).toISOString()}function g(e,t,r){return Number.isFinite(e)?Math.max(t,Math.min(r,Math.floor(e))):t}function J(e){return Array.from(new Set(e))}export{le as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,ue as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,pe as DEFAULT_HEADLESS_EXECUTION_LIMIT,ye as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,me as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,fe as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,V as RUN_YOLO_STORY_WORKTREE_BINDING_REQUIRED,G as headlessExecutionEntityId,Fe as runYoloExecutionPhase};
@@ -168,6 +168,42 @@ interface YoloopDriverResult {
168
168
  readonly terminalClass?: 'release-blocked';
169
169
  readonly releaseBlocked?: ReleaseBlockedResultV1;
170
170
  }
171
+ interface AuthorizedChildPrompt {
172
+ readonly storyId: string;
173
+ readonly targetRef: string;
174
+ readonly commandRef: string;
175
+ readonly preparationOnly?: true;
176
+ readonly source: 'execution-plan' | 'task-directive' | 'next-story';
177
+ readonly dispatchId?: string;
178
+ readonly idempotencyKey?: string;
179
+ readonly graphRevision?: string;
180
+ readonly writeSet?: readonly string[];
181
+ readonly executionBranch?: string;
182
+ readonly rootAuthority?: BranchlessRootAuthority;
183
+ /** P227.23: set only for prompts admitted from a validated v4 plan. */
184
+ readonly storyWorktreePhase?: 'phase-1' | 'phase-2';
185
+ readonly storyWorktreeEpicId?: string;
186
+ readonly storyWorktreeDispatchId?: string;
187
+ readonly storyWorktreeBaseSha?: string;
188
+ readonly storyWorktreeTemporaryBranch?: string;
189
+ }
190
+ interface BranchlessRootAuthority {
191
+ readonly schemaVersion: 1;
192
+ readonly kind: 'branchless_story_preparation';
193
+ readonly storyId: string;
194
+ readonly invocationPrompt: string;
195
+ readonly authorizedWriteSet: readonly string[];
196
+ readonly effectScope: 'filesystem_only';
197
+ readonly lifecycleAuthority: 'root_only';
198
+ readonly artifact: {
199
+ readonly schemaVersion: 1;
200
+ readonly kind: 'branchless_root_bound_artifact';
201
+ readonly path: string;
202
+ readonly content: string;
203
+ readonly contentBinding: string;
204
+ };
205
+ readonly publicSafe: true;
206
+ }
171
207
  /** Mirror of the server `STORY_WORKTREE_DISPATCH_DOMAIN` (parity-tested). */
172
208
  export declare const YOLOOP_V4_STORY_WORKTREE_DISPATCH_DOMAIN: "neocortex.p225.story-worktree-dispatch.v1";
173
209
  /** P227.23 (ADR-4): the server dispatch id for one story at one graph revision. */
@@ -291,5 +327,24 @@ export declare function prepareYoloopV4ChildWorkspace(input: {
291
327
  readonly graphRevision: string;
292
328
  readonly temporaryBranch?: string;
293
329
  }): Promise<YoloopV4StoryWorktreeWorkspace>;
330
+ export declare function checkV4DispatchBases(projectRoot: string, executionBranch: string, children: readonly Pick<AuthorizedChildPrompt, 'storyId' | 'storyWorktreeBaseSha'>[]): Promise<{
331
+ ok: true;
332
+ } | {
333
+ ok: false;
334
+ fingerprint: string;
335
+ reasonCode: string;
336
+ storyIds: string[];
337
+ }>;
338
+ type PhaseTwoObservation = {
339
+ readonly kind: 'ready' | 'pending' | 'blocked';
340
+ readonly reasonCode: string;
341
+ };
342
+ /** The response is evidence for this phase only after its dispatch identity matches. */
343
+ export declare function classifyRunnerPhaseTwoObservation(observed: InvokeResult, binding: {
344
+ storyId: string;
345
+ graphRevision: string;
346
+ stepIds: readonly string[];
347
+ releaseReceiptId?: string;
348
+ }): PhaseTwoObservation;
294
349
  /** Public step identities are checked by shape; the server binds their exact lists. */
295
350
  export declare function isRunnerYoloopV4PlanValid(plan: unknown): boolean;