@ornexus/neocortex 4.66.13 → 4.66.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +3 -2
  6. package/packages/client/dist/commands/invoke.js +1 -1
  7. package/packages/client/dist/continuity/migrations/007-native-launch-retry.d.ts +19 -0
  8. package/packages/client/dist/continuity/migrations/007-native-launch-retry.js +16 -0
  9. package/packages/client/dist/continuity/sqlite-store.d.ts +1 -1
  10. package/packages/client/dist/continuity/sqlite-store.js +68 -67
  11. package/packages/client/dist/yoloop/invoke-hooks.d.ts +3 -3
  12. package/packages/client/dist/yoloop/invoke-hooks.js +11 -11
  13. package/packages/client/dist/yoloop/shared-yoloop-types.d.ts +2 -1
  14. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +2 -1
  15. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  16. package/packages/shared/dist/yoloop/native-launch-retry.js +16 -0
  17. package/targets-stubs/antigravity/gemini.md +1 -1
  18. package/targets-stubs/antigravity/neocortex.md +1 -1
  19. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  20. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  21. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  22. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  23. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  24. package/targets-stubs/claude-code/neocortex.md +2 -2
  25. package/targets-stubs/codex/AGENTS.md +1 -1
  26. package/targets-stubs/codex/neocortex.toml +1 -1
  27. package/targets-stubs/cursor/agent.md +2 -2
  28. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  29. package/targets-stubs/gemini-cli/agent.md +2 -2
  30. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  31. package/targets-stubs/grok/SKILL.md +1 -1
  32. package/targets-stubs/kimi/neocortex.md +1 -1
  33. package/targets-stubs/openclaw/SKILL.md +1 -1
  34. package/targets-stubs/opencode/neocortex-root.md +2 -2
  35. package/targets-stubs/opencode/neocortex.md +2 -2
  36. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -104,9 +104,9 @@ export declare function maybeCaptureYoloopStartOriginBinding(args: string, proje
104
104
  /**
105
105
  * Post-response hook: apply server-provided operations to local state.
106
106
  * Safe to call for any response — no-op if no yoloopStateUpdate present.
107
- * A `rollover_session` or `commit_successor_transition` update is
108
- * authoritative: failure is returned to the caller so instructions cannot be
109
- * released before durable state exists.
107
+ * Rollover, successor and lock ownership updates are authoritative: failure is
108
+ * returned to the caller so instructions cannot be released before durable
109
+ * state exists.
110
110
  * Non-rollover legacy operations retain fail-soft compatibility.
111
111
  */
112
112
  export declare function persistYoloopFromResponse(metadata: Record<string, unknown> | undefined, projectRoot: string, nowIso?: string): Promise<YoloopPersistenceResult>;
@@ -1,16 +1,16 @@
1
- import{statSync as J}from"node:fs";import{join as X}from"node:path";import{YoloopClientStateStore as L}from"./yoloop-client-state-store.js";import{LEGACY_ADOPTION_RECEIPT_SCHEMA as Q,LEGACY_ADOPTION_TARGET_POLICY as ee,runLegacyYoloopAdoption as te}from"./legacy-yoloop-adoption.js";import{isYoloopInvocation as oe}from"./target-normalization.js";import{applyStateMigration as re,StateMigrationApplyError as ie}from"../migrations/state-json.js";function W(e){return oe(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class ne extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="YoloopStateReadError"}}function j(e,r){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??r}const G=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function ae(e){const r=j(e,"");if(G.has(r))return!0;const t=e?.code;return typeof t=="string"&&G.has(t)}const se=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function we(e){if(typeof e.args!="string"||e.args.length===0)return;const r=e.args.match(se);if(!r)return;const t=r[0];if(e.args.slice(t.length).trim()!=="")return;let n=!1;try{const o=X(e.projectRoot,"docs","epics");n=J(o).isDirectory()}catch(o){const a=o instanceof Error?o.message:String(o);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${a}. Proceeding with raw args.`);return}n&&(e.args=`${t} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function be(e,r,t){if(W(e))try{const i=await te(r,t?{nowIso:t}:{});return i.written&&process.stderr.write(`[yoloop] ${i.receipt.reasonCode}: continuation policy ${ee} (${Q}).
2
- `),await new L(r).readAll(t)}catch(i){const n=j(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${n}. Local yoloop authority was not read; no request was sent.
3
- `),new ne(n)}}async function Se(e,r,t={}){if(W(e))try{let i;try{i=(await new L(r).readAll(t.nowIso))?.state?.currentEpicId}catch{i=void 0}const{runYoloopStartAdaptations:n}=await import("./yoloop-start-origin-binding.js"),o=await n({args:e,projectRoot:r,persistedCurrentEpicId:i,...t.nowIso?{nowIso:t.nowIso}:{},...t.fetchTimeoutMs?{fetchTimeoutMs:t.fetchTimeoutMs}:{},...t.prProvider?{prProvider:t.prProvider}:{},...t.repository?{repository:t.repository}:{}}),a=o.branchModeConversion;!t.quiet&&a&&(a.outcome==="converted"||a.outcome==="refused"&&a.reasonCode!=="branch-mode-conversion-epic-missing")&&process.stderr.write(`[yoloop] branch-mode-conversion-start ${a.outcome}${a.reasonCode?` ${a.reasonCode}`:""}.
4
- `);const s=o.originBinding,p=s.reasonCode==="origin-binding-start-target-ambiguous"||s.reasonCode==="origin-binding-start-target-terminal"||s.reasonCode==="origin-binding-start-branch-mode-not-epic"||s.reasonCode==="origin-binding-start-state-invalid"||s.reasonCode==="origin-binding-start-failed";return!t.quiet&&s.outcome!=="already-bound"&&!p&&process.stderr.write(`[yoloop] origin-binding-start ${s.outcome}${s.reasonCode?` ${s.reasonCode}`:""}.
5
- `),s}catch{t.quiet||process.stderr.write(`[yoloop] origin-binding-start refused origin-binding-start-failed.
6
- `);return}}async function Ce(e,r,t){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const n=i.operations.some(s=>s.type==="rollover_session"||s.type==="commit_successor_transition");let o;const a=n?3:1;for(let s=0;s<a;s+=1)try{return await new L(r).applyUpdate(i,t),{ok:!0,authoritative:n,reasonCodes:[]}}catch(p){if(o=p,!n||s+1>=a||!ae(p))break}{const p=j(o,n?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return n?(process.stderr.write(`[yoloop] ${p}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
1
+ import{statSync as J}from"node:fs";import{join as X}from"node:path";import{YoloopClientStateStore as L}from"./yoloop-client-state-store.js";import{LEGACY_ADOPTION_RECEIPT_SCHEMA as Q,LEGACY_ADOPTION_TARGET_POLICY as ee,runLegacyYoloopAdoption as te}from"./legacy-yoloop-adoption.js";import{isYoloopInvocation as oe}from"./target-normalization.js";import{applyStateMigration as re,StateMigrationApplyError as ie}from"../migrations/state-json.js";function W(e){return oe(e)}const N=Object.freeze({stateReadFailed:"YOLOOP_STATE_READ_FAILED",authoritativeWritebackFailed:"YOLOOP_AUTHORITATIVE_WRITEBACK_FAILED",auxiliaryWritebackFailed:"YOLOOP_AUXILIARY_WRITEBACK_FAILED"});class ne extends Error{reasonCode;constructor(r){super(r),this.reasonCode=r,this.name="YoloopStateReadError"}}function j(e,r){return(e instanceof Error?e.message:String(e)).match(/\bYOLOOP_[A-Z0-9_]+\b/)?.[0]??r}const G=new Set(["YOLOOP_RUN_REVISION_CONFLICT","YOLOOP_RUN_SNAPSHOT_CONFLICT","YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT","EAGAIN","EBUSY","EMFILE","ENFILE"]);function ae(e){const r=j(e,"");if(G.has(r))return!0;const t=e?.code;return typeof t=="string"&&G.has(t)}const se=/^\s*\*?(yoloop|auto-yolo|epic-runner|story-runner|loop-yolo|auto-epic)\b/i;function we(e){if(typeof e.args!="string"||e.args.length===0)return;const r=e.args.match(se);if(!r)return;const t=r[0];if(e.args.slice(t.length).trim()!=="")return;let a=!1;try{const o=X(e.projectRoot,"docs","epics");a=J(o).isDirectory()}catch(o){const s=o instanceof Error?o.message:String(o);e.logger?.warn?.(`[Neocortex] Zero-config *yoloop hook (P121.05): could not stat docs/epics/: ${s}. Proceeding with raw args.`);return}a&&(e.args=`${t} @docs/epics/`,e.logger?.info?.("[Neocortex] Zero-config *yoloop (P121.05): auto-resolved empty args to @docs/epics/"))}async function be(e,r,t){if(W(e))try{const i=await te(r,t?{nowIso:t}:{});return i.written&&process.stderr.write(`[yoloop] ${i.receipt.reasonCode}: continuation policy ${ee} (${Q}).
2
+ `),await new L(r).readAll(t)}catch(i){const a=j(i,N.stateReadFailed);throw process.stderr.write(`[yoloop] ${a}. Local yoloop authority was not read; no request was sent.
3
+ `),new ne(a)}}async function Se(e,r,t={}){if(W(e))try{let i;try{i=(await new L(r).readAll(t.nowIso))?.state?.currentEpicId}catch{i=void 0}const{runYoloopStartAdaptations:a}=await import("./yoloop-start-origin-binding.js"),o=await a({args:e,projectRoot:r,persistedCurrentEpicId:i,...t.nowIso?{nowIso:t.nowIso}:{},...t.fetchTimeoutMs?{fetchTimeoutMs:t.fetchTimeoutMs}:{},...t.prProvider?{prProvider:t.prProvider}:{},...t.repository?{repository:t.repository}:{}}),s=o.branchModeConversion;!t.quiet&&s&&(s.outcome==="converted"||s.outcome==="refused"&&s.reasonCode!=="branch-mode-conversion-epic-missing")&&process.stderr.write(`[yoloop] branch-mode-conversion-start ${s.outcome}${s.reasonCode?` ${s.reasonCode}`:""}.
4
+ `);const n=o.originBinding,p=n.reasonCode==="origin-binding-start-target-ambiguous"||n.reasonCode==="origin-binding-start-target-terminal"||n.reasonCode==="origin-binding-start-branch-mode-not-epic"||n.reasonCode==="origin-binding-start-state-invalid"||n.reasonCode==="origin-binding-start-failed";return!t.quiet&&n.outcome!=="already-bound"&&!p&&process.stderr.write(`[yoloop] origin-binding-start ${n.outcome}${n.reasonCode?` ${n.reasonCode}`:""}.
5
+ `),n}catch{t.quiet||process.stderr.write(`[yoloop] origin-binding-start refused origin-binding-start-failed.
6
+ `);return}}async function Ce(e,r,t){if(!e)return{ok:!0,authoritative:!1,reasonCodes:[]};const i=e.yoloopStateUpdate;if(!i||!Array.isArray(i.operations)||i.operations.length===0)return{ok:!0,authoritative:!1,reasonCodes:[]};const a=i.operations.some(n=>n.type==="rollover_session"||n.type==="commit_successor_transition"||n.type==="acquire_lock"||n.type==="release_lock"&&n.expectedLeaseId!==void 0);let o;const s=a?3:1;for(let n=0;n<s;n+=1)try{return await new L(r).applyUpdate(i,t),{ok:!0,authoritative:a,reasonCodes:[]}}catch(p){if(o=p,!a||n+1>=s||!ae(p))break}{const p=j(o,a?N.authoritativeWritebackFailed:N.auxiliaryWritebackFailed);return a?(process.stderr.write(`[yoloop] ${p}. Authoritative yoloop transition was not persisted; no continuation instructions were released.
7
7
  `),{ok:!1,authoritative:!0,reasonCodes:[p]}):(process.stderr.write(`[yoloop] ${p}. Auxiliary state update was not persisted; retry the same command.
8
- `),{ok:!0,authoritative:!1,reasonCodes:[p]})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,r){return Array.isArray(e)&&e.length<=r&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(t))}function K(e){return c(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ce(e){const r={...e};return delete r.scope,delete r.stateSummary,delete r.graphRetrieval,delete r.runnerBootstrap,delete r.projectEvidence,delete r.continuity,delete r.implementCheckpoint,r}function le(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function de(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function pe(e,r){const t=e.syntheticStory;if(!c(t))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=t.schemaVersion,n=t.epicId,o=t.storyId,a=t.storyPath,s=t.deterministicKey,p=t.storyContent,E=t.storyContentSha256,f=t.lifecycle;if(i!==2||typeof n!="string"||!/^P9\d{18}$/.test(n)||typeof o!="string"||o!==`${n}.01.000001`||typeof a!="string"||a!==`docs/stories/${o}.story.md`||typeof s!="string"||!/^[a-f0-9]{16}$/.test(s)||typeof E!="string"||!/^[a-f0-9]{64}$/.test(E)||typeof p!="string"||p.length===0||p.length>131072||!c(f)||f.branchMode!=="epic"||f.executionBranch!==`epic/${n}`||typeof f.originBranch!="string"||!de(f.originBranch)||typeof f.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(f.graphRevision)||f.isolatedSyntheticEpic!==!0||t.publicSafe!==!0||t.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const u=await import("node:fs/promises"),w=await import("node:path"),I=await import("node:crypto");if(I.createHash("sha256").update(p).digest("hex")!==E)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const k=w.join(r,".neocortex"),O=w.join(k,"state.json"),b=w.join(r,...a.split("/"));let R;try{R=await u.readFile(O,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=I.createHash("sha256").update(R).digest("hex");let y;try{y=JSON.parse(R)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!c(y)||!c(y.stories)||!c(y.epics)||K(y))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!c(y.config)||y.config.default_branch!==f.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const d=y.stories[o];if(d!==void 0&&(!c(d)||d.epic_id!==n||d.story_file!==a||!c(d.inlineYolo)||d.inlineYolo.deterministicKey!==s))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=y.epics[n];if(g!==void 0&&(!c(g)||g.id!==n||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==f.executionBranch||g.origin_branch!==f.originBranch||g.graph_revision!==f.graphRevision||!c(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==s||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const _=c(g)?g:{},S=Array.isArray(_.stories)?_.stories:[];if(S.some(l=>typeof l!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const l of S){const m=y.stories[l];if(!c(m)||m.id!==l||m.epic_id!==n)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const l=await u.readFile(b,"utf8"),m=l.includes(`id: ${o}`)&&l.includes(`synthetic_key: ${s}`);if(l!==p&&!m)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(l){if(l.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const C=S.includes(o)?[...S]:[...S,o],T={...y.stories,[o]:{...c(d)?d:{},id:o,epic_id:n,title:"Synthetic inline USER STORY for yolo",status:c(d)&&typeof d.status=="string"?d.status:"backlog",steps_completed:c(d)&&Array.isArray(d.steps_completed)?d.steps_completed:[],last_step:c(d)?d.last_step??null:null,branch_name:c(d)?d.branch_name??null:null,story_file:a,source:"inline-yolo-materialization",inlineYolo:{...c(d)&&c(d.inlineYolo)?d.inlineYolo:{},schemaVersion:2,deterministicKey:s,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=C.filter(l=>c(T[l])&&le(T[l].status)).length,Y=c(y.inlineYolo)?y.inlineYolo:{},Z=c(Y.materializations)?Y.materializations:{},q=ce({...y,stories:T,epics:{...y.epics,[n]:{..._,id:n,title:typeof _.title=="string"?_.title:"Isolated synthetic inline yolo lifecycle",status:v===C.length&&C.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:f.executionBranch,origin_branch:f.originBranch,graph_revision:f.graphRevision,stories:C,total_stories:C.length,completed_stories:v,...v===C.length&&C.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:s,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...Z,[o]:{schemaVersion:2,epicId:n,storyId:o,storyPath:a,deterministicKey:s,storyContentSha256:E,sourceStateSha256:P,lifecycle:f,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${a}`,reasonCodes:Array.isArray(t.reasonCodes)?t.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${I.randomBytes(6).toString("hex")}`,x=w.join(k,`state.json.tmp.${B}`),z=`${b}.tmp.${B}`,F=w.join(k,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),D=w.join(k,"state.json.inline-yolo.lock");let H=!1,A;const V=async l=>{let m;try{m=await u.open(l,"r"),await m.sync()}catch(h){const $=h.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes($??""))throw h}finally{await m?.close().catch(()=>{})}},U=async(l,m)=>{const h=await u.open(l,"wx",384);try{await h.writeFile(m,"utf8"),await h.sync()}finally{await h.close()}};try{await u.mkdir(k,{recursive:!0}),await u.mkdir(w.dirname(b),{recursive:!0});try{A=await u.open(D,"wx",384),await A.writeFile(`${process.pid}
8
+ `),{ok:!0,authoritative:!1,reasonCodes:[p]})}}function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function M(e,r){return Array.isArray(e)&&e.length<=r&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=160&&/^[A-Za-z0-9_.:+-]+$/.test(t))}function q(e){return c(e.scope)?e.scope.kind==="projected"||typeof e.scope.omittedStoryCount=="number"&&e.scope.omittedStoryCount>0||typeof e.scope.omittedEpicCount=="number"&&e.scope.omittedEpicCount>0:!1}function ce(e){const r={...e};return delete r.scope,delete r.stateSummary,delete r.graphRetrieval,delete r.runnerBootstrap,delete r.projectEvidence,delete r.continuity,delete r.implementCheckpoint,r}function le(e){return typeof e=="string"&&["done","completed","merged"].includes(e.trim().toLowerCase())}function de(e){return/^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/.test(e)&&!e.includes("..")&&!e.includes("//")&&!e.includes("@{")&&!e.endsWith("/")&&!e.endsWith(".")&&!e.endsWith(".lock")}async function pe(e,r){const t=e.syntheticStory;if(!c(t))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-missing"};const i=t.schemaVersion,a=t.epicId,o=t.storyId,s=t.storyPath,n=t.deterministicKey,p=t.storyContent,E=t.storyContentSha256,f=t.lifecycle;if(i!==2||typeof a!="string"||!/^P9\d{18}$/.test(a)||typeof o!="string"||o!==`${a}.01.000001`||typeof s!="string"||s!==`docs/stories/${o}.story.md`||typeof n!="string"||!/^[a-f0-9]{16}$/.test(n)||typeof E!="string"||!/^[a-f0-9]{64}$/.test(E)||typeof p!="string"||p.length===0||p.length>131072||!c(f)||f.branchMode!=="epic"||f.executionBranch!==`epic/${a}`||typeof f.originBranch!="string"||!de(f.originBranch)||typeof f.graphRevision!="string"||!/^[a-f0-9]{64}$/.test(f.graphRevision)||f.isolatedSyntheticEpic!==!0||t.publicSafe!==!0||t.sanitized!==!0)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-mutation-invalid"};const u=await import("node:fs/promises"),w=await import("node:path"),I=await import("node:crypto");if(I.createHash("sha256").update(p).digest("hex")!==E)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-content-integrity-invalid"};const k=w.join(r,".neocortex"),O=w.join(k,"state.json"),b=w.join(r,...s.split("/"));let R;try{R=await u.readFile(O,"utf8")}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-missing"}}const P=I.createHash("sha256").update(R).digest("hex");let y;try{y=JSON.parse(R)}catch{return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-corrupt"}}if(!c(y)||!c(y.stories)||!c(y.epics)||q(y))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-not-full"};if(!c(y.config)||y.config.default_branch!==f.originBranch)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-origin-branch-conflict"};const d=y.stories[o];if(d!==void 0&&(!c(d)||d.epic_id!==a||d.story_file!==s||!c(d.inlineYolo)||d.inlineYolo.deterministicKey!==n))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-conflict"};const g=y.epics[a];if(g!==void 0&&(!c(g)||g.id!==a||g.source!=="inline-yolo-materialization"||g.branch_mode!=="epic"||g.execution_branch!==f.executionBranch||g.origin_branch!==f.originBranch||g.graph_revision!==f.graphRevision||!c(g.inlineYoloLifecycle)||g.inlineYoloLifecycle.deterministicKey!==n||g.inlineYoloLifecycle.isolatedSyntheticEpic!==!0||!Array.isArray(g.stories)))return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-conflict"};const _=c(g)?g:{},S=Array.isArray(_.stories)?_.stories:[];if(S.some(l=>typeof l!="string")||new Set(S).size!==S.length)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-story-list-invalid"};for(const l of S){const m=y.stories[l];if(!c(m)||m.id!==l||m.epic_id!==a)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-epic-ownership-conflict"}}try{const l=await u.readFile(b,"utf8"),m=l.includes(`id: ${o}`)&&l.includes(`synthetic_key: ${n}`);if(l!==p&&!m)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-conflict"}}catch(l){if(l.code!=="ENOENT")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-story-file-unreadable"}}const C=S.includes(o)?[...S]:[...S,o],T={...y.stories,[o]:{...c(d)?d:{},id:o,epic_id:a,title:"Synthetic inline USER STORY for yolo",status:c(d)&&typeof d.status=="string"?d.status:"backlog",steps_completed:c(d)&&Array.isArray(d.steps_completed)?d.steps_completed:[],last_step:c(d)?d.last_step??null:null,branch_name:c(d)?d.branch_name??null:null,story_file:s,source:"inline-yolo-materialization",inlineYolo:{...c(d)&&c(d.inlineYolo)?d.inlineYolo:{},schemaVersion:2,deterministicKey:n,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0}}},v=C.filter(l=>c(T[l])&&le(T[l].status)).length,Y=c(y.inlineYolo)?y.inlineYolo:{},K=c(Y.materializations)?Y.materializations:{},Z=ce({...y,stories:T,epics:{...y.epics,[a]:{..._,id:a,title:typeof _.title=="string"?_.title:"Isolated synthetic inline yolo lifecycle",status:v===C.length&&C.length>0?"done":"in-progress",source:"inline-yolo-materialization",branch_mode:"epic",execution_branch:f.executionBranch,origin_branch:f.originBranch,graph_revision:f.graphRevision,stories:C,total_stories:C.length,completed_stories:v,...v===C.length&&C.length>0?{}:{completed_at:null},inlineYoloLifecycle:{schemaVersion:2,deterministicKey:n,isolatedSyntheticEpic:!0}}},inlineYolo:{...Y,schemaVersion:2,materializations:{...K,[o]:{schemaVersion:2,epicId:a,storyId:o,storyPath:s,deterministicKey:n,storyContentSha256:E,sourceStateSha256:P,lifecycle:f,publicSafe:!0,sanitized:!0,materializedBeforeExecution:!0,ephemeralExecutionForbidden:!0,pipelineTrigger:`*yolo @${s}`,reasonCodes:Array.isArray(t.reasonCodes)?t.reasonCodes:[]}}},last_updated:new Date().toISOString()}),B=`${Date.now()}-${I.randomBytes(6).toString("hex")}`,x=w.join(k,`state.json.tmp.${B}`),z=`${b}.tmp.${B}`,F=w.join(k,`state.json.backup-${new Date().toISOString().replace(/[:.]/g,"-")}`),D=w.join(k,"state.json.inline-yolo.lock");let H=!1,A;const V=async l=>{let m;try{m=await u.open(l,"r"),await m.sync()}catch(h){const $=h.code;if(!["EINVAL","ENOTSUP","EPERM","EISDIR"].includes($??""))throw h}finally{await m?.close().catch(()=>{})}},U=async(l,m)=>{const h=await u.open(l,"wx",384);try{await h.writeFile(m,"utf8"),await h.sync()}finally{await h.close()}};try{await u.mkdir(k,{recursive:!0}),await u.mkdir(w.dirname(b),{recursive:!0});try{A=await u.open(D,"wx",384),await A.writeFile(`${process.pid}
9
9
  ${P}
10
- `,"utf8"),await A.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const l=await u.readFile(O,"utf8");if(I.createHash("sha256").update(l).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await u.access(b)}catch{await U(z,p),await u.rename(z,b),await V(w.dirname(b)),H=!0}await u.copyFile(O,F);const h=await u.open(F,"r");try{await h.sync()}finally{await h.close()}return await U(x,JSON.stringify(q,null,2)),await u.rename(x,O),await V(k),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${o}; backup=${w.basename(F)}.
10
+ `,"utf8"),await A.sync()}catch($){if($.code==="EEXIST")return{applied:!1,blocking:!0,reasonCode:"inline-yolo-writeback-locked"};throw $}const l=await u.readFile(O,"utf8");if(I.createHash("sha256").update(l).digest("hex")!==P)return{applied:!1,blocking:!0,reasonCode:"inline-yolo-state-cas-conflict"};try{await u.access(b)}catch{await U(z,p),await u.rename(z,b),await V(w.dirname(b)),H=!0}await u.copyFile(O,F);const h=await u.open(F,"r");try{await h.sync()}finally{await h.close()}return await U(x,JSON.stringify(Z,null,2)),await u.rename(x,O),await V(k),process.stderr.write(`[Neocortex] inline yolo story materialized with bounded full-state merge; story=${o}; backup=${w.basename(F)}.
11
11
  `),{applied:!0,blocking:!1,reasonCode:"inline-yolo-materialized"}}catch(l){await Promise.allSettled([u.unlink(x),u.unlink(z)]),H&&await u.readFile(b,"utf8").catch(()=>{})===p&&await u.unlink(b).catch(()=>{});const m=l.message??String(l);return process.stderr.write(`[Neocortex] inline yolo materialization failed: ${m}.
12
- `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await A?.close().catch(()=>{}),A&&await u.unlink(D).catch(()=>{})}}async function ke(e,r){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return pe(e,r);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,n=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!c(i)||Object.keys(i).some(o=>!n.has(o))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(o=>!c(o)||Object.keys(o).some(a=>!["kind","source","target"].includes(a))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(o.kind))||typeof o.target!="string"||o.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.target)||o.source!==void 0&&(typeof o.source!="string"||o.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.source)))||!M(i.migratedEpicIds,4096)||!M(i.migratedStoryIds,4096)||!M(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const o=re(r,i),a=`.neocortex/state.json.migration-backup-${o.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${o.outcome}; operation=${o.operationId}; backup=${o.backupHash?a:"none"}.
13
- `),{applied:o.outcome==="applied",blocking:!1,reasonCode:o.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(o){const a=o instanceof ie?o.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${a}.
14
- `),{applied:!1,blocking:!0,reasonCode:a}}}const t=e.migratedState;return!t||typeof t!="object"||Array.isArray(t)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:K(t)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
12
+ `),{applied:!1,blocking:!0,reasonCode:"inline-yolo-persistence-failed"}}finally{await A?.close().catch(()=>{}),A&&await u.unlink(D).catch(()=>{})}}async function ke(e,r){if(!e||e.stateMutated!==!0)return{applied:!1,blocking:!1,reasonCode:"state-writeback-not-requested"};if(e.stateMutationStrategy==="merge-inline-yolo-v2"||e.stateMutationReason==="inline-yolo-materialized-synthetic-story")return pe(e,r);if(e.stateMutationStrategy==="state-migration-v1"||e.stateMigrationPlan!==void 0){const i=e.stateMigrationPlan,a=new Set(["schemaVersion","operationId","sourceSchemaVersion","targetSchemaVersion","sourceCanonicalHash","targetCanonicalHash","steps","migratedEpicIds","migratedStoryIds","preservedUnknownFieldCount","reasonCodes","sourceByteDigest"]);if(!c(i)||Object.keys(i).some(o=>!a.has(o))||i.schemaVersion!=="StateMigrationPlan/1.0"||typeof i.operationId!="string"||!/^smig_[a-f0-9]{32}$/.test(i.operationId)||typeof i.sourceCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.sourceCanonicalHash)||typeof i.targetCanonicalHash!="string"||!/^[a-f0-9]{64}$/.test(i.targetCanonicalHash)||typeof i.sourceByteDigest!="string"||!/^[a-f0-9]{64}$/.test(i.sourceByteDigest)||![0,1,"absent"].includes(i.sourceSchemaVersion)||i.targetSchemaVersion!==1||!Array.isArray(i.steps)||i.steps.length>8192||i.steps.some(o=>!c(o)||Object.keys(o).some(s=>!["kind","source","target"].includes(s))||!["initialize-collection","merge-epic","merge-story","preserve-legacy","remove-legacy","set-schema-version"].includes(String(o.kind))||typeof o.target!="string"||o.target.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.target)||o.source!==void 0&&(typeof o.source!="string"||o.source.length>512||!/^[A-Za-z0-9_.:[\]-]+$/.test(o.source)))||!M(i.migratedEpicIds,4096)||!M(i.migratedStoryIds,4096)||!M(i.reasonCodes,32)||!Number.isSafeInteger(i.preservedUnknownFieldCount)||i.preservedUnknownFieldCount<0)return{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"};try{const o=re(r,i),s=`.neocortex/state.json.migration-backup-${o.operationId}`;return process.stderr.write(`[P220-EV-STATE-MIGRATION] outcome=${o.outcome}; operation=${o.operationId}; backup=${o.backupHash?s:"none"}.
13
+ `),{applied:o.outcome==="applied",blocking:!1,reasonCode:o.outcome==="applied"?"state-migration-applied":"state-migration-replay-verified"}}catch(o){const s=o instanceof ie?o.reasonCode:"state-migration-apply-failed";return process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=${s}.
14
+ `),{applied:!1,blocking:!0,reasonCode:s}}}const t=e.migratedState;return!t||typeof t!="object"||Array.isArray(t)?{applied:!1,blocking:!0,reasonCode:"state-writeback-payload-missing"}:q(t)?(process.stderr.write(`[Neocortex] Refused projected/partial state replacement; canonical state was not modified.
15
15
  `),{applied:!1,blocking:!0,reasonCode:"state-writeback-partial-rejected"}):(process.stderr.write(`[P220-EV-STATE-MIGRATION] blocked=state-migration-plan-missing-or-invalid; canonical state was not modified.
16
16
  `),{applied:!1,blocking:!0,reasonCode:"state-migration-plan-missing-or-invalid"})}async function Ee(e){if(!e.featureFlag)return{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:"flag off"};try{return await(await import("./discovery-hook.js")).runDiscoveryHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] discovery hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,added:Object.freeze([]),skipped:Object.freeze([]),storiesAdded:0,reason:`lazy load error: ${t}`}}}async function _e(e){if(!e.featureFlag)return{applied:!1,reason:"flag_off"};try{return await(await import("../graph-retrieval/pre-command-hook.js")).runGraphRetrievalHook(e)}catch(r){const t=r instanceof Error?r.message:String(r);return e.logger?.warn?.(`[neocortex] graph retrieval hook (lazy load) failed: ${t}. Proceeding without enrichment.`),{applied:!1,reason:"hook_error",warning:t}}}export{N as YOLOOP_PERSISTENCE_REASON_CODES,ne as YoloopStateReadError,W as isYoloopTrigger,we as maybeAutoResolveYoloopArgs,Se as maybeCaptureYoloopStartOriginBinding,Ee as maybeRunDiscoveryHook,_e as maybeRunGraphRetrievalHook,ke as persistMigratedStateFromResponse,Ce as persistYoloopFromResponse,be as readYoloopForRequest};
@@ -27,7 +27,7 @@ export type YoloopSessionMode = 'directory' | 'epic-file' | 'epic-id';
27
27
  export type YoloopLockOwnerKind = 'client' | 'server';
28
28
  export type YoloopLockOwnerPidState = 'live' | 'stale' | 'unknown';
29
29
  export type YoloopLockLeaseState = 'active' | 'expired' | 'unknown';
30
- export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1' | 'continuation-replan-v1' | 'cross-epic-continuation-reconcile-v1';
30
+ export type YoloopPersistenceCapability = 'rollover-session-v1' | 'successor-transition-v1' | 'continuation-replan-v1' | 'native-launch-retry-v1' | 'cross-epic-continuation-reconcile-v1';
31
31
  export interface YoloopCrossEpicReconciliationEvidenceV1 {
32
32
  readonly schemaVersion: 'YoloopCrossEpicReconciliationEvidence/1.0';
33
33
  readonly repositoryFingerprint: string;
@@ -299,6 +299,7 @@ export type YoloopStateOperation = {
299
299
  readonly expectedRunId?: string;
300
300
  readonly expectedSessionId?: string;
301
301
  readonly expectedLeaseId?: string;
302
+ readonly expectedLeaseExpiresAt?: string;
302
303
  } | {
303
304
  readonly type: 'write_state';
304
305
  readonly state: YoloopPersistedCounters;
@@ -23,7 +23,7 @@
23
23
  * setSecureFilePermissions helper from secure-config.ts.
24
24
  */
25
25
  import type { YoloopPersistedCounters, YoloopPersistedState, YoloopRecoveryAttemptRef, YoloopRunControlV1, YoloopRunTransitionReceiptV1, YoloopStateOperation, YoloopStateUpdate } from './shared-yoloop-types.js';
26
- export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1", "continuation-replan-v1"];
26
+ export declare const YOLOOP_PERSISTENCE_CAPABILITIES: readonly ["rollover-session-v1", "successor-transition-v1", "continuation-replan-v1", "native-launch-retry-v1"];
27
27
  type YoloopSessionRolloverOperation = Extract<YoloopStateOperation, {
28
28
  readonly type: 'rollover_session';
29
29
  }>;
@@ -101,6 +101,7 @@ export declare class YoloopClientStateStore {
101
101
  * the legacy checkout-local adapter; a corrupt v2 never falls back.
102
102
  */
103
103
  private readCommonAuthorityIfPresent;
104
+ private reconcileCommonLock;
104
105
  /** Apply legacy operation semantics to the common authority under its Git CAS. */
105
106
  private applyCommonOperation;
106
107
  private reserveContinuationAuthority;
@@ -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(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
+ import{promises as y}from"node:fs";import{existsSync as C}from"node:fs";import{createHash as P}from"node:crypto";import{join as R,dirname as ye}from"node:path";import{hostname as N}from"node:os";import{setSecureFilePermissions as Oe,setSecureDirPermissions as _e}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as B}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as z,epicOperationalCanonicalJson as E,epicOperationalHash as x,mutateEpicOperationalState as k,readEpicOperationalState as m}from"../git/epic-operational-state.js";import{yoloopDomainHash as Ie}from"../../../shared/dist/yoloop/canonical.js";const fe=".neocortex",J="yoloop-state.json",we="yoloop.lock",Se="yoloop-state.mutation.lock",W="yoloop-session-rollover.json",G="yoloop-successor-transition.json",X=360*60*1e3,Re=3e4,Ee=200,Z=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1","native-launch-retry-v1"]),Ce={warn:()=>{},info:()=>{},error:()=>{}};function Y(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 rt(t){return{lock:null,state:Y(t),capabilities:Z}}class ot{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Ce){this.projectRoot=e,this.stateDir=R(e,fe),this.statePath=R(this.stateDir,J),this.lockPath=R(this.stateDir,we),this.mutationLockPath=R(this.stateDir,Se),this.rolloverManifestPath=R(this.stateDir,W),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s){const c=await this.reconcileCommonLock(s,n);return{lock:c.lock,state:c.state,capabilities:[...new Set([...c.capabilities,"native-launch-retry-v1"])]}}await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[r,o]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(r,n),state:o,capabilities:Z}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const r of e.operations)await this.applyCommonOperation(r,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const r of e.operations)await this.applyOperation(r,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!he(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const r=o=>{const a=(o.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(!he(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=o.continuationReceipts??[],d=i.find(l=>ze(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(E(d)===E(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...o,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:o,operational:a}=m(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return r(a.yoloop.state)==="unchanged"?"unchanged":(await k(this.projectRoot,{identityHash:c[0],expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=r(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const o=r(await this.readState(s));return o==="unchanged"?"unchanged":(await this.writeState(o),"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 r=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(r)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(r).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=Ye(a.status,e);if(!u)throw new Error(A.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(He({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:r}),r)})}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:r,...o}=e.state;await this.writeState({...o,...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 z(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=m(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"&&!C(R(this.projectRoot,".git")))return null;throw e}}async reconcileCommonLock(e,n){const s=e.yoloop.lock;if(!s||s.ownerKind!=="client")return e.yoloop;const r=ie(s);if(!ae(e.yoloop,n,r))return{...e.yoloop,lock:{...s,ownerPidState:r==="live"?"live":"unknown"}};const{document:o,operational:a}=m(this.projectRoot);if(E(a.yoloop.lock)!==E(s))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const c=Object.values(a.identities).filter(d=>d.epicId===s.currentEpicId);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");const{value:i}=await k(this.projectRoot,{identityHash:c[0].identityHash,expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},d=>{if(d.activeJournal!==null||E(d.yoloop.lock)!==E(s)||!ae(d.yoloop,n,ie(s)))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const l={...d.yoloop,lock:null};return d.yoloop=l,l});return i}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await z(this.projectRoot,e);return}const{document:s,operational:r}=m(this.projectRoot),o=Object.keys(r.identities);if(o.length!==1)throw new Error("epic-operational-identity-mismatch");const a=o[0];await k(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:r.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d){if(d.sessionId===e.lock.sessionId&&d.leaseId===e.lock.leaseId&&d.hostname===N()&&d.pid===process.pid)return;throw new Error("YOLOOP_LOCK_HELD")}d={...e.lock,pid:process.pid,hostname:N(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??X,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.expectedLeaseExpiresAt&&(d?.leaseExpiresAt??d?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)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(E(O)!==E(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||x("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(x("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||x("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:M([...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),r=s.pendingContinuationAuthorities??[],o=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!o)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=r.find(c=>c.idempotencyKey===o);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(r.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...r,e]})}async acknowledgeContinuationAuthority(e,n,s){const r=await this.readState(s),o=r.pendingContinuationAuthorities??[],a=o.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=o[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=o.filter((l,u)=>u!==a),d=r.continuationReceipts??[];await this.writeState({...r,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,r){const o=await this.readState(r),a=o.pendingContinuationAuthorities??[],c=o.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({...o,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const r=await this.readState(s);if(r.currentSession||(r.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(o){if(o.code!=="ENOENT")throw o}await this.writeState({...r,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:C(this.lockPath),rolloverManifestPresent:C(this.rolloverManifestPath),successorTransitionManifestPresent:C(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(r){throw r.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):r}if(P("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(C(this.lockPath)||C(this.rolloverManifestPath)||C(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:P("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const r=await y.open(s,"w",384);try{await r.writeFile(n),await r.sync()}finally{await r.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(r){throw await y.unlink(s).catch(()=>{}),r}}async replanContinuationSession(e,n){const{type:s,payloadHash:r,receipt:o,...a}=e;if(Ne(a)!==e.payloadHash||!Q(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(!Q(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),r=s.recovery_history??[];if(r.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=M([...r,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 r=await this.readState(s),o=r.recovery_history??[],a=o.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=o[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=o.slice();i[a]={...c,outcome:n,finished_at:s};const d={...r,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:N(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??X,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},r=JSON.stringify(s,null,2);try{const o=await y.open(this.lockPath,"wx");try{await o.writeFile(r,"utf8")}finally{await o.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(o){const a=o;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),o;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"),o;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(r,"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||e.expectedLeaseExpiresAt&&(s?.leaseExpiresAt??s?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(r){const o=r;if(o.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:o.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 Ke(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"),Y(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const r=await y.open(n,"w",384);try{await r.writeFile(s,"utf8"),await r.sync()}finally{await r.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(r){const o=r;this.logger.error({event:"yoloop_state_write_error",err:o.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw r}}async rolloverSession(e,n){D(e);const s=await this.readRolloverManifest();if(s){if(xe(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 r=await this.readState(n),o=await this.readLock();ne(e,r,o),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 r=h(s)===h(e.next);if(!r){const a=await this.readLock();ne(e,s,a),await this.writeState(e.next),r=!0}const o=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(o){if(o.sessionId!==e.expectedSessionId||o.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!r)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 D(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){H(e);const s=await this.readSuccessorTransitionManifest();if(s){if(ge(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 r=await this.readState(n);if(U(e,r)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}ee(e,r),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(!U(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const o=Pe(e,s);await this.writeState(o),s=await this.readState(n)}if(!U(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 H(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 r=await this.readState(s);if(!r.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const o={...r,currentSession:{...r.currentSession,currentEpicIndex:e}};await this.writeState(o),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<Ee;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(r){if(r.code!=="EEXIST")throw r;try{const o=await y.stat(this.mutationLockPath);if(Date.now()-o.mtimeMs>Re){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(o=>setTimeout(o,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){K(e);const s=await this.readState(n),r=s.runControl,o=r?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(o){if(o.operationId===e.operationId&&o.idempotencyKey===e.idempotencyKey&&o.payloadHash===e.payloadHash)return o;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(r&&r.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");F(r,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){te(e);const s=await this.readState(n),r=s.runControl,o={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=r?.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(r?.predecessor)===h(o))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!r||r.runId!==e.previousRunId||!["exhausted","success"].includes(r.status)||r.revision!==e.expectedRevision||r.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(o))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 K(i),F(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{Oe(e)}catch{}}trySetDirPerms(e){try{_e(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=b(e,n),r={...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(!r.pid||r.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(r.hostname&&r.hostname!==N())return{...r,ownerPidState:"unknown"};try{return process.kill(r.pid,0),{...r,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(b(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!==N())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===N()}async cleanupOrphanTempFiles(){try{const e=ye(this.statePath),n=await y.readdir(e),s=[`${J}.tmp.`,`${W}.tmp.`,`${G}.tmp.`],r=n.filter(o=>s.some(a=>o.startsWith(a)));for(const o of r)try{await y.unlink(R(e,o))}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 P("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ne(t){return _("p222-yoloop-continuation-replan-v1",t)}function Q(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 Te(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Le(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function me(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function Ae(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function ge(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;te(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,r=t.acknowledgement?.receipt.idempotencyKey,o=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!==Ae(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||r!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof o!="string"||!e.test(o))||s!==void 0&&o===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function ee(t,e){if(H(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")}ve(t,e)}function ve(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],r=t.acknowledgement;if(r){const d=n.find(p=>p.idempotencyKey===r.idempotencyKey);if(!d||r.receipt.sessionId!==d.sessionId||h(r.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==r.idempotencyKey),u=[...s.slice(-63),r.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 o=t.reservation?.authority;if(!o)return;const a=String(o.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(o))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Pe(t,e){ee(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function U(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n);const r={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(r)}function xe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function D(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!==Le(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 te(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!==me(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function ne(t,e,n){D(t);const s=e.currentSession;if(!s||Te(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const r=e.runControl;if((r?.revision??0)!==t.expectedRevision||(r?.latestSnapshotHash??null)!==t.expectedSnapshotHash||r&&r.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 o=t.exhaustedRun;if(r)if(r.status==="exhausted"){if(h(o)!==h(r))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!o||o.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=o.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:r.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:r.revision,expectedSnapshotHash:r.latestSnapshotHash,payloadHash:c.payloadHash,next:o};K(i),F(r,i)}else{const c=o?.receipts[0],i=o?.receipts[1];if(o&&(o.runId!==t.runId||o.status!=="exhausted"||o.revision!==2||o.events.length!==2||o.progressSnapshots.length!==4||o.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`||o.latestSnapshotHash!==i.snapshotHash||o.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...o?{runControl:o}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function se(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 A=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ke={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 Ye(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:A.has(t)||t==="cancelling"?null:"cancelling"}function He(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},r={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},o=_("p220-yoloop-progress-snapshot-id-v1",{runId:r.runId,operationId:r.operationId,sequence:r.sequence,phase:r.phase}),a={...r,snapshotId:o,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...r,snapshotId:o})},c={...r,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},L=se(I),v={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:L,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:L,next:{...O,receipts:[...O.receipts,v]}}}function K(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!==se(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function F(t,e){const n=e.next,s=t?.events??[],r=t?.progressSnapshots??[],o=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!==r.length+2||n.receipts.length!==o.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,r.length))!==h(r)||h(n.receipts.slice(0,o.length))!==h(o))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(A.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(!(ke[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");re(a),re(c),Ue(i,s.at(-1)?.eventHash??null)}function re(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ue(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-${De(`${t}:${e}`)}`}function De(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 b(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),r=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(r)?"unknown":s<=r?"expired":"active"}function ie(t){if(t.hostname!==N()||!Number.isSafeInteger(t.pid)||t.pid<=0)return"unknown";try{return process.kill(t.pid,0),"live"}catch(e){return e.code==="ESRCH"?"stale":"unknown"}}function ae(t,e,n){const s=t.lock;if(s?.ownerKind!=="client"||!s.leaseId||!s.sessionId)return!1;if(b(s,e)==="expired")return!0;const r=t.state.runControl,o=r?.progressSnapshots.at(-1),a=r?.receipts.at(-1);return r&&o&&a&&r.runId===s.sessionId&&A.has(r.status)&&o.runId===r.runId&&o.revision===r.revision&&o.status===r.status&&o.phase==="after"&&o.snapshotHash===r.latestSnapshotHash&&a.runId===r.runId&&a.revision===r.revision&&a.status===r.status&&a.snapshotHash===o.snapshotHash&&a.operationId===o.operationId&&Date.parse(o.occurredAt)>=Date.parse(s.startedAt)&&Date.parse(o.occurredAt)<=Date.parse(e)?!0:n==="stale"&&(t.state.pendingContinuationAuthorities?.length??0)===0}function Ke(t,e){const n=Y(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)?M(t.recovery_history):[]}}function M(t){return t.length<=B?t:t.slice(t.length-B)}const V=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"]),Fe=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function be(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(Fe.has(n))return 0;const s=V.indexOf(e);return s<0?V.length:V.length-1-s}const $="yoloop-round-refused-before-setup",Me="neocortex.p230.round-refused-before-setup.v1",ce=64,Ve=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),$e="reasonCode,storyId",de=/^[a-z0-9][a-z0-9-]{2,79}$/,je=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,qe=/^[a-f0-9]{64}$/;function g(t){return typeof t=="string"&&je.test(t)&&!t.includes("..")}function T(t){return typeof t=="string"&&qe.test(t)}function le(t){if(!(!Array.isArray(t)||t.length===0||t.length>ce)&&t.every(g)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function ue(t){return Ie(Me,{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 Be(t){if(!t||!g(t.epicId)||!T(t.sessionId)||!T(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ce)return;const e=t.refusals.map(r=>({storyId:r?.storyId,reasonCode:r?.reasonCode})).sort((r,o)=>String(r.storyId).localeCompare(String(o.storyId)));if(!e.every(r=>g(r.storyId)&&typeof r.reasonCode=="string"&&de.test(r.reasonCode)))return;const n=e.map(r=>r.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:$,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(r=>Object.freeze({storyId:r.storyId,reasonCode:r.reasonCode})))};return Object.freeze({...s,digest:ue(s)})}function ze(t){return S(t)&&t.kind===$}function he(t,e){if(!S(t)||Object.keys(t).some(p=>!Ve.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:r,sessionId:o,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==$||!g(r)||!T(o)||!T(a)||!T(d))return!1;const l=le(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===$e&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&de.test(p.reasonCode))||d!==ue(t))return!1;if(!e)return!0;const u=le([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&o===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Je="story-round-no-setup-evidence";function it(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,r=S(s?.expectedTransition)?s.expectedTransition:void 0,o=Array.isArray(r?.storyLifecycle)?r.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||!o||o.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,L=Array.isArray(I?.receipts)?I.receipts:[],v=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],pe=f=>O.some(w=>S(w)&&w.storyId===f)||L.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||v.some(w=>S(w)&&w.storyId===f);for(const f of i){if(pe(f))return;const w=o.find(q=>S(q)&&q.storyId===f),j=S(t.stories[f])?t.stories[f]:void 0;if(!w||!j||!Number.isSafeInteger(w.remaining)||be(j.status)!==w.remaining)return}return Be({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Je}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{Z as YOLOOP_PERSISTENCE_CAPABILITIES,Je as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,$ as YOLOOP_ROUND_REFUSED_KIND,ot as YoloopClientStateStore,Be as buildClientYoloopRoundRefusedReceipt,Ne as buildYoloopContinuationReplanPayloadHash,se as buildYoloopRunTransitionPayloadHash,Le as buildYoloopSessionRolloverPayloadHash,me as buildYoloopSuccessorRunPayloadHash,Ae as buildYoloopSuccessorTransitionPayloadHash,M as capRecoveryHistory,be as clientYoloopStoryLifecycleRemaining,Y as createDefaultCounters,rt as createDefaultState,it as deriveYoloopRoundRefusedBeforeSetupReceipt,Te as fingerprintYoloopSession,ze as isClientYoloopRoundRefusedRecord,he as isValidClientYoloopRoundRefusedReceipt};
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'node:crypto';
2
+ export const NATIVE_LAUNCH_RETRY_CAPABILITY = 'native-launch-retry-v1';
3
+ /** Terminal refusal is distinct from loss of contact with an executor. */
4
+ export function isNativeLaunchRefusal(receipt) {
5
+ return receipt.topology === 'native-agent' && receipt.state === 'interrupted'
6
+ && receipt.freshness === 'fresh' && receipt.revision > 0
7
+ && receipt.handle === null && receipt.parentHandle === null
8
+ && receipt.observedAt !== null && receipt.observedAt === receipt.terminalAt
9
+ && ((receipt.observationSource === 'host-event'
10
+ && (receipt.reasonCode === 'sentinel-profile-unavailable' || receipt.reasonCode === 'native-agent-launch-refused'))
11
+ || (receipt.observationSource === 'host-list' && receipt.reasonCode === 'native-agent-launch-refused'));
12
+ }
13
+ /** One deterministic retry for a reservation, even after repeated root invocations. */
14
+ export function nativeLaunchRetryKey(dispatchKey) {
15
+ return `sha256:${createHash('sha256').update(`native-launch-retry-v1:${dispatchKey}`).digest('hex')}`;
16
+ }
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.66.13 | OrNexus Team
1
+ # 🧠 Neocortex v4.66.14 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.13 | OrNexus Team — Development orchestrator candidate (native-needs-validation)."
3
+ description: "🧠 Neocortex v4.66.14 | 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
3
- description: "🧠 Neocortex v4.66.13 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.14 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root alias of neocortex)'
6
6
  icon: '>'
7
- version: '4.66.13'
7
+ version: '4.66.14'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.13 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.66.14 | 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.13 │
116
+ │ ### ######## v4.66.14 │
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.13 │
105
+ │ ### ######## v4.66.14 │
106
106
  │ ######### ##### │
107
107
  │ ## ############## Development Orchestrator │
108
108
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.66.13'
7
+ version: '4.66.14'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.13 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.14 | 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.13 │
116
+ │ ### ######## v4.66.14 │
117
117
  │ ######### ##### │
118
118
  │ ## ############## Development Orchestrator │
119
119
  │ ## ### ###### ## OrNexus Team │
@@ -28,7 +28,7 @@ returned instructions.
28
28
 
29
29
  <!-- END: Plugin Conflict Prevention -->
30
30
 
31
- # Neocortex v4.66.13 | OrNexus Team
31
+ # Neocortex v4.66.14 | OrNexus Team
32
32
 
33
33
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
34
34
 
@@ -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.13 | OrNexus Team — Development orchestrator for direct @neocortex requests."
4
+ description = "🧠 Neocortex v4.66.14 | 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.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.13 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.14 | 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.13 │
118
+ │ ### ######## v4.66.14 │
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.13 | OrNexus Team — Route explicit Neocortex *commands through the public thin client in DeepSeek Harness."
3
+ description: "🧠 Neocortex v4.66.14 | 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
  ---