@ornexus/neocortex 4.66.48 → 4.66.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1190 -1190
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/git/git-lifecycle-store.d.ts +3 -1
- package/packages/client/dist/git/git-lifecycle-store.js +8 -8
- package/packages/client/dist/git/story-worktree-manager.d.ts +2 -0
- package/packages/client/dist/git/story-worktree-manager.js +3 -3
- package/packages/client/dist/runner/headless/phase-two-checkpoint-evidence.d.ts +4 -4
- package/packages/client/dist/runner/headless/phase-two-checkpoint-evidence.js +1 -1
- package/packages/client/dist/runner/headless/run-yolo.d.ts +1 -0
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +6 -3
- package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +1 -0
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -141,6 +141,7 @@ export interface GitOutcome {
|
|
|
141
141
|
readonly stdout: string;
|
|
142
142
|
/** P227.07: process exit code (0 on success; -1 when Git did not exit normally). */
|
|
143
143
|
readonly exitCode: number;
|
|
144
|
+
readonly failure?: 'capacity' | 'timeout';
|
|
144
145
|
}
|
|
145
146
|
export interface RepositoryFacts {
|
|
146
147
|
readonly mainRoot: string;
|
|
@@ -299,6 +300,7 @@ export declare class StoryWorktreeManager {
|
|
|
299
300
|
* reclaimed only when it is provably empty (no path, no branch).
|
|
300
301
|
*/
|
|
301
302
|
private reclaimStaleReservation;
|
|
303
|
+
private isTemporaryBranchAbsent;
|
|
302
304
|
private readDocument;
|
|
303
305
|
/** Journal write under the lifecycle lock, retrying bounded lock contention. */
|
|
304
306
|
private mutate;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{execFile as ne}from"node:child_process";import{createHash as ce,randomBytes as de}from"node:crypto";import{chmod as he,lstat as D,mkdir as le,open as we,readFile as x,realpath as E,rename as W,rmdir as fe,unlink as B,writeFile as j}from"node:fs/promises";import{homedir as ue}from"node:os";import{isAbsolute as q,join as b,resolve as pe}from"node:path";import{isDeepStrictEqual as me}from"node:util";import{yoloopDomainHash as G}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as ye,STATE_JSON_FIELD_MERGE_MAX_BYTES as ke}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as ge,bindStoryWorktreeLeaseEvidence as ve,compactStoryWorktreeJournal as Ie,ensureStoryWorktreeJournal as _,isStoryWorktreeCleanupReceiptRecord as Re,mutateGitLifecycleRuntime as be,readGitLifecycleRuntime as Se}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as Ee,ensurePrivateStoryWorktreeRoot as Pe,ensureStoryWorktreeSharedResolution as Ae,resolveStoryWorktreePath as F,resolveStoryWorktreeRoot as De,storyWorktreeIdentity as xe}from"./story-worktree-paths.js";const H="nx-owner",_e="neocortex.p225.story-worktree-receipt.v1";function V(c){return G(_e,c)}const J=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),Oe=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,T=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,Be=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function Y(c){if(c===null||typeof c!="object"||Array.isArray(c))return!1;const e=c,r=Object.keys(e);if(r.length!==J.length||!r.every(a=>J.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&K.test(e.directiveId)&&typeof e.epicId=="string"&&X.test(e.epicId)&&typeof e.storyId=="string"&&T.test(e.storyId)&&typeof e.releasedStepId=="string"&&Oe.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&T.test(a))&&typeof e.integratedEpicHeadSha=="string"&&P.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&N.test(e.graphRevision)&&typeof e.issuedAt=="string"&&Be.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const U=1440*60*1e3,Ce="neocortex.p225.two-phase-release-directive-id.v1",C=".neocortex/state.json",M=".story-worktree-sync",$e=3e4,Te=200,P=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,N=/^[a-f0-9]{64}$/,L=/^swt-[a-f0-9]{24}$/,K=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,X=/^P[1-9][0-9]*$/,We=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",Z=128*1024,je=/^[a-f0-9]{64}$/;function Q(c){if(!c||typeof c!="object"||Array.isArray(c))return;const e=c;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(!je.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function ee(c){return`docs/epics/epic-${c}.md`}function He(c,e){if(e===ee(c)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${c}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${c}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class te extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(c){throw new te(c)}function Me(){const c={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete c[e];return c.GIT_TERMINAL_PROMPT="0",c}function Qe(c,e){return l(c,e)}function l(c,e){return new Promise(r=>{ne("git",[...e],{cwd:c,encoding:"utf8",env:Me(),maxBuffer:8*1024*1024,timeout:$e,windowsHide:!0},(t,a)=>r({ok:!t,stdout:String(a??""),exitCode:t?typeof t.code=="number"?t.code:-1:0}))})}async function p(c,e){return(await l(c,e)).ok}async function re(c,e,r){if(!P.test(e)||!P.test(r))return"unverified";const t=await l(c,["merge-base","--is-ancestor",e,r]);if(t.ok)return"contained";if(t.exitCode!==1)return"unverified";const a=await l(c,["rev-parse","--is-shallow-repository"]);return a.ok&&a.stdout.trim()==="false"?"divergent":"unverified"}async function R(c,e,r){const t=await l(c,e);return t.ok||o(r),t.stdout.trim()}async function ae(c,e){return p(c,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function Ne(c,e,r){const t=c.worktreePath,a=b(t,C),s=b(t,".neocortex"),i=b(s,M),n=b(i,"original.json"),h=b(i,"merged.json"),w=await D(a).catch(()=>{});if(!w?.isFile()||w.nlink!==1||w.size>ke||await E(a)!==a||!await p(t,["diff","--cached","--quiet"])||await p(t,["diff","--quiet","--",C])||await p(t,["cat-file","-e",`${r}:.neocortex/${M}`])||await R(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[d,u,y]=await Promise.all([l(t,["show",`${e}:${C}`]),l(t,["show",`${r}:${C}`]),l(t,["show","-s","--format=%cI",r])]);if(!d.ok||!u.ok||!y.ok||d.stdout===u.stdout)return!1;const f=await x(a),I=ye({base:d.stdout,epic:u.stdout,story:f,storyId:c.storyId,epicId:c.epicId,aggregateTimestamp:y.stdout.trim()});if(I===void 0)return!1;try{await le(i,{mode:448})}catch{return!1}let m=!1,k=!1;try{const v=await we(h,"wx",w.mode&511);try{await v.writeFile(I,"utf8"),await v.sync()}finally{await v.close()}if(!(await x(a)).equals(f))return!1;await W(a,n),m=!0,(!(await x(n)).equals(f)||!await p(t,["checkout-index","--",C]))&&o("story-worktree-sync-state-backup-preserved"),await ae(t,r);const g=await R(t,["rev-parse","HEAD"],"story-worktree-git-failed"),A=g===r?u.stdout:g===e?d.stdout:void 0;return(A===void 0||!(await x(a)).equals(Buffer.from(A)))&&o("story-worktree-sync-state-backup-preserved"),await W(g===r?h:n,a),k=!0,g===r}finally{(!m||k)&&(await B(n).catch(()=>{}),await B(h).catch(()=>{}),await fe(i).catch(()=>{}))}}function O(c){return ce("sha256").update(c).digest("hex")}async function Le(c){try{return await D(c),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function z(c){try{return await D(c),!0}catch{return!1}}function se(c){return new Promise(e=>setTimeout(e,c))}function oe(c){const e=[];for(const r of c.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(n=>n.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(n=>n.startsWith("HEAD "))?.slice(5),i=t.find(n=>n.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...i?.startsWith("refs/heads/")?{branch:i.slice(11)}:{}})}return e}function ze(c){return c.length>0&&c.length<=512&&!q(c)&&!/^[A-Za-z]:/.test(c)&&!c.includes("\\")&&!c.split("/").some(e=>e===".."||e==="")}class et{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=pe(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>de(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();let s=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(s?.state==="active"&&s.baseSha===e.baseSha&&s.graphRevision===e.graphRevision&&s.epicId===r.epicId&&s.storyId===r.storyId&&s.executionBranch===r.executionBranch&&s.temporaryBranch===r.temporaryBranch&&await this.ownershipProven(s,t))return await this.assertReusableBase(t,s,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha),await this.assertNoCleanupInProgress(t,s.leaseId),{ok:!0,value:this.leaseValue(s,!0),privatePath:s.worktreePath};await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.baseSha);const i=De({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??ue(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});i.ok||o(i.reasonCode);const n=F({root:i.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});n.ok||o(n.reasonCode);const h=await Pe(i.value,this.platform);h.ok||o(h.reasonCode);const w=F({root:await E(i.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});w.ok||o(w.reasonCode);const d=w.value;s=(await this.readDocument()).storyWorktrees?.entries[r.leaseId],s&&(await this.reclaimStaleReservation(s,t)||o("story-worktree-entry-conflict")),await z(d)&&o("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const u=this.randomNonce(),y=this.now(),f={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,u),nonceDigest:O(u),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:y.toISOString(),expiresAt:new Date(y.getTime()+(this.options.ttlMs??U)).toISOString()};await this.mutate(m=>{const k=_(m);(k.entries[f.leaseId]||Object.values(k.entries).some(v=>v.worktreePath===d))&&o("story-worktree-entry-conflict"),k.entries[f.leaseId]=f});let I=!1;try{await p(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha])||o("story-worktree-add-failed"),I=!0,this.platform!=="win32"?await he(d,448):await this.enableWindowsLongPaths(t,d);const m=await this.prepareSharedResolution(t,d,e.baseSha),k=await this.worktreeGitDir(d,t);await j(b(k,H),`${JSON.stringify({schemaVersion:1,leaseId:f.leaseId,nonce:u})}
|
|
2
|
-
`,{flag:"wx",mode:384});const
|
|
3
|
-
`,{flag:"wx",mode:384});try{await this.mutate(m=>{const k=_(m);(k.entries[f.leaseId]||Object.values(k.entries).some(v=>this.samePath(v.worktreePath,s)))&&o("story-worktree-entry-conflict"),k.entries[f.leaseId]=f,this.bindLeaseEvidence(m,f)})}catch(m){throw await this.removeOwnMarker(n,u),m}const I={...this.leaseValue(f,!1),sharedResolution:d};return{ok:!0,value:w?{...I,alignment:w}:I,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const h=e.directive;(!Y(e.directive)||h.epicId!==t.epicId||h.storyId!==t.storyId||a!==void 0&&a!==h.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(h.integratedEpicHeadSha)}if(e.automatic){const h=e.directive;(!Y(h)||h.graphRevision!==t.graphRevision||Array.isArray(h.dependsOn)&&h.dependsOn.includes(t.storyId)||h.directiveId!==G(Ce,{epicId:h.epicId,storyId:h.storyId,dependsOn:h.dependsOn,integratedEpicHeadSha:h.integratedEpicHeadSha,graphRevision:h.graphRevision}))&&o("story-worktree-directive-invalid");const w=await this.assertPhaseTwo({storyId:t.storyId});(!w.ok||w.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 p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let i="already-synced";if(e.automatic){await D(b(t.worktreePath,".neocortex",M)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const h=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");h!==a&&(await p(t.worktreePath,["merge-base","--is-ancestor",h,a])||o("story-worktree-sync-not-fast-forward"),!await ae(t.worktreePath,a)&&!await Ne(t,h,a)&&o("story-worktree-sync-conflict-preserved"),i="synced")}if(!e.automatic&&!await p(t.worktreePath,["merge-base","--is-ancestor",a,"HEAD"])){if(!(await l(t.worktreePath,["merge","--no-edit",a])).ok){const d=(await l(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(ze).sort().slice(0,Te);return d.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}i="synced"}const n=await R(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&n!==a&&o("story-worktree-sync-head-raced"),await this.mutate(h=>{const w=_(h),d=w.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),w.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:i,integratedSha:a,headSha:n}}})}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&&!L.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"||!T.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,i)=>s.leaseId.localeCompare(i.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"||!T.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await E(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 l(r.mainRoot,["worktree","prune"]);let i;t.workspaceMechanism==="native_subagent_worktree"?i="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(i="story-worktree-branch-moved");const n=i===void 0,h=this.now().toISOString(),w={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${O(`${t.leaseId}|${t.nonceDigest}|${h}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:n,remoteBranchRemoved:!1,...i?{preservedReasonCode:i}:{},cleanedAt:h};return Re(w)||o("story-worktree-receipt-invalid"),await this.mutate(d=>{const u=_(d),y=u.entries[t.leaseId];for(y&&y.nonceDigest===t.nonceDigest&&delete u.entries[t.leaseId],u.cleanupReceipts.push({...w});u.cleanupReceipts.length>ge;)u.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:w,receiptDigest:V(w)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!L.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((g,A)=>A>0&&this.samePath(g.path,t.worktreePath)),i=a.some(g=>g.branch===t.temporaryBranch),n=await l(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),h=n.ok&&P.test(n.stdout.trim())?n.stdout.trim():void 0,w=await l(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=w.ok&&P.test(w.stdout.trim())?w.stdout.trim():void 0,u=await Le(t.worktreePath),y=u==="present",f=t.state==="active"&&y&&await this.ownershipProven(t,r);let I,m;if(f){const g=await l(t.worktreePath,["rev-parse","HEAD"]);g.ok&&P.test(g.stdout.trim())&&(I=g.stdout.trim()),m=await this.clean(t.worktreePath)}const k=I??(y?void 0:h),v=k&&d?await p(r.mainRoot,["merge-base","--is-ancestor",k,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:f?"proven":"unproven",pathExists:y,pathAbsence:u,registered:s,...h?{branchSha:h}:{},branchCheckedOut:i,...I?{headSha:I}:{},...m!==void 0?{clean:m}:{},...d?{epicHead:d}:{},...v!==void 0?{integrated:v}:{}}}})}async registeredWorktrees(){return this.guard(async()=>{const e=await this.repository();return{ok:!0,value:{facts:e,worktrees:(await this.listWorktrees(e)).slice(1)}}})}sameWorktreePath(e,r){return this.samePath(e,r)}async fail(e){const{StoryWorktreeCleanup:r}=await import("./story-worktree-cleanup.js");return new r({manager:this,projectRoot:this.projectRoot,now:this.now}).cleanup({leaseId:e.leaseId,trigger:e.trigger??"failure",...e.dryRun?{dryRun:!0}:{}})}async abandon(e){return this.fail({...e,trigger:"abandon"})}async guard(e){try{return await e()}catch(r){if(r instanceof 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=xe(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 E(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 E(r),s=oe(await R(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await E(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!N.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!P.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r),i=await re(e.mainRoot,t,s);i!=="contained"&&o(i==="divergent"?"story-worktree-base-divergent":"story-worktree-base-unverified")}async assertReusableBase(e,r,t,a){(!N.test(a)||!P.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r.executionBranch),i=await re(e.mainRoot,t,s);i!=="contained"&&(i!=="divergent"&&o("story-worktree-base-unverified"),(r.syncedSha!==s||!await p(r.worktreePath,["merge-base","--is-ancestor",t,"HEAD"])||!await p(r.worktreePath,["merge-base","--is-ancestor",s,"HEAD"]))&&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 E(await R(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await E(await R(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=b(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,i)=>{for(let n=1;n<=8;n++){if(await p(s,i))return;await se(25*n)}o("story-worktree-config-failed")},a=await l(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 E(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await x(b(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),i=s.findIndex(n=>this.samePath(n.path,e.worktreePath));return i>0&&s[i].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!L.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 l(e,["status","--porcelain=v1","--untracked-files=all","-z"]);if(!r.ok||r.stdout!==` M ${$}\0`||(await l(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok)return;const t=b(e,$);try{const a=await D(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>Z)return;const s=await l(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>Z)return;const i=Q(JSON.parse(await x(t,"utf8"))),n=Q(JSON.parse(s.stdout));if(!i||!n)return;const h=Object.keys(i);return h.length>=Object.keys(n).length||!h.every(w=>Object.hasOwn(n,w)&&me(i[w],n[w]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=b(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await D(t)).mode&511;await j(a,r,{encoding:"utf8",flag:"wx",mode:s}),await W(a,t)}catch{await B(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=ee(r);return(await l(e,["cat-file","-e",`${t}:${s}`])).ok?!(await l(e,["cat-file","-e",`${a}:${s}`])).ok:!1}async assertPlanningInBase(e,r,t){const a=await l(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 l(e,["merge-base",t,a]);if(!s.ok)return!1;const i=await l(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!i.ok)return!1;const n=i.stdout.split("\0").filter(Boolean);return n.length>0&&n.every(h=>He(r,h))}async clean(e){const r=await l(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await l(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 l(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!P.test(s))return{...t,ownership:"proven"};const i=await l(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),n=i.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",s,i.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:n}}bindLeaseEvidence(e,r){try{ve(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:V(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[Ee]:a}}}async prepareSharedResolution(e,r,t){const a=await l(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 Ae({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 l(e.mainRoot,["worktree","remove",r.worktreePath]),await l(e.mainRoot,["worktree","prune"]));const a=await this.listWorktrees(e).catch(()=>{});a&&!a.some(s=>s.branch===r.temporaryBranch)&&await l(e.mainRoot,["update-ref","-d",`refs/heads/${r.temporaryBranch}`,r.baseSha]),await this.mutate(s=>{const i=_(s),n=i.entries[r.leaseId];n&&n.nonceDigest===r.nonceDigest&&delete i.entries[r.leaseId],Ie(s)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await x(e,"utf8")).nonce===r&&await B(e)}catch{}}async listWorktrees(e){const r=oe(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 E(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await x(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||!(!await z(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 i=_(s),n=i.entries[e.leaseId];n&&n.state==="creating"&&n.nonceDigest===e.nonceDigest&&(delete i.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 be(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 se(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{H as STORY_WORKTREE_MARKER_FILE,_e as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,et as StoryWorktreeManager,V as digestStoryWorktreeReceiptLocal,oe as parseWorktreeList,Qe as runStoryWorktreeGit,re as storyWorktreeBaseAncestry,Le as storyWorktreePathAbsence};
|
|
1
|
+
import{execFile as he}from"node:child_process";import{createHash as le,randomBytes as fe}from"node:crypto";import{chmod as we,lstat as D,mkdir as ue,open as pe,readFile as _,realpath as S,rename as H,rmdir as me,unlink as T,writeFile as M}from"node:fs/promises";import{homedir as ye}from"node:os";import{isAbsolute as F,join as R,resolve as ke}from"node:path";import{isDeepStrictEqual as ge}from"node:util";import{yoloopDomainHash as J}from"../../../shared/dist/yoloop/canonical.js";import{mergeLegacyStateForStorySync as Ie,STATE_JSON_FIELD_MERGE_MAX_BYTES as ve}from"./state-json-field-merge.js";import{STORY_WORKTREE_JOURNAL_MAX_CLEANUP_RECEIPTS as Re,bindStoryWorktreeLeaseEvidence as be,compactStoryWorktreeJournal as Se,ensureStoryWorktreeJournal as O,isStoryWorktreeCleanupReceiptRecord as Ee,mutateGitLifecycleRuntime as Pe,readGitLifecycleRuntime as Ae}from"./git-lifecycle-store.js";import{STORY_WORKTREE_ID_ENV as De,ensurePrivateStoryWorktreeRoot as _e,ensureStoryWorktreeSharedResolution as Oe,resolveStoryWorktreePath as U,resolveStoryWorktreeRoot as xe,storyWorktreeIdentity as Te}from"./story-worktree-paths.js";const N="nx-owner",Be="neocortex.p225.story-worktree-receipt.v1";function Y(c){return J(Be,c)}const K=Object.freeze(["schemaVersion","kind","directiveId","epicId","storyId","releasedStepId","dependsOn","integratedEpicHeadSha","graphRevision","issuedAt"]),Ce=/^step-c-[0-9]+-[a-z0-9-]{1,60}$/,W=/^P[1-9][0-9]*(?:\.[0-9]+)+$/,$e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function X(c){if(c===null||typeof c!="object"||Array.isArray(c))return!1;const e=c,r=Object.keys(e);if(r.length!==K.length||!r.every(a=>K.includes(a)))return!1;const t=e.dependsOn;return e.schemaVersion===1&&e.kind==="dependency-release-directive"&&typeof e.directiveId=="string"&&te.test(e.directiveId)&&typeof e.epicId=="string"&&re.test(e.epicId)&&typeof e.storyId=="string"&&W.test(e.storyId)&&typeof e.releasedStepId=="string"&&Ce.test(e.releasedStepId)&&Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(a=>typeof a=="string"&&W.test(a))&&typeof e.integratedEpicHeadSha=="string"&&P.test(e.integratedEpicHeadSha)&&typeof e.graphRevision=="string"&&z.test(e.graphRevision)&&typeof e.issuedAt=="string"&&$e.test(e.issuedAt)&&Number.isFinite(Date.parse(e.issuedAt))}const Z=1440*60*1e3,We="neocortex.p225.two-phase-release-directive-id.v1",C=".neocortex/state.json",L=".story-worktree-sync",Q=3e4,ee=18e4,je=ee+3*Q,He=200,P=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,z=/^[a-f0-9]{64}$/,G=/^swt-[a-f0-9]{24}$/,te=/^[A-Za-z0-9][A-Za-z0-9_-]{7,95}$/,re=/^P[1-9][0-9]*$/,Me=/^(?:main|master|develop|trunk|release(?:\/.*)?|epic\/.*)$/,$=".neocortex/pending-epic-claims.json",ae=128*1024,Ne=/^[a-f0-9]{64}$/;function se(c){if(!c||typeof c!="object"||Array.isArray(c))return;const e=c;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(!Ne.test(a)||!s||typeof s!="object"||Array.isArray(s))return;return t}}function q(c){return`docs/epics/epic-${c}.md`}function Le(c,e){if(e===q(c)||e===".neocortex/state.json"||e===$||e==="NEOCORTEX.md")return!0;const r=`docs/stories/${c}.`;if(e.startsWith(r)&&!e.slice(r.length).includes("/"))return!0;const t=`.neocortex/planning/epic-${c}/`;return e.startsWith(t)&&!e.split("/").includes("..")}class oe extends Error{reasonCode;constructor(e){super(e),this.reasonCode=e}}function o(c){throw new oe(c)}function ze(){const c={...process.env};for(const e of["GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_COMMON_DIR","GIT_OBJECT_DIRECTORY"])delete c[e];return c.GIT_TERMINAL_PROMPT="0",c}function rt(c,e){return f(c,e)}function f(c,e,r=Q){return new Promise(t=>{he("git",[...e],{cwd:c,encoding:"utf8",env:{...ze(),LC_ALL:"C"},maxBuffer:8*1024*1024,timeout:r,windowsHide:!0},(a,s,i)=>{const n=a?Ge(a,String(i??"")):void 0;t({ok:!a,stdout:String(s??""),exitCode:a?typeof a.code=="number"?a.code:-1:0,...n?{failure:n}:{}})})})}function Ge(c,e){return c.code==="ENOSPC"||c.code==="EDQUOT"||/\b(?:No space left on device|Disk quota exceeded|ENOSPC|EDQUOT)\b/i.test(e)?"capacity":c.killed===!0&&c.signal==="SIGTERM"?"timeout":void 0}async function p(c,e){return(await f(c,e)).ok}async function ie(c,e,r){if(!P.test(e)||!P.test(r))return"unverified";const t=await f(c,["merge-base","--is-ancestor",e,r]);if(t.ok)return"contained";if(t.exitCode!==1)return"unverified";const a=await f(c,["rev-parse","--is-shallow-repository"]);return a.ok&&a.stdout.trim()==="false"?"divergent":"unverified"}async function b(c,e,r){const t=await f(c,e);return t.ok||o(r),t.stdout.trim()}async function ne(c,e){return p(c,["merge","--ff-only","--no-autostash","--no-overwrite-ignore",e])}async function qe(c,e,r){const t=c.worktreePath,a=R(t,C),s=R(t,".neocortex"),i=R(s,L),n=R(i,"original.json"),h=R(i,"merged.json"),l=await D(a).catch(()=>{});if(!l?.isFile()||l.nlink!==1||l.size>ve||await S(a)!==a||!await p(t,["diff","--cached","--quiet"])||await p(t,["diff","--quiet","--",C])||await p(t,["cat-file","-e",`${r}:.neocortex/${L}`])||await b(t,["rev-parse","HEAD"],"story-worktree-git-failed")!==e)return!1;const[d,w,y]=await Promise.all([f(t,["show",`${e}:${C}`]),f(t,["show",`${r}:${C}`]),f(t,["show","-s","--format=%cI",r])]);if(!d.ok||!w.ok||!y.ok||d.stdout===w.stdout)return!1;const u=await _(a),v=Ie({base:d.stdout,epic:w.stdout,story:u,storyId:c.storyId,epicId:c.epicId,aggregateTimestamp:y.stdout.trim()});if(v===void 0)return!1;try{await ue(i,{mode:448})}catch{return!1}let m=!1,g=!1;try{const I=await pe(h,"wx",l.mode&511);try{await I.writeFile(v,"utf8"),await I.sync()}finally{await I.close()}if(!(await _(a)).equals(u))return!1;await H(a,n),m=!0,(!(await _(n)).equals(u)||!await p(t,["checkout-index","--",C]))&&o("story-worktree-sync-state-backup-preserved"),await ne(t,r);const k=await b(t,["rev-parse","HEAD"],"story-worktree-git-failed"),A=k===r?w.stdout:k===e?d.stdout:void 0;return(A===void 0||!(await _(a)).equals(Buffer.from(A)))&&o("story-worktree-sync-state-backup-preserved"),await H(k===r?h:n,a),g=!0,k===r}finally{(!m||g)&&(await T(n).catch(()=>{}),await T(h).catch(()=>{}),await me(i).catch(()=>{}))}}function x(c){return le("sha256").update(c).digest("hex")}async function V(c){try{return await D(c),"present"}catch(e){return e.code==="ENOENT"?"enoent":"unknown"}}async function j(c){try{return await D(c),!0}catch{return!1}}function ce(c){return new Promise(e=>setTimeout(e,c))}function de(c){const e=[];for(const r of c.split("\0\0")){const t=r.split("\0").filter(Boolean),a=t.find(n=>n.startsWith("worktree "))?.slice(9);if(!a)continue;const s=t.find(n=>n.startsWith("HEAD "))?.slice(5),i=t.find(n=>n.startsWith("branch "))?.slice(7);e.push({path:a,...s?{head:s}:{},...i?.startsWith("refs/heads/")?{branch:i.slice(11)}:{}})}return e}function Ve(c){return c.length>0&&c.length<=512&&!F(c)&&!/^[A-Za-z]:/.test(c)&&!c.includes("\\")&&!c.split("/").some(e=>e===".."||e==="")}class at{options;projectRoot;now;randomNonce;platform;constructor(e){this.options=e,this.projectRoot=ke(e.projectRoot),this.now=e.now??(()=>new Date),this.randomNonce=e.randomNonce??(()=>fe(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();let s=(await this.readDocument()).storyWorktrees?.entries[r.leaseId];if(s?.state==="active"&&s.baseSha===e.baseSha&&s.graphRevision===e.graphRevision&&s.epicId===r.epicId&&s.storyId===r.storyId&&s.executionBranch===r.executionBranch&&s.temporaryBranch===r.temporaryBranch&&await this.ownershipProven(s,t))return await this.assertReusableBase(t,s,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.storyId,e.baseSha),await this.assertNoCleanupInProgress(t,s.leaseId),{ok:!0,value:this.leaseValue(s,!0),privatePath:s.worktreePath};await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.storyId,e.baseSha);const i=xe({platform:this.platform,env:this.options.env??process.env,homedir:this.options.homedir??ye(),...this.options.worktreeRoot?{override:this.options.worktreeRoot}:{}});i.ok||o(i.reasonCode);const n=U({root:i.value,hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});n.ok||o(n.reasonCode);const h=await _e(i.value,this.platform);h.ok||o(h.reasonCode);const l=U({root:await S(i.value),hash8:r.hash8,repositoryRoot:t.mainRoot,platform:this.platform});l.ok||o(l.reasonCode);const d=l.value;s=(await this.readDocument()).storyWorktrees?.entries[r.leaseId],s&&(await this.reclaimStaleReservation(s,t)||o("story-worktree-entry-conflict")),await j(d)&&o("story-worktree-path-occupied"),await p(t.mainRoot,["show-ref","--verify","--quiet",`refs/heads/${r.temporaryBranch}`])&&o("story-worktree-branch-exists");const w=this.randomNonce(),y=this.now(),u={schemaVersion:1,leaseId:r.leaseId,epicId:r.epicId,storyId:r.storyId,dispatchDigest:x(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,w),nonceDigest:x(w),baseSha:e.baseSha,graphRevision:e.graphRevision,state:"creating",acquiredAt:y.toISOString(),expiresAt:new Date(y.getTime()+(this.options.ttlMs??Z)).toISOString()};await this.mutate(m=>{const g=O(m);(g.entries[u.leaseId]||Object.values(g.entries).some(I=>I.worktreePath===d))&&o("story-worktree-entry-conflict"),g.entries[u.leaseId]=u});let v=!1;try{const m=await f(t.mainRoot,["worktree","add","-b",r.temporaryBranch,d,e.baseSha],ee);m.ok||(m.failure==="capacity"&&o("story-worktree-capacity-exhausted"),m.failure==="timeout"&&o("story-worktree-checkout-timed-out"),o("story-worktree-add-failed")),v=!0,this.platform!=="win32"?await we(d,448):await this.enableWindowsLongPaths(t,d);const g=await this.prepareSharedResolution(t,d,e.baseSha),I=await this.worktreeGitDir(d,t);await M(R(I,N),`${JSON.stringify({schemaVersion:1,leaseId:u.leaseId,nonce:w})}
|
|
2
|
+
`,{flag:"wx",mode:384});const k={...u,state:"active"};return await this.mutate(A=>{const E=O(A),B=E.entries[u.leaseId];(!B||B.state!=="creating"||B.nonceDigest!==u.nonceDigest)&&o("story-worktree-entry-conflict"),E.entries[u.leaseId]=k}),{ok:!0,value:{...this.leaseValue(k,!1),sharedResolution:g},privatePath:d}}catch(m){throw await this.rollbackCreate(t,u,v),m}})}async adopt(e){return this.guard(async()=>{const r=this.identity(e),t=await this.repository();await this.assertAuthorizedBase(t,r.executionBranch,e.baseSha,e.graphRevision),await this.assertPlanningInBase(t,e.epicId,e.storyId,e.baseSha),(typeof e.worktreePath!="string"||!F(e.worktreePath))&&o("story-worktree-adopt-path-invalid");let a;try{a=await S(e.worktreePath)}catch{o("story-worktree-adopt-unregistered")}const s=await this.listWorktrees(t),i=s.findIndex(E=>this.samePath(E.path,a));i===0&&o("story-worktree-adopt-main-refused"),i<0&&o("story-worktree-adopt-unregistered");const n=s[i];n.branch||o("story-worktree-adopt-detached"),(!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(n.branch)||n.branch.includes(".."))&&o("story-worktree-adopt-branch-invalid"),(Me.test(n.branch)||n.branch===s[0]?.branch||await p(t.mainRoot,["config","--get",`branch.${n.branch}.remote`]))&&o("story-worktree-adopt-branch-protected");const l=(await this.readDocument()).storyWorktrees?.entries??{},d=l[r.leaseId];if(d){if(this.samePath(d.worktreePath,a)&&d.state==="active"&&await this.ownershipProven(d,t))return(d.graphRevision!==e.graphRevision||d.baseSha!==e.baseSha)&&o("story-worktree-reuse-base-divergent"),await p(a,["merge-base","--is-ancestor",e.baseSha,"HEAD"])||o("story-worktree-base-divergent"),await this.assertNoCleanupInProgress(t,d.leaseId),await this.mutate(E=>{this.bindLeaseEvidence(E,d)}),{ok:!0,value:this.leaseValue(d,!0),privatePath:d.worktreePath};o("story-worktree-entry-conflict")}Object.values(l).some(E=>this.samePath(E.worktreePath,a))&&o("story-worktree-entry-conflict"),(await f(a,["status","--porcelain=v1","--untracked-files=all","-z"])).ok||o("story-worktree-git-failed");let y;await this.clean(a)||(y=await this.reconciledClaimsSidecar(a),y===void 0&&o("native-worktree-dirty"));const u=await b(a,["rev-parse","HEAD"],"story-worktree-git-failed");u!==e.baseSha&&!await p(a,["merge-base","--is-ancestor",u,e.baseSha])&&o(await this.planningOnlyDrift(a,e.epicId,u,e.baseSha)?"epic-planning-not-in-base":"native-worktree-base-mismatch");const v=await this.worktreeGitDir(a,t),m=R(v,N),g=await j(m);g&&await this.markerLeaseId(m)!==r.leaseId&&o("story-worktree-marker-exists"),y!==void 0&&(await this.restoreClaimsSidecar(a,y),await this.clean(a)||o("native-worktree-dirty"));let I;u!==e.baseSha&&(await this.alignWorktree(a,n.branch,u,e.baseSha),I=Object.freeze({mode:"fast-forward",fromSha:u,toSha:e.baseSha}));const k=R(a,"node_modules","@neocortex","shared"),A=await D(k).then(()=>!0,()=>!1);try{return await this.adoptAligned({facts:t,identity:r,input:e,canonical:a,temporaryBranch:n.branch,markerPath:m,orphanMarker:g,alignment:I})}catch(E){throw!A&&await D(k).then(B=>B.isSymbolicLink(),()=>!1)&&await T(k).catch(()=>{}),I&&await this.restoreAlignment(a,n.branch,u,e.baseSha),E}})}async alignWorktree(e,r,t,a){const s=await f(e,["diff","--name-only","--no-renames","-z",t,a]),i=await f(e,["ls-files","--others","--ignored","--exclude-standard","--directory","-z"]);(!s.ok||!i.ok)&&o("native-worktree-align-failed");const n=i.stdout.split("\0").filter(Boolean).map(d=>d.replace(/\/$/,""));s.stdout.split("\0").filter(Boolean).some(d=>n.some(w=>d===w||d.startsWith(`${w}/`)||w.startsWith(`${d}/`)))&&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 b(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:i,markerPath:n,orphanMarker:h,alignment:l}=e,d=await this.prepareSharedResolution(r,s,a.baseSha);h&&await T(n);const w=this.randomNonce(),y=this.now(),u={schemaVersion:1,leaseId:t.leaseId,epicId:t.epicId,storyId:t.storyId,dispatchDigest:x(t.dispatchId),hash8:t.hash8,executionBranch:t.executionBranch,temporaryBranch:i,worktreeRef:t.worktreeRef,worktreePath:s,workspaceMechanism:"native_subagent_worktree",ownerId:this.ownerId(a.ownerId,w),nonceDigest:x(w),baseSha:a.baseSha,graphRevision:a.graphRevision,state:"active",acquiredAt:y.toISOString(),expiresAt:new Date(y.getTime()+(this.options.ttlMs??Z)).toISOString()};await M(n,`${JSON.stringify({schemaVersion:1,leaseId:u.leaseId,nonce:w})}
|
|
3
|
+
`,{flag:"wx",mode:384});try{await this.mutate(m=>{const g=O(m);(g.entries[u.leaseId]||Object.values(g.entries).some(I=>this.samePath(I.worktreePath,s)))&&o("story-worktree-entry-conflict"),g.entries[u.leaseId]=u,this.bindLeaseEvidence(m,u)})}catch(m){throw await this.removeOwnMarker(n,w),m}const v={...this.leaseValue(u,!1),sharedResolution:d};return{ok:!0,value:l?{...v,alignment:l}:v,privatePath:s}}async sync(e){return this.guard(async()=>{const r=await this.repository(),t=await this.ownedEntry(e.leaseId,r);let a=e.integratedSha;if(e.directive!==void 0){const h=e.directive;(!X(e.directive)||h.epicId!==t.epicId||h.storyId!==t.storyId||a!==void 0&&a!==h.integratedEpicHeadSha)&&o("story-worktree-directive-invalid"),a=String(h.integratedEpicHeadSha)}if(e.automatic){const h=e.directive;(!X(h)||h.graphRevision!==t.graphRevision||Array.isArray(h.dependsOn)&&h.dependsOn.includes(t.storyId)||h.directiveId!==J(We,{epicId:h.epicId,storyId:h.storyId,dependsOn:h.dependsOn,integratedEpicHeadSha:h.integratedEpicHeadSha,graphRevision:h.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 p(r.mainRoot,["merge-base","--is-ancestor",a,s])||o("story-worktree-sync-sha-unintegrated");let i="already-synced";if(e.automatic){await D(R(t.worktreePath,".neocortex",L)).catch(()=>{})&&o("story-worktree-sync-state-backup-preserved");const h=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");h!==a&&(await p(t.worktreePath,["merge-base","--is-ancestor",h,a])||o("story-worktree-sync-not-fast-forward"),!await ne(t.worktreePath,a)&&!await qe(t,h,a)&&o("story-worktree-sync-conflict-preserved"),i="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 d=(await f(t.worktreePath,["diff","--name-only","--diff-filter=U","-z"])).stdout.split("\0").filter(Ve).sort().slice(0,He);return d.length===0&&o("story-worktree-sync-failed"),{ok:!1,reasonCode:"story-worktree-sync-conflict",conflictPaths:d}}i="synced"}const n=await b(t.worktreePath,["rev-parse","HEAD"],"story-worktree-git-failed");return e.automatic&&n!==a&&o("story-worktree-sync-head-raced"),await this.mutate(h=>{const l=O(h),d=l.entries[t.leaseId];(!d||d.nonceDigest!==t.nonceDigest)&&o("story-worktree-entry-conflict"),l.entries[t.leaseId]={...d,syncedSha:a}}),{ok:!0,value:{leaseId:t.leaseId,outcome:i,integratedSha:a,headSha:n}}})}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&&!G.test(e.leaseId)&&o("story-worktree-lease-invalid"),e.epicId!==void 0&&!re.test(e.epicId)&&o("story-worktree-identity-invalid"),e.storyId!==void 0&&(typeof e.storyId!="string"||!W.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,i)=>s.leaseId.localeCompare(i.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"||!W.test(e.storyId))&&o("story-worktree-identity-invalid");const r=await this.repository();let t;try{t=await S(await b(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 b(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 i;t.workspaceMechanism==="native_subagent_worktree"?i="story-worktree-adopted-branch-preserved":await p(r.mainRoot,["update-ref","-d",`refs/heads/${t.temporaryBranch}`,a])||(i="story-worktree-branch-moved");const n=i===void 0,h=this.now().toISOString(),l={schemaVersion:1,kind:"cleanup-receipt",receiptId:`swc-${x(`${t.leaseId}|${t.nonceDigest}|${h}`).slice(0,24)}`,epicId:t.epicId,storyId:t.storyId,leaseId:t.leaseId,trigger:"success",worktreeRemoved:!0,localBranchRemoved:n,remoteBranchRemoved:!1,...i?{preservedReasonCode:i}:{},cleanedAt:h};return Ee(l)||o("story-worktree-receipt-invalid"),await this.mutate(d=>{const w=O(d),y=w.entries[t.leaseId];for(y&&y.nonceDigest===t.nonceDigest&&delete w.entries[t.leaseId],w.cleanupReceipts.push({...l});w.cleanupReceipts.length>Re;)w.cleanupReceipts.shift()}),{ok:!0,value:{leaseId:t.leaseId,receipt:l,receiptDigest:Y(l)}}})}async probe(e){return this.guard(async()=>{(typeof e!="string"||!G.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,A)=>A>0&&this.samePath(k.path,t.worktreePath)),i=a.some(k=>k.branch===t.temporaryBranch),n=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.temporaryBranch}^{commit}`]),h=n.ok&&P.test(n.stdout.trim())?n.stdout.trim():void 0,l=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${t.executionBranch}^{commit}`]),d=l.ok&&P.test(l.stdout.trim())?l.stdout.trim():void 0,w=await V(t.worktreePath),y=w==="present",u=t.state==="active"&&y&&await this.ownershipProven(t,r);let v,m;if(u){const k=await f(t.worktreePath,["rev-parse","HEAD"]);k.ok&&P.test(k.stdout.trim())&&(v=k.stdout.trim()),m=await this.clean(t.worktreePath)}const g=v??(y?void 0:h),I=g&&d?await p(r.mainRoot,["merge-base","--is-ancestor",g,d]):void 0;return{ok:!0,value:{entry:t,facts:r,ownership:u?"proven":"unproven",pathExists:y,pathAbsence:w,registered:s,...h?{branchSha:h}:{},branchCheckedOut:i,...v?{headSha:v}:{},...m!==void 0?{clean:m}:{},...d?{epicHead:d}:{},...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 oe)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=Te(e);return r.ok||o(r.reasonCode),e.ownerId!==void 0&&!te.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-${x(`owner|${r}`).slice(0,16)}`}async repository(){let e;try{e=await S(this.projectRoot)}catch{o("story-worktree-project-root-invalid")}const r=await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-project-root-invalid"),t=await S(r),s=de(await b(e,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"))[0];return s||o("story-worktree-project-root-invalid"),{mainRoot:await S(s.path),commonDir:t}}async assertAuthorizedBase(e,r,t,a){(typeof a!="string"||!z.test(a))&&o("story-worktree-graph-revision-invalid"),(typeof t!="string"||!P.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r),i=await ie(e.mainRoot,t,s);i!=="contained"&&o(i==="divergent"?"story-worktree-base-divergent":"story-worktree-base-unverified")}async assertReusableBase(e,r,t,a){(!z.test(a)||!P.test(t)||!await p(e.mainRoot,["cat-file","-e",`${t}^{commit}`]))&&o("story-worktree-base-invalid");const s=await this.epicHead(e,r.executionBranch),i=await ie(e.mainRoot,t,s);i!=="contained"&&(i!=="divergent"&&o("story-worktree-base-unverified"),(r.syncedSha!==s||!await p(r.worktreePath,["merge-base","--is-ancestor",t,"HEAD"])||!await p(r.worktreePath,["merge-base","--is-ancestor",s,"HEAD"]))&&o("story-worktree-base-divergent"))}async epicHead(e,r){return b(e.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${r}^{commit}`],"story-worktree-epic-branch-missing")}async worktreeGitDir(e,r){const t=await S(await b(e,["rev-parse","--absolute-git-dir"],"story-worktree-git-failed")),a=await S(await b(e,["rev-parse","--path-format=absolute","--git-common-dir"],"story-worktree-git-failed")),s=R(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,i)=>{for(let n=1;n<=8;n++){if(await p(s,i))return;await ce(25*n)}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 S(e.worktreePath)!==e.worktreePath)return!1;const t=await this.worktreeGitDir(e.worktreePath,r),a=JSON.parse(await _(R(t,N),"utf8"));if(a.schemaVersion!==1||a.leaseId!==e.leaseId||typeof a.nonce!="string"||x(a.nonce)!==e.nonceDigest)return!1;const s=await this.listWorktrees(r),i=s.findIndex(n=>this.samePath(n.path,e.worktreePath));return i>0&&s[i].branch===e.temporaryBranch}catch{return!1}}async ownedEntry(e,r){(typeof e!="string"||!G.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=R(e,$);try{const a=await D(t);if(!a.isFile()||a.isSymbolicLink()||a.size<1||a.size>ae)return;const s=await f(e,["show",`HEAD:${$}`]);if(!s.ok||s.stdout.length>ae)return;const i=se(JSON.parse(await _(t,"utf8"))),n=se(JSON.parse(s.stdout));if(!i||!n)return;const h=Object.keys(i);return h.length>=Object.keys(n).length||!h.every(l=>Object.hasOwn(n,l)&&ge(i[l],n[l]))?void 0:s.stdout}catch{return}}async restoreClaimsSidecar(e,r){const t=R(e,$),a=`${t}.${process.pid}.${this.randomNonce().slice(0,16)}.tmp`;try{const s=(await D(t)).mode&511;await M(a,r,{encoding:"utf8",flag:"wx",mode:s}),await H(a,t)}catch{await T(a).catch(()=>{}),o("native-worktree-dirty")}}async planningMissingFromBase(e,r,t,a){const s=q(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,a){const s=[q(r),`docs/stories/${t}.story.md`],i=async d=>{const w=await b(e.mainRoot,["ls-tree","--full-tree","-r","--name-only","-z",d,"--",...s],"story-worktree-base-unverified");return new Set(w.split("\0"))},[n,h,l]=await Promise.all([i(a),i("HEAD"),Promise.all(s.map(async d=>await j(R(this.projectRoot,d))||await j(R(e.mainRoot,d))))]);s.some((d,w)=>!n.has(d)&&(h.has(d)||l[w]))&&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 i=await f(e,["diff","--name-only","--no-renames","-z",s.stdout.trim(),t]);if(!i.ok)return!1;const n=i.stdout.split("\0").filter(Boolean);return n.length>0&&n.every(h=>Le(r,h))}async clean(e){const r=await f(e,["status","--porcelain=v1","--untracked-files=all","-z"]);return!r.ok||r.stdout.length>0?!1:!(await f(e,["rev-parse","-q","--verify","MERGE_HEAD"])).ok}async project(e,r){const t={leaseId:e.leaseId,epicId:e.epicId,storyId:e.storyId,worktreeId:`nxwt-${e.hash8}`,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,workspaceMechanism:e.workspaceMechanism,state:e.state,baseSha:e.baseSha,...e.syncedSha?{syncedSha:e.syncedSha}:{},ownership:"unproven",expiresAt:e.expiresAt};if(e.state!=="active"||!await this.ownershipProven(e,r))return t;const a=await f(e.worktreePath,["rev-parse","HEAD"]),s=a.stdout.trim();if(!a.ok||!P.test(s))return{...t,ownership:"proven"};const i=await f(r.mainRoot,["rev-parse","--verify","--quiet",`refs/heads/${e.executionBranch}^{commit}`]),n=i.ok&&await p(r.mainRoot,["merge-base","--is-ancestor",s,i.stdout.trim()]);return{...t,ownership:"proven",headSha:s,clean:await this.clean(e.worktreePath),integrated:n}}bindLeaseEvidence(e,r){try{be(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:Y(t),worktreeId:a,worktreeRef:e.worktreeRef,temporaryBranch:e.temporaryBranch,baseSha:e.baseSha,reused:r,env:{[De]: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 Oe({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){const a=l=>l.filter(d=>d.branch===r.temporaryBranch||this.samePath(d.path,r.worktreePath)),s=await this.listWorktrees(e).catch(()=>{});if(!s)return;const i=a(s),[n]=i;if(t&&i.length===1&&n?.branch===r.temporaryBranch&&n.head===r.baseSha&&this.samePath(n.path,r.worktreePath)){if(!await p(e.mainRoot,["worktree","remove",r.worktreePath]))return}else if(i.length>0)return;if(await V(r.worktreePath)!=="enoent")return;const h=`refs/heads/${r.temporaryBranch}`;!await p(e.mainRoot,["update-ref","-d",h,r.baseSha])&&!await this.isTemporaryBranchAbsent(e,h)||await this.mutate(l=>{const d=O(l),w=d.entries[r.leaseId];w?.state==="creating"&&w.nonceDigest===r.nonceDigest&&delete d.entries[r.leaseId],Se(l)}).catch(()=>{})}async removeOwnMarker(e,r){try{JSON.parse(await _(e,"utf8")).nonce===r&&await T(e)}catch{}}async listWorktrees(e){const r=de(await b(e.mainRoot,["worktree","list","--porcelain","-z"],"story-worktree-git-failed"));return Promise.all(r.map(async t=>{const a=this.platform==="win32"?t.path.replace(/\//g,"\\"):t.path;try{return{...t,path:await S(a)}}catch{return{...t,path:a}}}))}samePath(e,r){if(this.platform==="win32"){const t=a=>a.replace(/\//g,"\\").toLowerCase();return t(e)===t(r)}return this.platform==="darwin"?e.toLowerCase()===r.toLowerCase():e===r}async markerLeaseId(e){try{const r=JSON.parse(await _(e,"utf8"));return typeof r.leaseId=="string"?r.leaseId:void 0}catch{return}}async reclaimStaleReservation(e,r){if(e.state!=="creating"||this.now().getTime()-Date.parse(e.acquiredAt)<je)return!1;const t=await this.listWorktrees(r).catch(()=>{});if(!(t&&!t.some(i=>i.branch===e.temporaryBranch||this.samePath(i.path,e.worktreePath))&&await V(e.worktreePath)==="enoent"&&await this.isTemporaryBranchAbsent(r,`refs/heads/${e.temporaryBranch}`)))return!1;let s=!1;return await this.mutate(i=>{const n=O(i),h=n.entries[e.leaseId];h&&h.state==="creating"&&h.nonceDigest===e.nonceDigest&&(delete n.entries[e.leaseId],s=!0)}),s}async isTemporaryBranchAbsent(e,r){const t=await f(e.mainRoot,["for-each-ref","--format=%(refname)","--",r]);return t.ok&&!t.stdout.split(/\r?\n/).includes(r)}async readDocument(){return Ae(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 Pe(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 ce(t*Math.min(a,8)+Math.floor(Math.random()*t))}}}export{N as STORY_WORKTREE_MARKER_FILE,Be as STORY_WORKTREE_RECEIPT_DIGEST_DOMAIN,at as StoryWorktreeManager,Y as digestStoryWorktreeReceiptLocal,de as parseWorktreeList,rt as runStoryWorktreeGit,ie as storyWorktreeBaseAncestry,V as storyWorktreePathAbsence};
|
|
@@ -16,8 +16,8 @@ export interface PhaseTwoCheckpointEvidence {
|
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
18
|
* The fingerprint covers HEAD, the complete tracked diff, the path and content
|
|
19
|
-
* of non-ignored untracked files, and the public QA artifact. A completed
|
|
20
|
-
*
|
|
21
|
-
*
|
|
19
|
+
* of non-ignored untracked files, and the public QA artifact. A completed
|
|
20
|
+
* worker that reported a QA block can be reused only under the same QA policy
|
|
21
|
+
* release. Successful checkpoints keep their original fingerprint.
|
|
22
22
|
*/
|
|
23
|
-
export declare function collectPhaseTwoCheckpointEvidence(worktreePath: string, storyId: string): PhaseTwoCheckpointEvidence;
|
|
23
|
+
export declare function collectPhaseTwoCheckpointEvidence(worktreePath: string, storyId: string, qaPolicyRelease?: string): PhaseTwoCheckpointEvidence;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync as
|
|
1
|
+
import{execFileSync as q}from"node:child_process";import{createHash as h}from"node:crypto";import{lstatSync as y,readFileSync as g,readlinkSync as E,realpathSync as l}from"node:fs";import{isAbsolute as k,join as A,relative as B}from"node:path";const S=32*1024*1024,v=2*1024*1024,w=/^[a-z0-9][a-z0-9._:-]{0,127}$/;function m(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function C(e){return typeof e=="string"&&w.test(e)?e:void 0}function b(e,n){if(Array.isArray(e))for(const t of e){const o=m(t);if(!o||!n(o))continue;const s=C(o.reasonCode);if(s)return s}}function x(e,n){if(!e)return{qaStatus:"missing",reasonCode:"story-worktree-phase-two-checkpoint-evidence-missing"};let t;try{t=m(JSON.parse(e.toString("utf8")))}catch{return{qaStatus:"invalid",reasonCode:"story-worktree-phase-two-checkpoint-evidence-invalid"}}if(t?.schemaVersion!==2||t.storyId!==n||t.publicSafe!==!0)return{qaStatus:"invalid",reasonCode:"story-worktree-phase-two-checkpoint-evidence-invalid"};const o=b(t.blockingChecks,()=>!0),s=b(t.nonBlockingChecks,r=>r.requiredByReleaseClaim===!0&&r.safeToContinueYoloop===!1),i=Array.isArray(t.reasonCodes)?t.reasonCodes.map(C).find(r=>!!r):void 0;return t.status==="qa-failed-block"||t.safeToContinueYoloop===!1?{qaStatus:"blocked",reasonCode:o??s??i??"story-worktree-phase-two-qa-blocked"}:t.status==="qa-passed"&&t.safeToContinueYoloop===!0&&Array.isArray(t.blockingChecks)&&t.blockingChecks.length===0?{qaStatus:"passed"}:{qaStatus:"pending",reasonCode:s??i??"story-worktree-phase-two-checkpoint-pending"}}function p(e,n){try{return q("git",[...n],{cwd:e,encoding:"buffer",maxBuffer:S,stdio:["ignore","pipe","ignore"]})}catch{return}}function _(e,n){try{const t=l(e),o=A(t,".neocortex","stories",n,"qa-gate-result.json"),s=y(o);if(!s.isFile()||s.isSymbolicLink())return;const i=l(o),r=B(t,i);if(!r||k(r)||r===".."||r.startsWith(`..${process.platform==="win32"?"\\":"/"}`))return;const a=g(i);return a.length<=v?a:void 0}catch{return}}function u(e,n,t){if(e.update(n).update("\0"),!t){e.update("unavailable\0");return}e.update(String(t.length)).update("\0").update(t).update("\0")}function R(e,n){if(n)try{const t=Buffer.from(`${l(e)}/`),o=h("sha256");if(n.length===0)return o.digest();let s=0;for(const i of n.subarray(0,n.length-+(n.at(-1)===0)).toString("utf8").split("\0")){if(!i||k(i)||i===".."||i.startsWith("../")||i.includes("/../"))return;const r=Buffer.from(i),a=Buffer.concat([t,r]),c=y(a),f=c.isSymbolicLink()?E(a,{encoding:"buffer"}):c.isFile()?g(a):void 0;if(!f||(s+=r.length+f.length,s>S))return;u(o,"path",r),u(o,c.isSymbolicLink()?"symlink":"file",f)}return o.digest()}catch{return}}function F(e,n,t){const o=p(e,["rev-parse","--verify","HEAD"]),s=p(e,["diff","--binary","--full-index","--no-ext-diff","HEAD","--"]),i=p(e,["ls-files","--others","--exclude-standard","-z"]),r=R(e,i),a=_(e,n),c=x(a,n),f=c.qaStatus==="invalid"||c.qaStatus==="missing"?void 0:a,d=h("sha256");return d.update("neocortex-phase-two-checkpoint-fingerprint-v1\0"),d.update(n).update("\0"),u(d,"head",o),u(d,"tracked-diff",s),u(d,"untracked-state",r),u(d,`qa-${c.qaStatus}`,f),c.qaStatus==="blocked"&&t&&u(d,"qa-policy-release",Buffer.from(t)),{fingerprint:d.digest("hex"),physicalStateComplete:!!(o&&s&&i&&r),...c,publicSafe:!0}}export{F as collectPhaseTwoCheckpointEvidence};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as ee,randomBytes as te}from"node:crypto";import{isAbsolute as re,resolve as x}from"node:path";import{P205_RELEASE_GATE_BUDGETS as oe,P205_ROOT_INVOKE_TIMEOUT_MS as L}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as ae,AUTONOMOUS_GOVERNANCE_REASON_CODES as F,autonomousGovernanceMetadata as B,buildAutonomousGovernanceEnvelope as ne,readAutonomousGovernanceEnvelopeFromMetadata as V,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 T,hashPublicValue as O,redaction as c}from"./types.js";import{collectPhaseTwoCheckpointEvidence as ue}from"./phase-two-checkpoint-evidence.js";const me=L+60*1e3,le=30*1e3,fe=30*1e3,pe=L,ye=1,_e=3,z=l.STORY_WORKTREE_PHASE_BINDING_REQUIRED;function N(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:x(t)===x(e.cwd)&&x(t)!==x(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"}),Ie=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 P=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,he=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,Se=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),Ee=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),w=/(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,g=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function ze(e){const t=e.adapterRegistry??de(),r=C(e.limit??ye,1,10),n=C(e.leaseMs??me,1e3,oe.terminalWorkflowMaxDurationMs),a=C(e.staleLeaseAfterMs??le,0,1440*60*1e3),d=C(e.maxAttempts??_e,1,10),s=[],o=[],i=e.now(),u=be({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 h=new Set(e.attemptIds??[]),S=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(m=>m.directive_kind==="run_yolo").filter(m=>h.size===0||h.has(m.attempt_id)).slice(0,r);for(const m of S){const y=await Ce({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:m,registry:t,now:e.now,leaseMs:n,timeoutMs:C(e.timeoutMs??pe,1e3,72e5),backoffMs:C(e.backoffMs??fe,1e3,36e5),maxAttempts:d,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??Pe,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:S.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 be(e){let t=0,r=0;const n=[],a=[];for(const d of we(e.metadata)){if(!E(d)||d.kind!=="run_yolo")continue;const s=xe(d);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(N(o.executionMode)&&!e.storyWorktreeBindingValid){r+=1,a.push(z);continue}if(!e.store.jobExists(o.jobId)){r+=1,a.push(F.BYPASS_BLOCKED);continue}const i=De(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(i)){const y=o.storyId??R(o.targetRef),I=e.store.reconcileCompletedHeadlessExecutionReceipt({directiveHash:i,directiveKind:"run_yolo",jobId:o.jobId,targetKind:"story",targetRef:o.targetRef,...y?{storyId:y}:{}});if(!I.verified){r+=1,a.push(I.reasonCode);continue}n.some(b=>b.attemptId===I.attempt.attempt_id)||n.push(ge(I.attempt)),a.push(I.reasonCode,l.EXECUTION_COMPLETED);continue}const u=ne({autonomousKind:"run_yolo",source:Te(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??R(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:O(o.commandRef)}),f=se(e.store,u,e.nowIso,{requireExistingJob:!0});if(!f.ok){r+=1,a.push(f.reasonCode);continue}const h=G("attempt",o.idempotencyKey),S=G("exec",o.operationId),m=e.store.enqueueHeadlessExecutionAttempt({attemptId:h,executionId:S,jobId:o.jobId,directiveHash:i,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??R(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:Ne(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 ge(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 Ce(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 k(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 k(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=Ae(e);if(!s.ok)return k(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 k(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,h=u.retry?l.EXECUTION_BACKOFF:i.reasonCode,S=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,I={...i.hashes,directive:e.attempt.directive_hash};if(delete I.phaseTwoBinding,delete I.phaseTwoCheckpointFingerprint,y&&(I.phaseTwoBinding=y,e.adapterOptions?.cwd&&e.attempt.story_id)){const b=ue(e.adapterOptions.cwd,e.attempt.story_id);b.physicalStateComplete&&(I.phaseTwoCheckpointFingerprint=b.fingerprint)}return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:f,receiptStatus:S,reasonCode:h,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:I,redactionSummary:i.redactionSummary,relativePaths:i.relativePaths.length>0?i.relativePaths:[e.attempt.target_ref],runtimeId:i.runtimeId,modelId:i.modelId,runtimeSource:i.runtimeSource})}function Ae(e){const t=V(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=O(`*yolo @${e.attempt.target_ref}`),n=Object.keys(v).find(s=>t.envelope.hashes.command===O(`*yolo @${e.attempt.target_ref}${v[s]}`));if(n&&N(n)&&!e.storyWorktreeBindingValid)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:z,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=Re(e.attempt);if(!a.ok)return a;const d=ke(e);return d.ok?{ok:!0,input:{promptKind:n?Ie[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:T(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 ke(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=je(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 Re(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")),(!P.test(e.target_ref)||g.test(e.target_ref)||_.test(e.target_ref))&&t.push(c("targetRef","prompt_body","value-denied"));const r=R(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 xe(e){const t=[];for(const A of Object.keys(e))(!Se.has(A)||w.test(A))&&t.push(c(A,M(A),"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"),h=p(e,"storyId"),S=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")),U(a)||t.push(c("jobId","unsafe_key","value-denied")),U(d)||t.push(c("operationId","unsafe_key","value-denied")),U(s)||t.push(c("idempotencyKey","unsafe_key","value-denied")),(o!=="story"||!i||!P.test(i)||_.test(i))&&t.push(c("targetRef","prompt_body","value-denied")),S!==void 0&&!X(S)&&t.push(c("executionMode","unsafe_key","value-denied"));const m=E(e.metadata)?e.metadata:void 0,y=X(S)?S:void 0,I=y==="branchless_child_preparation"?"branchless_sandbox":"story_worktree";y&&(m?.governanceSource!=="delegated-subagent"||m.childWorkspace!==I||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 b=i?`*yolo @${i}${y?v[y]:""}`:void 0;(!u||u!==b||u.includes("@neocortex")||g.test(u)||_.test(u))&&t.push(c("commandRef","prompt_body","value-denied")),h&&i&&h!==R(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 $=Oe(e.runtime,t);e.attempts!==void 0&&D(e.attempts,"attempts",t),e.metadata!==void 0&&D(e.metadata,"metadata",t);const H=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,...h?{storyId:h}:{},...y?{executionMode:y}:{},...$?{runtime:$}:{},publicSummary:f,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...m?{metadata:m}:{},...H.length>0?{redactionSummary:H}:{},publicSafe:!0}}}function Te(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function Oe(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))(!Ee.has(d)||w.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)||g.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)||g.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 k(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===F.BYPASS_BLOCKED?{governanceEvidence:ae}:{},publicSummary:T(r.publicSummary)},i=V(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:T(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:u},receipt:{receiptId:`receipt-${j("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-${j("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:T(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 we(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 O(K({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,...N(e.executionMode)?{operationId:e.operationId,idempotencyKey:e.idempotencyKey}:{},runtime:e.runtime}))}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:E(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${K(e[t])}`).join(",")}}`:JSON.stringify(e)}function D(e,t,r){if(typeof e=="string"){(_.test(e)||g.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}`;w.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 P.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)||w.test(r)||_.test(r)||typeof n=="string"&&_.test(n)||(t[r]=n);return Object.keys(t).length>0?t:void 0}function R(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function je(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function Ne(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 U(e){return!!(e&&he.test(e)&&!_.test(e)&&!g.test(e))}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(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 j(e,t)}function Pe(e,t){return j(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 C(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{fe as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,me as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,ye as DEFAULT_HEADLESS_EXECUTION_LIMIT,_e as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,le as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,pe as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,z as RUN_YOLO_STORY_WORKTREE_BINDING_REQUIRED,G as headlessExecutionEntityId,ze as runYoloExecutionPhase};
|
|
1
|
+
import{createHash as ee,randomBytes as te}from"node:crypto";import{isAbsolute as re,resolve as x}from"node:path";import{P205_RELEASE_GATE_BUDGETS as oe,P205_ROOT_INVOKE_TIMEOUT_MS as L}from"../../../../shared/dist/yoloop/epic-terminal-git.js";import{AUTONOMOUS_GOVERNANCE_EVIDENCE_TAG as ae,AUTONOMOUS_GOVERNANCE_REASON_CODES as F,autonomousGovernanceMetadata as B,buildAutonomousGovernanceEnvelope as ne,readAutonomousGovernanceEnvelopeFromMetadata as V,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 T,hashPublicValue as O,redaction as c}from"./types.js";import{collectPhaseTwoCheckpointEvidence as ue}from"./phase-two-checkpoint-evidence.js";const me=L+60*1e3,le=30*1e3,fe=30*1e3,pe=L,ye=1,_e=3,z=l.STORY_WORKTREE_PHASE_BINDING_REQUIRED;function N(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:x(t)===x(e.cwd)&&x(t)!==x(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"}),Ie=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 P=/^docs\/stories\/[A-Za-z0-9._-]+\.story\.md$/,he=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/,Se=new Set(["schemaVersion","contractVersion","kind","commandClass","jobId","operationId","idempotencyKey","targetKind","targetRef","commandRef","storyId","executionMode","runtime","publicSummary","reasonCode","attempts","metadata","redactionSummary","publicSafe"]),Ee=new Set(["runtimeId","modelId","source","reasonCode","publicSafe"]),w=/(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,g=/(?:[;&|`$<>]|\$\(|\n|\r|\0)/;async function ze(e){const t=e.adapterRegistry??de(),r=C(e.limit??ye,1,10),n=C(e.leaseMs??me,1e3,oe.terminalWorkflowMaxDurationMs),a=C(e.staleLeaseAfterMs??le,0,1440*60*1e3),d=C(e.maxAttempts??_e,1,10),s=[],o=[],i=e.now(),m=be({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(...m.reasonCodes),o.push(...m.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 h=new Set(e.attemptIds??[]),S=e.store.listDueHeadlessExecutionAttempts({nowIso:e.now(),limit:Math.max(r*5,10)}).filter(u=>u.directive_kind==="run_yolo").filter(u=>h.size===0||h.has(u.attempt_id)).slice(0,r);for(const u of S){const y=await Ce({store:e.store,projectRoot:e.projectRoot,runnerId:e.runnerId,attempt:u,registry:t,now:e.now,leaseMs:n,timeoutMs:C(e.timeoutMs??pe,1e3,72e5),backoffMs:C(e.backoffMs??fe,1e3,36e5),maxAttempts:d,adapterOptions:e.adapterOptions,runtimeDefaults:e.runtimeDefaults,runtimeFallback:e.runtimeFallback,idFactory:e.idFactory??Pe,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(u=>u.outcome!=="failed")&&m.rejectedCount===0,enqueuedAttemptCount:m.enqueuedCount,dueAttemptCount:S.length,processedAttemptCount:o.slice(m.recoveredReceipts.length).filter(u=>u.outcome!=="ignored").length,recoveredAttemptIds:f.recoveredAttemptIds,receipts:o,reasonCodes:J(s.length>0?s:[l.OK]),publicSafe:!0}}function be(e){let t=0,r=0;const n=[],a=[];for(const d of we(e.metadata)){if(!E(d)||d.kind!=="run_yolo")continue;const s=xe(d);if(!s.ok){r+=1,a.push(s.reasonCode);continue}const o=s.directive;if(N(o.executionMode)&&!e.storyWorktreeBindingValid){r+=1,a.push(z);continue}if(!e.store.jobExists(o.jobId)){r+=1,a.push(F.BYPASS_BLOCKED);continue}const i=De(o);if(e.store.hasCompletedHeadlessExecutionDirectiveHash(i)){const y=o.storyId??R(o.targetRef),I=e.store.reconcileCompletedHeadlessExecutionReceipt({directiveHash:i,directiveKind:"run_yolo",jobId:o.jobId,targetKind:"story",targetRef:o.targetRef,...y?{storyId:y}:{}});if(!I.verified){r+=1,a.push(I.reasonCode);continue}n.some(b=>b.attemptId===I.attempt.attempt_id)||n.push(ge(I.attempt)),a.push(I.reasonCode,l.EXECUTION_COMPLETED);continue}const m=ne({autonomousKind:"run_yolo",source:Te(o.metadata,"headless-run-yolo"),targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??R(o.targetRef),jobId:o.jobId,operationSeed:o.operationId,commandHash:O(o.commandRef)}),f=se(e.store,m,e.nowIso,{requireExistingJob:!0});if(!f.ok){r+=1,a.push(f.reasonCode);continue}const h=G("attempt",o.idempotencyKey),S=G("exec",o.operationId),u=e.store.enqueueHeadlessExecutionAttempt({attemptId:h,executionId:S,jobId:o.jobId,directiveHash:i,directiveKind:"run_yolo",commandClass:o.commandClass,targetKind:"story",targetRef:o.targetRef,storyId:o.storyId??R(o.targetRef),runtimeId:o.runtime?.runtimeId,modelId:o.runtime?.modelId,runtimeSource:Ne(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(m,{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(!u.accepted){r+=1,a.push(u.reasonCode??"queue-cap-reached");continue}u.inserted&&(t+=1),a.push(l.OK)}return{enqueuedCount:t,rejectedCount:r,recoveredReceipts:n,reasonCodes:J(a)}}function ge(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 Ce(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 k(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 k(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=Ae(e);if(!s.ok)return k(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 k(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 m=ve(e.attempt,i,e.maxAttempts,e.backoffMs,e.now()),f=m.retry?"backoff":i.status,h=m.retry?l.EXECUTION_BACKOFF:i.reasonCode,S=f==="completed"?"applied":f==="backoff"?"deferred":f==="skipped"?"ignored":"failed",{phaseTwoCompletion:u}=e,y=f==="completed"&&e.storyWorktreeBindingValid&&s.input.promptKind==="yolo-story-worktree-phase-2"&&u?.attemptId===e.attempt.attempt_id&&/^[a-f0-9]{64}$/.test(u.digest)?u.digest:void 0,I={...i.hashes,directive:e.attempt.directive_hash};if(delete I.phaseTwoBinding,delete I.phaseTwoCheckpointFingerprint,y&&(I.phaseTwoBinding=y,e.adapterOptions?.cwd&&e.attempt.story_id)){const b=ue(e.adapterOptions.cwd,e.attempt.story_id,u?.qaPolicyRelease);b.physicalStateComplete&&(I.phaseTwoCheckpointFingerprint=b.fingerprint)}return k(e.store,e.attempt,{leaseId:r,runnerId:e.runnerId,status:f,receiptStatus:S,reasonCode:h,publicSummary:m.retry?"Headless run_yolo execution scheduled bounded retry after transient adapter outcome.":i.publicSummary,completedAt:e.now(),durationMs:i.durationMs,notBeforeAt:m.notBeforeAt,retryCount:m.retryCount,counts:i.counts,hashes:I,redactionSummary:i.redactionSummary,relativePaths:i.relativePaths.length>0?i.relativePaths:[e.attempt.target_ref],runtimeId:i.runtimeId,modelId:i.modelId,runtimeSource:i.runtimeSource})}function Ae(e){const t=V(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=O(`*yolo @${e.attempt.target_ref}`),n=Object.keys(v).find(s=>t.envelope.hashes.command===O(`*yolo @${e.attempt.target_ref}${v[s]}`));if(n&&N(n)&&!e.storyWorktreeBindingValid)return{ok:!1,status:"failed",receiptStatus:"failed",reasonCode:z,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=Re(e.attempt);if(!a.ok)return a;const d=ke(e);return d.ok?{ok:!0,input:{promptKind:n?Ie[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:T(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 ke(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=je(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 Re(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")),(!P.test(e.target_ref)||g.test(e.target_ref)||_.test(e.target_ref))&&t.push(c("targetRef","prompt_body","value-denied"));const r=R(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 xe(e){const t=[];for(const A of Object.keys(e))(!Se.has(A)||w.test(A))&&t.push(c(A,M(A),"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"),m=p(e,"commandRef"),f=p(e,"publicSummary"),h=p(e,"storyId"),S=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")),U(a)||t.push(c("jobId","unsafe_key","value-denied")),U(d)||t.push(c("operationId","unsafe_key","value-denied")),U(s)||t.push(c("idempotencyKey","unsafe_key","value-denied")),(o!=="story"||!i||!P.test(i)||_.test(i))&&t.push(c("targetRef","prompt_body","value-denied")),S!==void 0&&!X(S)&&t.push(c("executionMode","unsafe_key","value-denied"));const u=E(e.metadata)?e.metadata:void 0,y=X(S)?S:void 0,I=y==="branchless_child_preparation"?"branchless_sandbox":"story_worktree";y&&(u?.governanceSource!=="delegated-subagent"||u.childWorkspace!==I||u.integrationOwner!=="root_agent"||u.maxDepth!==1||typeof u.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(u.graphRevision))&&t.push(c("executionMode","unsafe_key","value-denied"));const b=i?`*yolo @${i}${y?v[y]:""}`:void 0;(!m||m!==b||m.includes("@neocortex")||g.test(m)||_.test(m))&&t.push(c("commandRef","prompt_body","value-denied")),h&&i&&h!==R(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 $=Oe(e.runtime,t);e.attempts!==void 0&&D(e.attempts,"attempts",t),e.metadata!==void 0&&D(e.metadata,"metadata",t);const H=Me(e.redactionSummary,t);return t.length>0||r!=="run_yolo"||!n||!a||!d||!s||!i||!m||!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:m,...h?{storyId:h}:{},...y?{executionMode:y}:{},...$?{runtime:$}:{},publicSummary:f,...typeof e.reasonCode=="string"?{reasonCode:e.reasonCode}:{},...u?{metadata:u}:{},...H.length>0?{redactionSummary:H}:{},publicSafe:!0}}}function Te(e,t){return e?.governanceSource==="delegated-subagent"?"delegated-subagent":t}function Oe(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))(!Ee.has(d)||w.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)||g.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)||g.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 k(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===F.BYPASS_BLOCKED?{governanceEvidence:ae}:{},publicSummary:T(r.publicSummary)},i=V(t.metadata_json,{autonomousKind:"run_yolo",jobId:t.job_id,targetKind:"story",targetRef:t.target_ref}),m=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:T(r.publicSummary),notBeforeAt:r.notBeforeAt,retryCount:r.retryCount,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:m},receipt:{receiptId:`receipt-${j("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:m}}),e.recordHeadlessExecutionSummary({eventId:`event-${j("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:T(r.publicSummary),reasonCode:r.reasonCode,createdAt:r.completedAt,durationMs:r.durationMs,counts:d,hashes:s,redactionSummary:n,relativePaths:a,metadata:m}),{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 we(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 O(K({kind:e.kind,commandClass:e.commandClass,jobId:e.jobId,targetRef:e.targetRef,commandRef:e.commandRef,storyId:e.storyId,executionMode:e.executionMode,...N(e.executionMode)?{operationId:e.operationId,idempotencyKey:e.idempotencyKey}:{},runtime:e.runtime}))}function K(e){return Array.isArray(e)?`[${e.map(K).join(",")}]`:E(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${K(e[t])}`).join(",")}}`:JSON.stringify(e)}function D(e,t,r){if(typeof e=="string"){(_.test(e)||g.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}`;w.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 P.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)||w.test(r)||_.test(r)||typeof n=="string"&&_.test(n)||(t[r]=n);return Object.keys(t).length>0?t:void 0}function R(e){return e.replace(/^docs\/stories\//,"").replace(/\.story\.md$/,"")}function je(e){if(e==="explicit"||e==="origin"||e==="default"||e==="fallback")return e}function Ne(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 U(e){return!!(e&&he.test(e)&&!_.test(e)&&!g.test(e))}function E(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function j(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 j(e,t)}function Pe(e,t){return j(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 C(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{fe as DEFAULT_HEADLESS_EXECUTION_BACKOFF_MS,me as DEFAULT_HEADLESS_EXECUTION_LEASE_MS,ye as DEFAULT_HEADLESS_EXECUTION_LIMIT,_e as DEFAULT_HEADLESS_EXECUTION_MAX_ATTEMPTS,le as DEFAULT_HEADLESS_EXECUTION_STALE_LEASE_AFTER_MS,pe as DEFAULT_HEADLESS_EXECUTION_TIMEOUT_MS,z as RUN_YOLO_STORY_WORKTREE_BINDING_REQUIRED,G as headlessExecutionEntityId,ze as runYoloExecutionPhase};
|
|
@@ -23,13 +23,15 @@ export declare const MAX_HEADLESS_YOLOOP_LOCAL_CONCURRENCY_CAP = 10;
|
|
|
23
23
|
export declare const YOLOOP_CONTINUATION_DELEGATION_PERSIST_FAILED_REASON_CODE: "yoloop-continuation-delegation-persist-failed";
|
|
24
24
|
/**
|
|
25
25
|
* Binds the single pending continuation authority to the physical child wave
|
|
26
|
-
* the runner is about to launch.
|
|
27
|
-
*
|
|
28
|
-
*
|
|
26
|
+
* the runner is about to launch. V4 admits independent spec preparation from
|
|
27
|
+
* the graph alongside the logical continuation selection. Its `delegated` bit
|
|
28
|
+
* describes only the selected stories, once all are in admitted phase-one
|
|
29
|
+
* batches from the current plan.
|
|
29
30
|
*/
|
|
30
31
|
export declare function markYoloopContinuationDelegatedAtDispatch(input: {
|
|
31
32
|
readonly projectRoot: string;
|
|
32
33
|
readonly storyIds: readonly string[];
|
|
34
|
+
readonly phaseOneEpicId?: string;
|
|
33
35
|
readonly nowIso?: string;
|
|
34
36
|
}): Promise<'recorded' | 'unchanged' | 'none'>;
|
|
35
37
|
/**
|
|
@@ -373,6 +375,7 @@ export declare function checkV4DispatchBases(projectRoot: string, executionBranc
|
|
|
373
375
|
type PhaseTwoObservation = {
|
|
374
376
|
readonly kind: 'ready' | 'checkpoint-ready' | 'pending' | 'blocked';
|
|
375
377
|
readonly reasonCode: string;
|
|
378
|
+
readonly qaPolicyRelease?: string;
|
|
376
379
|
};
|
|
377
380
|
/** Keep explicit server waits authoritative and replace only the generic C13
|
|
378
381
|
* pending code with same-story, public QA evidence from the owned worktree. */
|