@ornexus/neocortex 4.66.10 → 4.66.12
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 +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/platform-detector.js +1 -1
- package/packages/client/dist/cli.js +0 -0
- package/packages/client/dist/commands/invoke.d.ts +2 -0
- package/packages/client/dist/commands/invoke.js +80 -78
- package/packages/client/dist/errors/error-messages.js +2 -2
- package/packages/client/dist/errors/transport-failure.d.ts +5 -0
- package/packages/client/dist/errors/transport-failure.js +1 -0
- package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
- package/packages/client/dist/git/published-story-reconciliation.d.ts +15 -0
- package/packages/client/dist/git/published-story-reconciliation.js +4 -2
- package/packages/client/dist/git/worktree-checkout-boundary.d.ts +2 -0
- package/packages/client/dist/git/worktree-checkout-boundary.js +1 -0
- package/packages/client/dist/license/license-client.js +1 -1
- package/packages/client/dist/runner-cli.js +0 -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 +12 -7
- package/targets-stubs/codex/neocortex-sentinel.toml +5 -0
- package/targets-stubs/codex/neocortex.toml +5 -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
|
@@ -1,2 +1,4 @@
|
|
|
1
|
-
import{execFile as
|
|
2
|
-
`)
|
|
1
|
+
import{execFile as ae}from"node:child_process";import{createHash as se}from"node:crypto";import{realpath as M}from"node:fs/promises";import{promisify as ce}from"node:util";import{parseYoloopInvocation as Q}from"../yoloop/target-normalization.js";import{resolveYoloopStartTarget as ue}from"../yoloop/yoloop-start-origin-binding.js";import{recoverLegacyDirectYoloStoryCheckpoint as de,resolveDirectYoloIntegrationAuthority as he,verifyDirectYoloIntegrationCommit as fe}from"./direct-yolo-checkpoint.js";import{resolveRemoteHeadFreshOptional as z}from"./epic-lifecycle-evidence.js";import{appendStoryWorktreeEvidence as pe,isStoryWorktreeEvidenceReceiptRecord as le,mutateGitLifecycleRuntime as ye,publishedStoryReconciliationId as V,readGitLifecycleRuntime as B,readStoryWorktreeEvidence as we}from"./git-lifecycle-store.js";import{readGovernanceStateSourceSync as me}from"./governance-runtime-store.js";import{parseNeocortexTrailers as K,trailerValue as P}from"./neocortex-trailers.js";import{StoryWorktreeManager as U}from"./story-worktree-manager.js";const X=ce(ae),T=/^[a-f0-9]{64}$/,A=/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/,ge=16;function Z(e){return se("sha256").update(e).digest("hex")}function v(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ve(e,o){let n;try{n=v(JSON.parse(e))}catch{return}if(!(n?.schemaVersion!==2||n.storyId!==o||n.publicSafe!==!0||n.status!=="qa-passed"||n.safeToContinueYoloop!==!0||!Array.isArray(n.blockingChecks)||n.blockingChecks.length!==0))return Z(e)}async function Ce(e,o){const n=Q(o);if(!n||!/^@?(?:\.\/)?docs\/epics\/epic-[A-Za-z][A-Za-z0-9_-]{0,63}\.md$/.test(n.remainder))return[];const t=ue(o);return!t||t.source!=="explicit"?[]:ee(e,t.epicId,!0)}async function Re(e,o,n){const t=Q(o)?.remainder,s=t?.match(/^@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md$/)?.[1]??t?.match(/^@?((?:P|EPIC-)[0-9]+)$/i)?.[1]?.toUpperCase();if(!s)return;const h=j(e);let I;try{const m=(await h("symbolic-ref","--quiet","--short","HEAD")).trim(),k=await B(e,{required:!0}),i=k.epics[s];if(i?.branch_mode!=="epic"||i.execution_branch!==m)return;const[g,b,...N]=(await h("show","-s","--format=%H%n%P%n%B","HEAD")).split(`
|
|
2
|
+
`);if(!g||!b||!A.test(g)||!A.test(b))return;const D=K(N.join(`
|
|
3
|
+
`),["Neocortex-Story","Neocortex-Epic","Neocortex-Execution-Branch","Neocortex-Prepared-Base","Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"]);if(!D.ok)return;const a=d=>P(D.values,d),p=a("Neocortex-Story");if(!p||!/^[A-Za-z][A-Za-z0-9_-]*\.[A-Za-z0-9._-]+$/.test(p)||a("Neocortex-Epic")!==s||a("Neocortex-Execution-Branch")!==m||a("Neocortex-Prepared-Base")!==b||!["Neocortex-Bundle-Digest","Neocortex-Graph-Revision","Neocortex-Claim-Revision"].every(d=>T.test(a(d)??""))||k.stories[p]?.checkpoint||n.some(d=>d.storyId===p))return;const $=me(e);if(!$.ok||!$.value||v(v(v(JSON.parse($.value.toString("utf8")))?.stories)?.[p])?.epic_id!==s)return;I={storyId:p,headSha:g,executionBranch:m}}catch{return}const{storyId:u,headSha:f,executionBranch:S}=I;try{if(await z(h,S)!==f)return}catch{return{status:"pending",storyId:u,headSha:f,reasonCode:"direct-yolo-recovery-remote-proof-unavailable"}}const c=await de({projectRoot:e,storyId:u,commitSha:f});if(c.ok)return{status:"recovered",storyId:u,headSha:f};if(c.reasonCode==="direct-yolo-checkpoint-conflict"){const m=await B(e,{required:!0});if(v(m.stories[u]?.checkpoint)?.headSha===f)return}return{status:"pending",storyId:u,headSha:f,reasonCode:c.reasonCode}}function j(e){return async(...o)=>(await X("git",[...o],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:4*1024*1024,env:{...process.env,GIT_OPTIONAL_LOCKS:"0",GIT_TERMINAL_PROMPT:"0"}})).stdout}async function Pe(e,o){const n=/^\s*\*?yolo\s+@(?:\.\/)?docs\/stories\/([A-Za-z][A-Za-z0-9_-]{0,63})\.[A-Za-z0-9.]+\.story\.md\s+story-worktree-phase-[12]\s*$/.exec(o);if(!n)return[];try{const s=(await X("git",["worktree","list","--porcelain","-z"],{cwd:e,encoding:"utf8",timeout:8e3,maxBuffer:1048576})).stdout.split("\0",1)[0];return s?.startsWith("worktree ")?await Se(s.slice(9),n[1]):[]}catch{return[]}}function Se(e,o){return ee(e,o,!1)}async function ee(e,o,n){const t=j(e),s=async u=>(await t("rev-parse","--verify","--quiet",`${u}^{commit}`)).trim(),h=async(u,f)=>{try{return await t("merge-base","--is-ancestor",u,f),!0}catch{return!1}},I=[];try{const u=await M((await t("rev-parse","--absolute-git-dir")).trim()),f=await M((await t("rev-parse","--path-format=absolute","--git-common-dir")).trim());if(u!==f)return[];const S=(await t("symbolic-ref","--quiet","--short","HEAD")).trim(),c=await s("HEAD"),m=await B(e,{required:!0});if(m.epics[o]?.execution_branch!==S)return[];const k=Object.values(m.storyWorktrees?.entries??{}).filter(i=>i.epicId===o&&i.executionBranch===S&&i.state==="active");if(k.length>ge)return[];for(const i of k)try{const g=await B(e,{required:!0});if(g.stories[i.storyId]?.checkpoint||k.filter(r=>r.storyId===i.storyId).length!==1||Date.parse(i.expiresAt)>Date.now())continue;const b=v(g.epics[o]?.branch_lease);if(b&&Date.parse(String(b.expiresAt))>Date.now())continue;const N=we(g,o)?.receipts??[];if(N.some(r=>r.kind==="integration-receipt"&&r.storyId===i.storyId))continue;const D=N.filter(r=>r.kind==="phase-one-receipt"&&r.storyId===i.storyId&&r.leaseId===i.leaseId&&r.graphRevision===i.graphRevision);if(D.length!==1)continue;const a=D[0],p=String(a.graphRevision),$=String(a.receiptId);if(!T.test(p)||!A.test(String(a.headSha))||a.specRef!==`docs/stories/${i.storyId}.spec.md`)continue;const H=N.filter(r=>r.kind==="published-story-reconciliation"&&r.storyId===i.storyId&&r.graphRevision===p);if(H.length>1||!n&&H.length===0)continue;const d=await he(e,i.storyId),x=d.originBinding;if(d.epicId!==o||d.executionBranch!==S||!x||x.originBranch===S||!await h(x.originHeadSha,c))continue;const l=await new U({projectRoot:e}).probe(i.leaseId);if(!l.ok||l.value.ownership!=="proven"||l.value.clean!==!0||!l.value.headSha||!A.test(l.value.headSha)||!await h(String(a.headSha),l.value.headSha))continue;const q=(await t("log","--max-count=2","--fixed-strings","--format=%H",`--grep=Neocortex-Story-Worktree-Tip: ${l.value.headSha}`,`${x.originHeadSha}..${c}`)).trim().split(`
|
|
4
|
+
`).filter(Boolean);if(q.length!==1||!A.test(q[0]))continue;const y=q[0],te=(await t("show","-s","--format=%P",y)).trim();if(!A.test(te))continue;const _=K(await t("show","-s","--format=%B",y),["Neocortex-Story-Worktree-Tip","Neocortex-Graph-Revision","Neocortex-Review-Artifact-Digest"]);if(!_.ok||P(_.values,"Neocortex-Story-Worktree-Tip")!==l.value.headSha)continue;const E=P(_.values,"Neocortex-Graph-Revision"),W=P(_.values,"Neocortex-Review-Artifact-Digest");if(!E||!T.test(E)||!W||!T.test(W))continue;const re=(await t("rev-parse",`${y}^{tree}`)).trim(),ie=(await t("rev-parse",`${l.value.headSha}^{tree}`)).trim();if(re!==ie)continue;const Y=await fe(d,i.storyId,y,{expectedGraphRevision:E});if(!Y.ok)continue;const oe=v(JSON.parse(await t("show",`${y}:.neocortex/state.json`))),F=v(v(oe?.stories)?.[i.storyId]);if(F?.epic_id!==o||JSON.stringify(F.depends_on??[])!==JSON.stringify(d.story.depends_on??[]))continue;const C=String(a.specRef),R=`docs/stories/${i.storyId}.story.md`;if(Z(await t("show",`${y}:${C}`))!==a.specDigest||Z(await t("show",`${c}:${C}`))!==a.specDigest||await t("show",`${y}:${R}`)!==await t("show",`${c}:${R}`))continue;await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R);const L=ve(await t("show",`${y}:.neocortex/stories/${i.storyId}/qa-gate-result.json`),i.storyId);if(!L)continue;const w=await z(t,x.originBranch);if(!w)continue;try{await s(w)}catch{if(!n||(await t("fetch","--quiet","--no-tags","--no-write-fetch-head","--refmap=","origin",w),await s(w)!==w))continue}if(!await h(x.originHeadSha,w)||!await h(y,w))continue;const G={schemaVersion:1,kind:"published-story-reconciliation",epicId:o,storyId:i.storyId,graphRevision:p,historicalGraphRevision:E,phaseOneReceiptId:$,executionBranch:S,executionHeadSha:c,originBranch:x.originBranch,originHeadSha:w,commitSha:y,bundleDigest:Y.value.bundleDigest,historicalQaDigest:L},J=async()=>{if(await s("HEAD")!==c||await s(`refs/heads/${S}`)!==c||await z(t,x.originBranch)!==w)throw new Error("published-story-reconciliation-ref-raced");const r=await new U({projectRoot:e}).probe(i.leaseId);if(!r.ok||r.value.ownership!=="proven"||r.value.clean!==!0||r.value.headSha!==l.value.headSha)throw new Error("published-story-reconciliation-worktree-raced");await t("diff","--quiet","HEAD","--",".neocortex/state.json",C,R)};if(H[0]){const r=H[0],ne={...G,executionHeadSha:r.executionHeadSha,originHeadSha:r.originHeadSha};if(r.receiptId!==V(ne)||!await h(r.executionHeadSha,c)||!await h(r.originHeadSha,w)||(await J(),(await B(e,{required:!0})).revision!==g.revision))continue;I.push(r);continue}const O=Object.freeze({...G,receiptId:V(G)});if(!le(O))continue;await ye(e,r=>{pe(r,o,{receipts:[O]})},{expectedRevision:g.revision,preCommit:J}),I.push(O)}catch{}}catch{}return I}export{ve as historicalStoryQaDigest,Ce as reconcilePublishedStoriesForYoloop,Re as recoverPublishedCheckpointForYoloop,Pe as revalidatePublishedStoriesForYolo,Se as revalidatePublishedStoryDependencies};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isAbsolute as l,relative as c,resolve as s,sep as i}from"node:path";function p(o,n){const e=new Set;for(const r of n.split("\0")){if(!r.startsWith("worktree "))continue;const t=c(s(o),s(r.slice(9)));t&&t!==".."&&!t.startsWith(`..${i}`)&&!l(t)&&e.add(`${t.split(i).join("/")}/`)}return e}export{p as registeredNestedWorktreeDirectories};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{decodeJwt as
|
|
1
|
+
import{decodeJwt as f}from"jose";import{setTimeout as d}from"node:timers/promises";import{classifyTransportFailure as k,mayRetryBeforeDispatch as y}from"../errors/transport-failure.js";import{NoOpCache as R}from"../types/index.js";import{getMachineFingerprint as p}from"../machine/fingerprint.js";import{CLIENT_VERSION as _}from"../version.js";import{classifyAuthCausalEvidence as l}from"./host-auth-recovery.js";const v="neocortex:jwt:token",E="neocortex:jwt:refresh_token",T=300,m=10080*60*1e3,c=v,h=E,u=m,w=12e3,C=150;class A{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;causalAuthRecovery;token=null;refreshToken=null;lastRecoveryResult=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new R,this.clientVersion=e.clientVersion??_,this.strictReadOnly=e.strictReadOnly??!1,this.causalAuthRecovery=e.causalAuthRecovery??!1,this.machineId=p({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const t=await this.inspectToken();return t.status==="authenticated"?t.token:null}if(this.token){const t=this.checkTokenValidity(this.token);if(t==="valid")return this.token;if(t==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const t=this.checkTokenValidity(e);if(t==="valid")return e;if(t==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const t=await this.refresh();if(t?.token)return t.token;if(this.causalAuthRecovery)return null}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const t=this.checkTokenValidity(e);return t==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:t==="needs-refresh"?"near-expiry":"expired"}}const s=this.refreshToken??await this.loadRefreshTokenFromCache();return s?(this.refreshToken=s,{status:"refresh-required",reason:"expired"}):this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}getLastRecoveryResult(){return this.lastRecoveryResult}refreshRequired(e,s){return this.lastRecoveryResult={status:"refresh-required",cause:e,action:s},null}rememberRecovery(e){return this.lastRecoveryResult=e,null}async activate(){if(this.strictReadOnly)return null;try{const e=this.licenseKey.startsWith("nxk_"),s=e?"activate-key":"activate",t=e?{api_key:this.licenseKey}:{license_key:this.licenseKey},a=await fetch(`${this.serverUrl}/api/v1/license/${s}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,machine_id:this.machineId,client_version:this.clientVersion})});if(!a.ok){let o="";try{o=String((await a.json()).error??"")}catch{}return this.rememberRecovery(l({kind:"http",status:a.status,...o?{errorCode:o}:{}}))}const i=await a.json();return i.tier!==void 0&&i.tier!=="free"&&i.tier!=="pro"&&i.tier!=="enterprise"?null:(this.token=i.token,this.refreshToken=i.refresh_token??null,await this.cache.set(c,i.token,i.expires_in*1e3).catch(()=>{}),i.refresh_token&&await this.cache.set(h,i.refresh_token,u).catch(()=>{}),{token:i.token,expiresIn:i.expires_in,refreshToken:i.refresh_token,tier:i.tier})}catch{return this.rememberRecovery(l({kind:"transport"}))}}async refresh(e){if(this.strictReadOnly)return null;const s=AbortSignal.timeout(w);try{const t=this.refreshToken??await this.loadRefreshTokenFromCache();if(!t)return this.refreshRequired("store-unavailable","retry-later");const a={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:t}),signal:s},i=`${this.serverUrl}/api/v1/license/refresh`,o=await fetch(i,a).catch(async n=>{if(s.aborted||!y(n))throw n;return await d(C,void 0,{signal:s}),fetch(i,a)});if(!o.ok){let n="";try{n=String((await o.json()).error??"")}catch{}return o.status===429?this.refreshRequired("rate-limited","retry-later"):o.status>=500?this.refreshRequired("service-unavailable","retry-later"):n==="invalid_grant"||n==="revoked"?this.refreshRequired("revoked","reactivate"):n==="invalid_scope"||n==="scope_denied"?this.refreshRequired("scope-denied","request-scope"):n==="client_denied"?this.refreshRequired("client-denied","stop"):this.refreshRequired("protocol-invalid","stop")}const r=await o.json().catch(n=>{if(!(n instanceof SyntaxError))throw n;return null});return!r||typeof r.token!="string"||!r.token||!Number.isFinite(r.expires_in)||r.expires_in<=0||r.refresh_token!==void 0&&typeof r.refresh_token!="string"?this.refreshRequired("protocol-invalid","stop"):(this.token=r.token,this.refreshToken=r.refresh_token??null,await this.cache.set(c,r.token,r.expires_in*1e3).catch(()=>{}),r.refresh_token&&await this.cache.set(h,r.refresh_token,u).catch(()=>{}),this.lastRecoveryResult={status:"authenticated",generation:0,accessCredential:r.token,expiresAt:new Date(Date.now()+r.expires_in*1e3).toISOString()},{token:r.token,expiresIn:r.expires_in,refreshToken:r.refresh_token})}catch(t){const a=k(t,s.aborted);return this.refreshRequired(a==="timeout"?"timeout":"transport-error","retry-later")}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:this.causalAuthRecovery?null:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const s=f(e);if(!s.exp)return"expired";const t=Math.floor(Date.now()/1e3);return s.exp<=t?"expired":s.exp-t<=T?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(c)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(h);return e&&e.length>0?e:null}catch{return null}}}export{v as LICENSE_ACCESS_TOKEN_CACHE_KEY,E as LICENSE_REFRESH_TOKEN_CACHE_KEY,m as LICENSE_REFRESH_TOKEN_TTL_MS,A as LicenseClient};
|
|
File without changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{promises as y}from"node:fs";import{existsSync as E}from"node:fs";import{createHash as A}from"node:crypto";import{join as R,dirname as he}from"node:path";import{hostname as C}from"node:os";import{setSecureFilePermissions as pe,setSecureDirPermissions as ye}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as j}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as q,epicOperationalCanonicalJson as m,epicOperationalHash as v,mutateEpicOperationalState as B,readEpicOperationalState as P}from"../git/epic-operational-state.js";import{yoloopDomainHash as Oe}from"../../../shared/dist/yoloop/canonical.js";const _e=".neocortex",z="yoloop-state.json",Ie="yoloop.lock",fe="yoloop-state.mutation.lock",J="yoloop-session-rollover.json",G="yoloop-successor-transition.json",W=360*60*1e3,we=3e4,Se=200,X=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),Re={warn:()=>{},info:()=>{},error:()=>{}};function x(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function nt(t){return{lock:null,state:x(t),capabilities:X}}class st{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Re){this.projectRoot=e,this.stateDir=R(e,_e),this.statePath=R(this.stateDir,z),this.lockPath=R(this.stateDir,Ie),this.mutationLockPath=R(this.stateDir,fe),this.rolloverManifestPath=R(this.stateDir,J),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s)return{lock:s.yoloop.lock,state:s.yoloop.state,capabilities:s.yoloop.capabilities};await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[o,r]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(o,n),state:r,capabilities:X}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const o of e.operations)await this.applyCommonOperation(o,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!le(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const o=r=>{const a=(r.pendingContinuationAuthorities??[]).find(l=>l.idempotencyKey===e.idempotencyKey);if(!a)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c={sessionId:String(a.sessionId??""),idempotencyKey:e.idempotencyKey,storyIds:Array.isArray(a.storyIds)?a.storyIds.map(String):[]};if(!le(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.continuationReceipts??[],d=i.find(l=>qe(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(m(d)===m(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...r,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:r,operational:a}=P(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return o(a.yoloop.state)==="unchanged"?"unchanged":(await B(this.projectRoot,{identityHash:c[0],expectedRevision:r.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=o(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const r=o(await this.readState(s));return r==="unchanged"?"unchanged":(await this.writeState(r),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(o)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,l=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(l){if(l.operationId===i&&l.idempotencyKey===d)return l;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=xe(a.status,e);if(!u)throw new Error(U.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ke({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await q(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=P(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!E(R(this.projectRoot,".git")))return null;throw e}}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await q(this.projectRoot,e);return}const{document:s,operational:o}=P(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const a=r[0];await B(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d&&d.sessionId!==e.lock.sessionId)throw new Error("YOLOOP_LOCK_HELD");d={...e.lock,pid:process.pid,hostname:C(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??W,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;l={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;l={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=u.find(I=>I.idempotencyKey===p);if(O){if(m(O)!==m(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const O=i.continuationReceipts??[];if(O.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||v("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");l={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");l={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":l={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":l=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(v("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||v("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(O=>O.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":l={...i,recovery_history:F([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),l={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}c.yoloop={...c.yoloop,lock:d,state:l}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=o.find(c=>c.idempotencyKey===r);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],a=r.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=r[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((l,u)=>u!==a),d=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),a=r.pendingContinuationAuthorities??[],c=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||_("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const l=_("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==l)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||_("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:E(this.lockPath),rolloverManifestPresent:E(this.rolloverManifestPath),successorTransitionManifestPresent:E(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(A("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(E(this.lockPath)||E(this.rolloverManifestPath)||E(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:A("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await y.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(o){throw await y.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...a}=e;if(Ee(a)!==e.payloadHash||!Z(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const c={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:_("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===_("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(h(e.receipt)!==h(c))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const l=i.continuationReplanReceipts??[],u=l.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(h(u)===h(c)&&h(i.continuationSession)===h(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,O=i.pendingContinuationAuthorities??[];if(!Z(p)||_("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||_("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...l.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=F([...o,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],a=r.findIndex(l=>l.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=r[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[a]={...c,outcome:n,finished_at:s};const d={...o,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:C(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??W,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await y.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const a=r;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),r;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Ue(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),x(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await y.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw o}}async rolloverSession(e,n){H(e);const s=await this.readRolloverManifest();if(s){if(ve(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();te(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=h(s)===h(e.next);if(!o){const a=await this.readLock();te(e,s,a),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return H(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){k(e);const s=await this.readSuccessorTransitionManifest();if(s){if(Le(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(n);if(Y(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}Q(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!Y(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=Ae(e,s);await this.writeState(r),s=await this.readState(n)}if(!Y(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await y.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await y.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return k(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Se;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await y.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>we){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){D(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");K(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){ee(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(o?.predecessor)===h(r))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return D(i),K(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{pe(e)}catch{}}trySetDirPerms(e){try{ye(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=re(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==C())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(re(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==C())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await y.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===C()}async cleanupOrphanTempFiles(){try{const e=he(this.statePath),n=await y.readdir(e),s=[`${z}.tmp.`,`${J}.tmp.`,`${G}.tmp.`],o=n.filter(r=>s.some(a=>r.startsWith(a)));for(const r of o)try{await y.unlink(R(e,r))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function _(t,e){return A("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ee(t){return _("p222-yoloop-continuation-replan-v1",t)}function Z(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===_("p205-yoloop-session-v1",n)}function Ce(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Ne(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function Te(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function me(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function Le(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function k(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;ee(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==me(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||o!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||s!==void 0&&r===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function Q(t,e){if(k(t),!(h(e.runControl)===h(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ge(t,e)}function ge(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],o=t.acknowledgement;if(o){const d=n.find(p=>p.idempotencyKey===o.idempotencyKey);if(!d||o.receipt.sessionId!==d.sessionId||h(o.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(l)||h(t.state.continuationReceipts??[])!==h(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const a=String(r.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Ae(t,e){Q(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function Y(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n);const o={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(o)}function ve(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Ne(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function ee(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==Te(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function te(t,e,n){H(t);const s=e.currentSession;if(!s||Ce(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(h(r)!==h(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=r.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:c.payloadHash,next:r};D(i),K(o,i)}else{const c=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function ne(t){const{receipts:e,...n}=t.next;return _("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const U=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Pe={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function xe(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:U.has(t)||t==="cancelling"?null:"cancelling"}function ke(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=_("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),a={...o,snapshotId:r,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},c={...o,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=_("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},l={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=_("p220-yoloop-run-event-id-v1",{runId:l.runId,operationId:l.operationId,sequence:l.sequence}),p={...l,eventId:u,eventHash:_("p220-yoloop-run-event-v1",{...l,eventId:u})},O={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,a,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},T=ne(I),g={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:T,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:T,next:{...O,receipts:[...O.receipts,g]}}}function D(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==ne(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function K(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,o.length))!==h(o)||h(n.receipts.slice(0,r.length))!==h(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(U.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const l=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(l==="budget"||l==="retry");if(!(Pe[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(h(t.predecessor)!==h(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=n.progressSnapshots.at(-2),c=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!a||!c||!i||!d||a.phase!=="before"||c.phase!=="after"||a.operationId!==e.operationId||c.operationId!==e.operationId||i.operationId!==e.operationId||a.runId!==e.runId||c.runId!==e.runId||i.runId!==e.runId||a.revision!==n.revision||c.revision!==n.revision||i.revision!==n.revision||a.parentSnapshotHash!==(t?.latestSnapshotHash??null)||c.parentSnapshotHash!==a.snapshotHash||n.latestSnapshotHash!==c.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");se(a),se(c),Ye(i,s.at(-1)?.eventHash??null)}function se(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ye(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==_("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function oe(t,e){return`lease-${He(`${t}:${e}`)}`}function He(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function re(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function Ue(t,e){const n=x(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?F(t.recovery_history):[]}}function F(t){return t.length<=j?t:t.slice(t.length-j)}const b=Object.freeze(["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"]),De=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function Ke(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(De.has(n))return 0;const s=b.indexOf(e);return s<0?b.length:b.length-1-s}const M="yoloop-round-refused-before-setup",Fe="neocortex.p230.round-refused-before-setup.v1",ie=64,be=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),Me="reasonCode,storyId",ae=/^[a-z0-9][a-z0-9-]{2,79}$/,Ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,$e=/^[a-f0-9]{64}$/;function L(t){return typeof t=="string"&&Ve.test(t)&&!t.includes("..")}function N(t){return typeof t=="string"&&$e.test(t)}function ce(t){if(!(!Array.isArray(t)||t.length===0||t.length>ie)&&t.every(L)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function de(t){return Oe(Fe,{schemaVersion:t.schemaVersion,kind:t.kind,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:t.storyIds,refusals:t.refusals.map(e=>({storyId:e.storyId,reasonCode:e.reasonCode}))})}function je(t){if(!t||!L(t.epicId)||!N(t.sessionId)||!N(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ie)return;const e=t.refusals.map(o=>({storyId:o?.storyId,reasonCode:o?.reasonCode})).sort((o,r)=>String(o.storyId).localeCompare(String(r.storyId)));if(!e.every(o=>L(o.storyId)&&typeof o.reasonCode=="string"&&ae.test(o.reasonCode)))return;const n=e.map(o=>o.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:M,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(o=>Object.freeze({storyId:o.storyId,reasonCode:o.reasonCode})))};return Object.freeze({...s,digest:de(s)})}function qe(t){return S(t)&&t.kind===M}function le(t,e){if(!S(t)||Object.keys(t).some(p=>!be.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:o,sessionId:r,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==M||!L(o)||!N(r)||!N(a)||!N(d))return!1;const l=ce(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===Me&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&ae.test(p.reasonCode))||d!==de(t))return!1;if(!e)return!0;const u=ce([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&r===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Be="story-round-no-setup-evidence";function ot(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,o=S(s?.expectedTransition)?s.expectedTransition:void 0,r=Array.isArray(o?.storyLifecycle)?o.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!r||r.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const l=new Set(i.map(f=>{const w=S(t.stories[f])?t.stories[f]:void 0;return typeof w?.epic_id=="string"?w.epic_id:f.split(".")[0]}));if(l.size!==1)return;const u=[...l][0],p=S(t.epics[u])?t.epics[u]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],I=S(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,T=Array.isArray(I?.receipts)?I.receipts:[],g=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],ue=f=>O.some(w=>S(w)&&w.storyId===f)||T.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||g.some(w=>S(w)&&w.storyId===f);for(const f of i){if(ue(f))return;const w=r.find($=>S($)&&$.storyId===f),V=S(t.stories[f])?t.stories[f]:void 0;if(!w||!V||!Number.isSafeInteger(w.remaining)||Ke(V.status)!==w.remaining)return}return je({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Be}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{X as YOLOOP_PERSISTENCE_CAPABILITIES,Be as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,M as YOLOOP_ROUND_REFUSED_KIND,st as YoloopClientStateStore,je as buildClientYoloopRoundRefusedReceipt,Ee as buildYoloopContinuationReplanPayloadHash,ne as buildYoloopRunTransitionPayloadHash,Ne as buildYoloopSessionRolloverPayloadHash,Te as buildYoloopSuccessorRunPayloadHash,me as buildYoloopSuccessorTransitionPayloadHash,F as capRecoveryHistory,Ke as clientYoloopStoryLifecycleRemaining,x as createDefaultCounters,nt as createDefaultState,ot as deriveYoloopRoundRefusedBeforeSetupReceipt,Ce as fingerprintYoloopSession,qe as isClientYoloopRoundRefusedRecord,le as isValidClientYoloopRoundRefusedReceipt};
|
|
1
|
+
import{promises as y}from"node:fs";import{existsSync as E}from"node:fs";import{createHash as A}from"node:crypto";import{join as R,dirname as he}from"node:path";import{hostname as C}from"node:os";import{setSecureFilePermissions as pe,setSecureDirPermissions as ye}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as j}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as q,epicOperationalCanonicalJson as m,epicOperationalHash as v,mutateEpicOperationalState as B,readEpicOperationalState as P}from"../git/epic-operational-state.js";import{yoloopDomainHash as Oe}from"../../../shared/dist/yoloop/canonical.js";const _e=".neocortex",z="yoloop-state.json",Ie="yoloop.lock",fe="yoloop-state.mutation.lock",J="yoloop-session-rollover.json",G="yoloop-successor-transition.json",W=360*60*1e3,we=3e4,Se=200,X=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),Re={warn:()=>{},info:()=>{},error:()=>{}};function x(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function nt(t){return{lock:null,state:x(t),capabilities:X}}class st{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Re){this.projectRoot=e,this.stateDir=R(e,_e),this.statePath=R(this.stateDir,z),this.lockPath=R(this.stateDir,Ie),this.mutationLockPath=R(this.stateDir,fe),this.rolloverManifestPath=R(this.stateDir,J),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s)return{lock:s.yoloop.lock,state:s.yoloop.state,capabilities:s.yoloop.capabilities};await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[o,r]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(o,n),state:r,capabilities:X}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const o of e.operations)await this.applyCommonOperation(o,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!le(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const o=r=>{const a=(r.pendingContinuationAuthorities??[]).find(l=>l.idempotencyKey===e.idempotencyKey);if(!a)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c={sessionId:String(a.sessionId??""),idempotencyKey:e.idempotencyKey,storyIds:Array.isArray(a.storyIds)?a.storyIds.map(String):[]};if(!le(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.continuationReceipts??[],d=i.find(l=>qe(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(m(d)===m(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...r,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:r,operational:a}=P(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return o(a.yoloop.state)==="unchanged"?"unchanged":(await B(this.projectRoot,{identityHash:c[0],expectedRevision:r.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=o(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const r=o(await this.readState(s));return r==="unchanged"?"unchanged":(await this.writeState(r),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(o)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,l=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(l){if(l.operationId===i&&l.idempotencyKey===d)return l;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=xe(a.status,e);if(!u)throw new Error(U.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ke({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await q(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=P(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!E(R(this.projectRoot,".git")))return null;throw e}}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await q(this.projectRoot,e);return}const{document:s,operational:o}=P(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const a=r[0];await B(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d&&d.sessionId!==e.lock.sessionId)throw new Error("YOLOOP_LOCK_HELD");d={...e.lock,pid:process.pid,hostname:C(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??W,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;l={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;l={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=u.find(I=>I.idempotencyKey===p);if(O){if(m(O)!==m(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const O=i.continuationReceipts??[];if(O.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||v("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");l={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");l={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":l={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":l=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(v("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||v("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(O=>O.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":l={...i,recovery_history:F([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),l={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}c.yoloop={...c.yoloop,lock:d,state:l}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=o.find(c=>c.idempotencyKey===r);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],a=r.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=r[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((l,u)=>u!==a),d=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),a=r.pendingContinuationAuthorities??[],c=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||_("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const l=_("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==l)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||_("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:E(this.lockPath),rolloverManifestPresent:E(this.rolloverManifestPath),successorTransitionManifestPresent:E(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(A("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(E(this.lockPath)||E(this.rolloverManifestPath)||E(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:A("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await y.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(o){throw await y.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...a}=e;if(Ee(a)!==e.payloadHash||!Z(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const c={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:_("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===_("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(h(e.receipt)!==h(c))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const l=i.continuationReplanReceipts??[],u=l.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(h(u)===h(c)&&h(i.continuationSession)===h(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,O=i.pendingContinuationAuthorities??[];if(!Z(p)||_("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||_("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...l.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=F([...o,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],a=r.findIndex(l=>l.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=r[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[a]={...c,outcome:n,finished_at:s};const d={...o,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:C(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??W,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await y.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const a=r;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),r;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT")}if(e.expectedSessionId&&e.expectedSessionId!==s?.sessionId||e.expectedLeaseId&&e.expectedLeaseId!==s?.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Ue(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),x(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await y.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw o}}async rolloverSession(e,n){H(e);const s=await this.readRolloverManifest();if(s){if(ve(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();te(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=h(s)===h(e.next);if(!o){const a=await this.readLock();te(e,s,a),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return H(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){k(e);const s=await this.readSuccessorTransitionManifest();if(s){if(Le(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(n);if(Y(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}Q(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!Y(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=Ae(e,s);await this.writeState(r),s=await this.readState(n)}if(!Y(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await y.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await y.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return k(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Se;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await y.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>we){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){D(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");K(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){ee(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(o?.predecessor)===h(r))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return D(i),K(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{pe(e)}catch{}}trySetDirPerms(e){try{ye(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=re(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==C())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(re(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==C())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await y.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===C()}async cleanupOrphanTempFiles(){try{const e=he(this.statePath),n=await y.readdir(e),s=[`${z}.tmp.`,`${J}.tmp.`,`${G}.tmp.`],o=n.filter(r=>s.some(a=>r.startsWith(a)));for(const r of o)try{await y.unlink(R(e,r))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function _(t,e){return A("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ee(t){return _("p222-yoloop-continuation-replan-v1",t)}function Z(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===_("p205-yoloop-session-v1",n)}function Ce(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Ne(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function Te(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function me(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function Le(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function k(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;ee(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==me(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||o!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||s!==void 0&&r===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function Q(t,e){if(k(t),!(h(e.runControl)===h(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ge(t,e)}function ge(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],o=t.acknowledgement;if(o){const d=n.find(p=>p.idempotencyKey===o.idempotencyKey);if(!d||o.receipt.sessionId!==d.sessionId||h(o.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(l)||h(t.state.continuationReceipts??[])!==h(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const a=String(r.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Ae(t,e){Q(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function Y(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n);const o={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(o)}function ve(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Ne(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function ee(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==Te(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function te(t,e,n){H(t);const s=e.currentSession;if(!s||Ce(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(h(r)!==h(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=r.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:c.payloadHash,next:r};D(i),K(o,i)}else{const c=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function ne(t){const{receipts:e,...n}=t.next;return _("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const U=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Pe={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function xe(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:U.has(t)||t==="cancelling"?null:"cancelling"}function ke(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=_("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),a={...o,snapshotId:r,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},c={...o,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=_("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},l={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=_("p220-yoloop-run-event-id-v1",{runId:l.runId,operationId:l.operationId,sequence:l.sequence}),p={...l,eventId:u,eventHash:_("p220-yoloop-run-event-v1",{...l,eventId:u})},O={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,a,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},T=ne(I),g={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:T,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:T,next:{...O,receipts:[...O.receipts,g]}}}function D(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==ne(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function K(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,o.length))!==h(o)||h(n.receipts.slice(0,r.length))!==h(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(U.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const l=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(l==="budget"||l==="retry");if(!(Pe[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(h(t.predecessor)!==h(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=n.progressSnapshots.at(-2),c=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!a||!c||!i||!d||a.phase!=="before"||c.phase!=="after"||a.operationId!==e.operationId||c.operationId!==e.operationId||i.operationId!==e.operationId||a.runId!==e.runId||c.runId!==e.runId||i.runId!==e.runId||a.revision!==n.revision||c.revision!==n.revision||i.revision!==n.revision||a.parentSnapshotHash!==(t?.latestSnapshotHash??null)||c.parentSnapshotHash!==a.snapshotHash||n.latestSnapshotHash!==c.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");se(a),se(c),Ye(i,s.at(-1)?.eventHash??null)}function se(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ye(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==_("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function oe(t,e){return`lease-${He(`${t}:${e}`)}`}function He(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function re(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function Ue(t,e){const n=x(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?F(t.recovery_history):[]}}function F(t){return t.length<=j?t:t.slice(t.length-j)}const b=Object.freeze(["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"]),De=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function Ke(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(De.has(n))return 0;const s=b.indexOf(e);return s<0?b.length:b.length-1-s}const M="yoloop-round-refused-before-setup",Fe="neocortex.p230.round-refused-before-setup.v1",ie=64,be=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),Me="reasonCode,storyId",ae=/^[a-z0-9][a-z0-9-]{2,79}$/,Ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,$e=/^[a-f0-9]{64}$/;function L(t){return typeof t=="string"&&Ve.test(t)&&!t.includes("..")}function N(t){return typeof t=="string"&&$e.test(t)}function ce(t){if(!(!Array.isArray(t)||t.length===0||t.length>ie)&&t.every(L)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function de(t){return Oe(Fe,{schemaVersion:t.schemaVersion,kind:t.kind,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:t.storyIds,refusals:t.refusals.map(e=>({storyId:e.storyId,reasonCode:e.reasonCode}))})}function je(t){if(!t||!L(t.epicId)||!N(t.sessionId)||!N(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ie)return;const e=t.refusals.map(o=>({storyId:o?.storyId,reasonCode:o?.reasonCode})).sort((o,r)=>String(o.storyId).localeCompare(String(r.storyId)));if(!e.every(o=>L(o.storyId)&&typeof o.reasonCode=="string"&&ae.test(o.reasonCode)))return;const n=e.map(o=>o.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:M,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(o=>Object.freeze({storyId:o.storyId,reasonCode:o.reasonCode})))};return Object.freeze({...s,digest:de(s)})}function qe(t){return S(t)&&t.kind===M}function le(t,e){if(!S(t)||Object.keys(t).some(p=>!be.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:o,sessionId:r,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==M||!L(o)||!N(r)||!N(a)||!N(d))return!1;const l=ce(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===Me&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&ae.test(p.reasonCode))||d!==de(t))return!1;if(!e)return!0;const u=ce([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&r===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Be="story-round-no-setup-evidence";function ot(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,o=S(s?.expectedTransition)?s.expectedTransition:void 0,r=Array.isArray(o?.storyLifecycle)?o.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!r||r.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const l=new Set(i.map(f=>{const w=S(t.stories[f])?t.stories[f]:void 0;return typeof w?.epic_id=="string"?w.epic_id:f.split(".")[0]}));if(l.size!==1)return;const u=[...l][0],p=S(t.epics[u])?t.epics[u]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],I=S(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,T=Array.isArray(I?.receipts)?I.receipts:[],g=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],ue=f=>O.some(w=>S(w)&&w.storyId===f)||T.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||g.some(w=>S(w)&&w.storyId===f);for(const f of i){if(ue(f))return;const w=r.find($=>S($)&&$.storyId===f),V=S(t.stories[f])?t.stories[f]:void 0;if(!w||!V||!Number.isSafeInteger(w.remaining)||Ke(V.status)!==w.remaining)return}return je({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Be}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{X as YOLOOP_PERSISTENCE_CAPABILITIES,Be as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,M as YOLOOP_ROUND_REFUSED_KIND,st as YoloopClientStateStore,je as buildClientYoloopRoundRefusedReceipt,Ee as buildYoloopContinuationReplanPayloadHash,ne as buildYoloopRunTransitionPayloadHash,Ne as buildYoloopSessionRolloverPayloadHash,Te as buildYoloopSuccessorRunPayloadHash,me as buildYoloopSuccessorTransitionPayloadHash,F as capRecoveryHistory,Ke as clientYoloopStoryLifecycleRemaining,x as createDefaultCounters,nt as createDefaultState,ot as deriveYoloopRoundRefusedBeforeSetupReceipt,Ce as fingerprintYoloopSession,qe as isClientYoloopRoundRefusedRecord,le as isValidClientYoloopRoundRefusedReceipt};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
|
|
4
4
|
status: native-needs-validation
|
|
5
5
|
source: https://antigravity.google/docs/subagents
|
|
6
6
|
tools:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex Root Agent v4.66.
|
|
3
|
+
description: "🧠 Neocortex Root Agent v4.66.12 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
tools:
|
|
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
113
113
|
┌────────────────────────────────────────────────────────────┐
|
|
114
114
|
│ │
|
|
115
115
|
│ ####### N E O C O R T E X │
|
|
116
|
-
│ ### ######## v4.66.
|
|
116
|
+
│ ### ######## v4.66.12 │
|
|
117
117
|
│ ######### ##### │
|
|
118
118
|
│ ## ############## Development Orchestrator │
|
|
119
119
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -102,7 +102,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
102
102
|
┌────────────────────────────────────────────────────────────┐
|
|
103
103
|
│ │
|
|
104
104
|
│ ####### N E O C O R T E X │
|
|
105
|
-
│ ### ######## v4.66.
|
|
105
|
+
│ ### ######## v4.66.12 │
|
|
106
106
|
│ ######### ##### │
|
|
107
107
|
│ ## ############## Development Orchestrator │
|
|
108
108
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team"
|
|
4
4
|
model: opus
|
|
5
5
|
color: blue
|
|
6
6
|
permissionMode: bypassPermissions
|
|
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
113
113
|
┌────────────────────────────────────────────────────────────┐
|
|
114
114
|
│ │
|
|
115
115
|
│ ####### N E O C O R T E X │
|
|
116
|
-
│ ### ######## v4.66.
|
|
116
|
+
│ ### ######## v4.66.12 │
|
|
117
117
|
│ ######### ##### │
|
|
118
118
|
│ ## ############## Development Orchestrator │
|
|
119
119
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -23,19 +23,24 @@ Tokens starting with `*` (e.g. `*commit-push`, `*implement`, `*status`, `*diagno
|
|
|
23
23
|
`*yolo`, `*review`, `*create-epic`, `*help`) are **Neocortex server triggers**, NOT
|
|
24
24
|
Codex built-in commands or actions.
|
|
25
25
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
- NEVER invoke any local tool, command, or plugin based on these arguments
|
|
29
|
-
- NEVER attempt to resolve or execute these tokens as anything other than neocortex-client args
|
|
30
|
-
- ALWAYS delegate the selected explicit user-intended payload to `neocortex-client invoke --args "..."`
|
|
31
|
-
- The ONLY action this agent takes is: collect args -> invoke thin client -> follow server instructions
|
|
26
|
+
Forward these tokens only to `neocortex-client invoke --args` and follow the
|
|
27
|
+
returned instructions.
|
|
32
28
|
|
|
33
29
|
<!-- END: Plugin Conflict Prevention -->
|
|
34
30
|
|
|
35
|
-
# Neocortex v4.66.
|
|
31
|
+
# Neocortex v4.66.12 | OrNexus Team
|
|
36
32
|
|
|
37
33
|
You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
|
|
38
34
|
|
|
35
|
+
## Thin-client executable
|
|
36
|
+
|
|
37
|
+
If `neocortex-client` is absent from PATH, use the installed absolute executable
|
|
38
|
+
in the same Git root, with identical arguments. Check `$HOME/.local/bin` or
|
|
39
|
+
`%APPDATA%\npm`, then the absolute `npm prefix --global` (`bin/` on Unix,
|
|
40
|
+
`neocortex-client.cmd` via PowerShell `&` on Windows). Retry once only if the
|
|
41
|
+
client did not start. Use this path for subsequent calls. If no global install
|
|
42
|
+
is found, report `neocortex-client-not-found`. Avoid workspace binaries and npx.
|
|
43
|
+
|
|
39
44
|
## Auto-Update Check
|
|
40
45
|
|
|
41
46
|
Before first invoke per session, run `neocortex-client reconcile-registry
|
|
@@ -44,6 +44,11 @@ neocortex-client invoke \
|
|
|
44
44
|
Then follow stdout exactly. If the thin client exits with a non-zero status,
|
|
45
45
|
report stderr and stop for user input.
|
|
46
46
|
|
|
47
|
+
Resolve the installed client from the story worktree using the Thin-client
|
|
48
|
+
executable section in AGENTS.md. If a shell cannot find the command, use the
|
|
49
|
+
absolute global executable there and preserve each argument. This fallback
|
|
50
|
+
applies only before the client has started.
|
|
51
|
+
|
|
47
52
|
Approval and sandbox scope is inherited from the parent Codex turn. A managed
|
|
48
53
|
request for max must be applied when launching or configuring the parent session
|
|
49
54
|
(for example, parent --yolo), not represented as child-only isolation. Host or
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Codex custom agent reference:
|
|
2
2
|
# https://developers.openai.com/codex/subagents
|
|
3
3
|
name = "neocortex"
|
|
4
|
-
description = "🧠 Neocortex v4.66.
|
|
4
|
+
description = "🧠 Neocortex v4.66.12 | OrNexus Team — Development orchestrator for direct @neocortex requests."
|
|
5
5
|
# [P201-EV-CODEX-GEMINI] Approval and sandbox keys are intentionally omitted.
|
|
6
6
|
# Codex reapplies the parent turn's live sandbox/approval settings, including
|
|
7
7
|
# --yolo, when spawning this profile. This profile must not claim child-only max.
|
|
@@ -41,6 +41,10 @@ per-story command such as `*yolo @docs/stories/<id>.story.md`.
|
|
|
41
41
|
Exact admission and bounded canonical recovery remain server-owned. This profile
|
|
42
42
|
must not remove prose, select a target, or repair an outer command.
|
|
43
43
|
|
|
44
|
+
Resolve the installed client from the target Git worktree using the
|
|
45
|
+
Thin-client executable section in AGENTS.md. If a shell cannot find the
|
|
46
|
+
command, use the absolute global executable there and preserve each argument.
|
|
47
|
+
|
|
44
48
|
neocortex-client invoke \
|
|
45
49
|
--args "{DELEGATED_PROMPT}" \
|
|
46
50
|
--format plain
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team"
|
|
4
4
|
model: inherit
|
|
5
5
|
readonly: false
|
|
6
6
|
is_background: false
|
|
@@ -115,7 +115,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
115
115
|
┌────────────────────────────────────────────────────────────┐
|
|
116
116
|
│ │
|
|
117
117
|
│ ####### N E O C O R T E X │
|
|
118
|
-
│ ### ######## v4.66.
|
|
118
|
+
│ ### ######## v4.66.12 │
|
|
119
119
|
│ ######### ##### │
|
|
120
120
|
│ ## ############## Development Orchestrator │
|
|
121
121
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
|
|
4
4
|
user-invocable: true
|
|
5
5
|
disable-model-invocation: false
|
|
6
6
|
---
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex-root
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team"
|
|
4
4
|
kind: local
|
|
5
5
|
tools:
|
|
6
6
|
# File operations (Gemini CLI built-ins)
|
|
@@ -73,7 +73,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
73
73
|
┌────────────────────────────────────────────────────────────┐
|
|
74
74
|
│ │
|
|
75
75
|
│ ####### N E O C O R T E X │
|
|
76
|
-
│ ### ######## v4.66.
|
|
76
|
+
│ ### ######## v4.66.12 │
|
|
77
77
|
│ ######### ##### │
|
|
78
78
|
│ ## ############## Development Orchestrator │
|
|
79
79
|
│ ## ### ###### ## OrNexus Team │
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: neocortex
|
|
3
|
-
description: "🧠 Neocortex v4.66.
|
|
3
|
+
description: "🧠 Neocortex v4.66.12 | OrNexus Team"
|
|
4
4
|
kind: local
|
|
5
5
|
tools:
|
|
6
6
|
# File operations (Gemini CLI built-ins)
|
|
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
|
|
|
72
72
|
┌────────────────────────────────────────────────────────────┐
|
|
73
73
|
│ │
|
|
74
74
|
│ ####### N E O C O R T E X │
|
|
75
|
-
│ ### ######## v4.66.
|
|
75
|
+
│ ### ######## v4.66.12 │
|
|
76
76
|
│ ######### ##### │
|
|
77
77
|
│ ## ############## Development Orchestrator │
|
|
78
78
|
│ ## ### ###### ## OrNexus Team │
|