@ornexus/neocortex 4.65.1 → 4.66.1

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 (150) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/install.ps1 +243 -77
  4. package/install.sh +221 -102
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/platform-detector.js +1 -1
  7. package/packages/client/dist/agent/refresh-stubs.d.ts +50 -0
  8. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  9. package/packages/client/dist/cli.js +5 -4
  10. package/packages/client/dist/commands/doctor.d.ts +26 -1
  11. package/packages/client/dist/commands/doctor.js +2 -2
  12. package/packages/client/dist/commands/invoke.d.ts +183 -5
  13. package/packages/client/dist/commands/invoke.js +94 -87
  14. package/packages/client/dist/commands/planning-qa.d.ts +64 -0
  15. package/packages/client/dist/commands/planning-qa.js +1 -0
  16. package/packages/client/dist/commands/refactor-control.js +3 -3
  17. package/packages/client/dist/commands/story-checkpoint.d.ts +3 -1
  18. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  19. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  20. package/packages/client/dist/commands/story-worktree.js +1 -1
  21. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +64 -1
  22. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  23. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  24. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  25. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  26. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  27. package/packages/client/dist/git/governance-runtime-store.d.ts +172 -0
  28. package/packages/client/dist/git/governance-runtime-store.js +3 -0
  29. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  30. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  31. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  32. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  33. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  34. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  35. package/packages/client/dist/memory/shared-project-memory-types.d.ts +39 -2
  36. package/packages/client/dist/memory/shared-project-memory-types.js +2 -2
  37. package/packages/client/dist/policy/subagent-approval-policy.js +1 -1
  38. package/packages/client/dist/private-execution/codex-executor.d.ts +21 -1
  39. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  40. package/packages/client/dist/private-execution/delivery.d.ts +17 -11
  41. package/packages/client/dist/private-execution/delivery.js +8 -6
  42. package/packages/client/dist/private-execution/diagnosis-root-review.d.ts +89 -0
  43. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -2
  44. package/packages/client/dist/private-execution/frozen-handoff.js +3 -3
  45. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  46. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  47. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  48. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  49. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  50. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  51. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  52. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  53. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  54. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  55. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  56. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  57. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  58. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  59. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  60. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  61. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  62. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  63. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  64. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  65. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  66. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  67. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  68. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  69. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  70. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  71. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  72. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  73. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  74. package/packages/client/dist/private-execution/harness-process.js +1 -0
  75. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  76. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  77. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  78. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +75 -1
  79. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -5
  80. package/packages/client/dist/private-execution/planning-generation-checkpoint.d.ts +9 -1
  81. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +4 -4
  82. package/packages/client/dist/private-execution/planning-research-checkpoint.d.ts +9 -1
  83. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -4
  84. package/packages/client/dist/private-execution/root-memory-request.d.ts +4 -1
  85. package/packages/client/dist/private-execution/root-memory-request.js +1 -1
  86. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +3 -1
  87. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -1
  88. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -1
  89. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  90. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  91. package/packages/client/dist/runner/headless/managed-profile.d.ts +20 -0
  92. package/packages/client/dist/runner/headless/managed-profile.js +1 -1
  93. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -2
  94. package/packages/client/dist/runner/headless/run-yoloop.d.ts +40 -0
  95. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  96. package/packages/client/dist/runner/headless/types.d.ts +20 -0
  97. package/packages/client/dist/runner/headless/types.js +2 -2
  98. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  99. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  100. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  101. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  102. package/packages/client/dist/yoloop/target-normalization.js +1 -1
  103. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  104. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  105. package/packages/shared/dist/compatibility/index.js +96 -0
  106. package/packages/shared/dist/planning/diagnosis-state.js +105 -1
  107. package/packages/shared/dist/project-memory-targets.js +36 -5
  108. package/targets-stubs/antigravity/README.md +1 -1
  109. package/targets-stubs/antigravity/gemini.md +1 -1
  110. package/targets-stubs/antigravity/install-antigravity.sh +1 -1
  111. package/targets-stubs/antigravity/mcp-config.json +0 -3
  112. package/targets-stubs/antigravity/neocortex.md +25 -13
  113. package/targets-stubs/antigravity/skill/SKILL.md +4 -4
  114. package/targets-stubs/claude-code/.mcp.json +0 -4
  115. package/targets-stubs/claude-code/neocortex-root.agent.yaml +2 -4
  116. package/targets-stubs/claude-code/neocortex-root.md +33 -43
  117. package/targets-stubs/claude-code/neocortex-sentinel.md +261 -0
  118. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -3
  119. package/targets-stubs/claude-code/neocortex.md +61 -84
  120. package/targets-stubs/codex/AGENTS.md +19 -18
  121. package/targets-stubs/codex/README.md +1 -1
  122. package/targets-stubs/codex/config-mcp.toml +0 -3
  123. package/targets-stubs/codex/neocortex-sentinel.toml +87 -0
  124. package/targets-stubs/codex/neocortex.toml +23 -44
  125. package/targets-stubs/cursor/README.md +1 -1
  126. package/targets-stubs/cursor/agent.md +26 -15
  127. package/targets-stubs/cursor/mcp.json +0 -3
  128. package/targets-stubs/deepseek-harness/SKILL.md +11 -8
  129. package/targets-stubs/gemini-cli/README.md +1 -1
  130. package/targets-stubs/gemini-cli/agent.md +25 -12
  131. package/targets-stubs/gemini-cli/agents/neocortex-sentinel.md +75 -0
  132. package/targets-stubs/gemini-cli/agents/neocortex.md +280 -49
  133. package/targets-stubs/gemini-cli/settings-mcp.json +0 -3
  134. package/targets-stubs/grok/SKILL.md +13 -1
  135. package/targets-stubs/grok/agents/neocortex-sentinel.md +64 -0
  136. package/targets-stubs/grok/config-mcp.toml +0 -3
  137. package/targets-stubs/grok/install-grok.sh +51 -1
  138. package/targets-stubs/kimi/mcp.json +0 -6
  139. package/targets-stubs/kimi/neocortex.md +21 -8
  140. package/targets-stubs/lib/managed-config-merge.js +301 -6
  141. package/targets-stubs/lib/managed-profile.sh +12 -1
  142. package/targets-stubs/lib/mcp-merge.js +122 -8
  143. package/targets-stubs/openclaw/SKILL.md +33 -4
  144. package/targets-stubs/opencode/neocortex-root.md +41 -41
  145. package/targets-stubs/opencode/neocortex-sentinel.md +115 -0
  146. package/targets-stubs/opencode/neocortex.md +292 -67
  147. package/targets-stubs/opencode/opencode-mcp.json +0 -7
  148. package/targets-stubs/vscode/README.md +1 -1
  149. package/targets-stubs/vscode/mcp.json +0 -4
  150. package/targets-stubs/vscode/neocortex.agent.md +29 -18
@@ -1 +1 @@
1
- import{promises as O}from"node:fs";import{existsSync as S}from"node:fs";import{createHash as R}from"node:crypto";import{join as w,dirname as X}from"node:path";import{hostname as f}from"node:os";import{setSecureFilePermissions as G,setSecureDirPermissions as Z}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as x}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as k,epicOperationalCanonicalJson as Y,epicOperationalHash as E,mutateEpicOperationalState as Q,readEpicOperationalState as H}from"../git/epic-operational-state.js";const ee=".neocortex",U="yoloop-state.json",te="yoloop.lock",ne="yoloop-state.mutation.lock",D="yoloop-session-rollover.json",F="yoloop-successor-transition.json",K=360*60*1e3,se=3e4,oe=200,M=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),re={warn:()=>{},info:()=>{},error:()=>{}};function T(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 Ae(t){return{lock:null,state:T(t),capabilities:M}}class Pe{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=re){this.projectRoot=e,this.stateDir=w(e,ee),this.statePath=w(this.stateDir,U),this.lockPath=w(this.stateDir,te),this.mutationLockPath=w(this.stateDir,ne),this.rolloverManifestPath=w(this.stateDir,D),this.successorTransitionManifestPath=w(this.stateDir,F),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:M}}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 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 c=(await this.readState(o)).runControl;if(!c)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${a}`,d=n.idempotencyKey??`idem-${e}-${a}`,h=c.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(h){if(h.operationId===i&&h.idempotencyKey===d)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=_e(c.status,e);if(!u)throw new Error(L.has(c.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(Ie({current:c,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 k(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=H(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"&&!S(w(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 k(this.projectRoot,e);return}const{document:s,operational:o}=H(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const c=r[0];await Q(this.projectRoot,{identityHash:c,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},a=>{const i=a.yoloop.state;let d=a.yoloop.lock,h=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:f(),ownerKind:"client",leaseId:e.lock.leaseId??J(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??K,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;h={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;h={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),_=u.find(I=>I.idempotencyKey===p);if(_){if(Y(_)!==Y(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");h={...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 _=i.continuationReceipts??[];if(_.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");h={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[..._,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||E("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");h={...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");h={...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");h={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":h={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":h=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(E("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||E("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(_=>_.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");h={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":h={...i,recovery_history:P([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(_=>_.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),h={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}a.yoloop={...a.yoloop,lock:d,state:h}})}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 c=o.find(a=>a.idempotencyKey===r);if(c){if(l(c)===l(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??[],c=r.findIndex(h=>h.idempotencyKey===e);if(c<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=r[c];if(n.idempotencyKey!==e||n.sessionId!==a.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((h,u)=>u!==c),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),c=r.pendingContinuationAuthorities??[],a=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=a.find(p=>p.idempotencyKey===i);if(d){if(l(d)===l(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(c.length!==1||y("p208-legacy-authority-before-v1",c[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=y("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||y("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...a.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 O.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 O.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:S(this.lockPath),rolloverManifestPresent:S(this.rolloverManifestPath),successorTransitionManifestPresent:S(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await O.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(R("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(S(this.lockPath)||S(this.rolloverManifestPath)||S(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:R("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await O.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await O.rename(s,e),await this.syncStateDirectory()}catch(o){throw await O.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...c}=e;if(ie(c)!==e.payloadHash||!b(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const a={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:y("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===y("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(l(e.receipt)!==l(a))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 h=i.continuationReplanReceipts??[],u=h.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(l(u)===l(a)&&l(i.continuationSession)===l(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,_=i.pendingContinuationAuthorities??[];if(!b(p)||y("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||y("p222-yoloop-replan-pending-v1",_)!==e.expectedPendingHash||_.length>1||_.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:[...h.slice(-63),a]})}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 c=P([...o,e]),a={...s,recovery_history:c};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:c.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],c=r.findIndex(h=>h.recovery_step_id_tokenized===e);if(c===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=r[c];if(a.outcome===n&&a.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[c]={...a,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:f(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??J(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??K,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await O.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 c=r;if(c.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:c.message},"failed to acquire yoloop lock"),r;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,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 O.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await O.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 O.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 O.readFile(this.statePath,"utf8"),s=JSON.parse(n);return fe(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"),T(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await O.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await O.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 O.unlink(n)}catch{}throw o}}async rolloverSession(e,n){v(e);const s=await this.readRolloverManifest();if(s){if(Oe(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();q(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=l(s)===l(e.next);if(!o){const c=await this.readLock();q(e,s,c),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 O.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 O.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 O.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 v(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 O.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 O.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){C(e);const s=await this.readSuccessorTransitionManifest();if(s){if(ue(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(N(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}V(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(!N(e,s)){l(s.runControl)===l(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=pe(e,s);await this.writeState(r),s=await this.readState(n)}if(!N(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 O.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 O.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 C(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 O.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 O.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 O.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 O.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<oe;s+=1)try{n=await O.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 O.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>se){await O.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 O.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){m(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");A(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){$(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},c=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(c){if(c.operationId===e.operationId&&c.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===c.payloadHash&&l(o?.predecessor)===l(r))return c;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 a=e.next.receipts.at(-1);if(!a||l(e.next.predecessor)!==l(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:a.payloadHash,next:e.next};return m(i),A(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{G(e)}catch{}}trySetDirPerms(e){try{Z(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=z(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!==f())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(z(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!==f())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 O.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===f()}async cleanupOrphanTempFiles(){try{const e=X(this.statePath),n=await O.readdir(e),s=[`${U}.tmp.`,`${D}.tmp.`,`${F}.tmp.`],o=n.filter(r=>s.some(c=>r.startsWith(c)));for(const r of o)try{await O.unlink(w(e,r))}catch{}}catch{}}}function l(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(l).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${l(n)}`).join(",")}}`}function y(t,e){return R("sha256").update(`${t}\0${l(e)}`).digest("hex")}function ie(t){return y("p222-yoloop-continuation-replan-v1",t)}function b(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===y("p205-yoloop-session-v1",n)}function ae(t){return y("p9390812898200217364-yoloop-session-v1",t)}function ce(t){return y("p9390812898200217364-yoloop-rollover-v1",t)}function de(t){return y("p9390812898200217364-yoloop-successor-run-v1",t)}function le(t){return y("p9046281030721413419-yoloop-successor-transition-v1",t)}function ue(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function C(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;$(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!==le(n)||Buffer.byteLength(l(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 V(t,e){if(C(t),!(l(e.runControl)===l(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")}he(t,e)}function he(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||l(o.receipt.storyIds)!==l(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const h=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(l(t.state.pendingContinuationAuthorities??[])!==l(h)||l(t.state.continuationReceipts??[])!==l(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(l(t.state.pendingContinuationAuthorities??[])!==l(n)||l(t.state.continuationReceipts??[])!==l(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const c=String(r.idempotencyKey??""),a=t.state.pendingContinuationAuthorities??[],i=a.find(d=>d.idempotencyKey===c);if(i&&l(i)!==l(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&a.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function pe(t,e){V(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 N(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 l(e)===l(o)}function Oe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function v(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!==ce(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 $(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!==de(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function q(t,e,n){v(t);const s=e.currentSession;if(!s||ae(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(l(r)!==l(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=r.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:a.payloadHash,next:r};m(i),A(o,i)}else{const a=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||a?.runId!==t.runId||a.revision!==1||a.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 c={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(l(c)!==l(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function B(t){const{receipts:e,...n}=t.next;return y("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const L=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ye={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 _e(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:L.has(t)||t==="cancelling"?null:"cancelling"}function Ie(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=y("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),c={...o,snapshotId:r,snapshotHash:y("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},a={...o,sequence:c.sequence+1,phase:"after",status:t.target,parentSnapshotHash:c.snapshotHash},i=y("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),d={...a,snapshotId:i,snapshotHash:y("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:i})},h={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=y("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),p={...h,eventId:u,eventHash:y("p220-yoloop-run-event-v1",{...h,eventId:u})},_={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,c,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:_},g=B(I),W={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:g,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:g,next:{..._,receipts:[..._.receipts,W]}}}function m(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!==B(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function A(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||l(n.events.slice(0,s.length))!==l(s)||l(n.progressSnapshots.slice(0,o.length))!==l(o)||l(n.receipts.slice(0,r.length))!==l(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(L.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(h==="budget"||h==="retry");if(!(ye[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(l(t.predecessor)!==l(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=n.progressSnapshots.at(-2),a=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!c||!a||!i||!d||c.phase!=="before"||a.phase!=="after"||c.operationId!==e.operationId||a.operationId!==e.operationId||i.operationId!==e.operationId||c.runId!==e.runId||a.runId!==e.runId||i.runId!==e.runId||c.revision!==n.revision||a.revision!==n.revision||i.revision!==n.revision||c.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==c.snapshotHash||n.latestSnapshotHash!==a.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");j(c),j(a),we(i,s.at(-1)?.eventHash??null)}function j(t){const{snapshotHash:e,...n}=t;if(e!==y("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function we(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==y("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function J(t,e){return`lease-${Se(`${t}:${e}`)}`}function Se(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 z(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 fe(t,e){const n=T(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)?P(t.recovery_history):[]}}function P(t){return t.length<=x?t:t.slice(t.length-x)}export{M as YOLOOP_PERSISTENCE_CAPABILITIES,Pe as YoloopClientStateStore,ie as buildYoloopContinuationReplanPayloadHash,B as buildYoloopRunTransitionPayloadHash,ce as buildYoloopSessionRolloverPayloadHash,de as buildYoloopSuccessorRunPayloadHash,le as buildYoloopSuccessorTransitionPayloadHash,P as capRecoveryHistory,T as createDefaultCounters,Ae as createDefaultState,ae as fingerprintYoloopSession};
1
+ import{promises as y}from"node:fs";import{existsSync as E}from"node:fs";import{createHash as A}from"node:crypto";import{join as R,dirname as he}from"node:path";import{hostname as C}from"node:os";import{setSecureFilePermissions as pe,setSecureDirPermissions as ye}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as j}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as q,epicOperationalCanonicalJson as m,epicOperationalHash as v,mutateEpicOperationalState as B,readEpicOperationalState as P}from"../git/epic-operational-state.js";import{yoloopDomainHash as Oe}from"../../../shared/dist/yoloop/canonical.js";const _e=".neocortex",z="yoloop-state.json",Ie="yoloop.lock",fe="yoloop-state.mutation.lock",J="yoloop-session-rollover.json",G="yoloop-successor-transition.json",W=360*60*1e3,we=3e4,Se=200,X=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),Re={warn:()=>{},info:()=>{},error:()=>{}};function x(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function nt(t){return{lock:null,state:x(t),capabilities:X}}class st{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Re){this.projectRoot=e,this.stateDir=R(e,_e),this.statePath=R(this.stateDir,z),this.lockPath=R(this.stateDir,Ie),this.mutationLockPath=R(this.stateDir,fe),this.rolloverManifestPath=R(this.stateDir,J),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s)return{lock:s.yoloop.lock,state:s.yoloop.state,capabilities:s.yoloop.capabilities};await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[o,r]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(o,n),state:r,capabilities:X}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const o of e.operations)await this.applyCommonOperation(o,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!le(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const o=r=>{const a=(r.pendingContinuationAuthorities??[]).find(l=>l.idempotencyKey===e.idempotencyKey);if(!a)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c={sessionId:String(a.sessionId??""),idempotencyKey:e.idempotencyKey,storyIds:Array.isArray(a.storyIds)?a.storyIds.map(String):[]};if(!le(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.continuationReceipts??[],d=i.find(l=>qe(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(m(d)===m(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...r,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:r,operational:a}=P(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return o(a.yoloop.state)==="unchanged"?"unchanged":(await B(this.projectRoot,{identityHash:c[0],expectedRevision:r.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=o(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const r=o(await this.readState(s));return r==="unchanged"?"unchanged":(await this.writeState(r),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(o)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,l=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(l){if(l.operationId===i&&l.idempotencyKey===d)return l;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=xe(a.status,e);if(!u)throw new Error(U.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ke({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await q(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=P(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!E(R(this.projectRoot,".git")))return null;throw e}}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await q(this.projectRoot,e);return}const{document:s,operational:o}=P(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const a=r[0];await B(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d&&d.sessionId!==e.lock.sessionId)throw new Error("YOLOOP_LOCK_HELD");d={...e.lock,pid:process.pid,hostname:C(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??W,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;l={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;l={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=u.find(I=>I.idempotencyKey===p);if(O){if(m(O)!==m(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const O=i.continuationReceipts??[];if(O.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||v("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");l={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");l={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":l={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":l=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(v("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||v("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(O=>O.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":l={...i,recovery_history:F([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),l={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}c.yoloop={...c.yoloop,lock:d,state:l}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=o.find(c=>c.idempotencyKey===r);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],a=r.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=r[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((l,u)=>u!==a),d=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),a=r.pendingContinuationAuthorities??[],c=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||_("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const l=_("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==l)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||_("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:E(this.lockPath),rolloverManifestPresent:E(this.rolloverManifestPath),successorTransitionManifestPresent:E(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(A("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(E(this.lockPath)||E(this.rolloverManifestPath)||E(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:A("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await y.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(o){throw await y.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...a}=e;if(Ee(a)!==e.payloadHash||!Z(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const c={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:_("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===_("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(h(e.receipt)!==h(c))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const l=i.continuationReplanReceipts??[],u=l.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(h(u)===h(c)&&h(i.continuationSession)===h(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,O=i.pendingContinuationAuthorities??[];if(!Z(p)||_("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||_("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...l.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=F([...o,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],a=r.findIndex(l=>l.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=r[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[a]={...c,outcome:n,finished_at:s};const d={...o,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:C(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??W,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await y.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const a=r;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),r;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Ue(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),x(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await y.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw o}}async rolloverSession(e,n){H(e);const s=await this.readRolloverManifest();if(s){if(ve(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();te(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=h(s)===h(e.next);if(!o){const a=await this.readLock();te(e,s,a),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return H(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){k(e);const s=await this.readSuccessorTransitionManifest();if(s){if(Le(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(n);if(Y(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}Q(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!Y(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=Ae(e,s);await this.writeState(r),s=await this.readState(n)}if(!Y(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await y.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await y.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return k(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Se;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await y.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>we){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){D(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");K(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){ee(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(o?.predecessor)===h(r))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return D(i),K(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{pe(e)}catch{}}trySetDirPerms(e){try{ye(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=re(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==C())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(re(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==C())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await y.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===C()}async cleanupOrphanTempFiles(){try{const e=he(this.statePath),n=await y.readdir(e),s=[`${z}.tmp.`,`${J}.tmp.`,`${G}.tmp.`],o=n.filter(r=>s.some(a=>r.startsWith(a)));for(const r of o)try{await y.unlink(R(e,r))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function _(t,e){return A("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ee(t){return _("p222-yoloop-continuation-replan-v1",t)}function Z(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===_("p205-yoloop-session-v1",n)}function Ce(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Ne(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function Te(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function me(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function Le(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function k(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;ee(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==me(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||o!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||s!==void 0&&r===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function Q(t,e){if(k(t),!(h(e.runControl)===h(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ge(t,e)}function ge(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],o=t.acknowledgement;if(o){const d=n.find(p=>p.idempotencyKey===o.idempotencyKey);if(!d||o.receipt.sessionId!==d.sessionId||h(o.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(l)||h(t.state.continuationReceipts??[])!==h(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const a=String(r.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Ae(t,e){Q(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function Y(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n);const o={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(o)}function ve(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Ne(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function ee(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==Te(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function te(t,e,n){H(t);const s=e.currentSession;if(!s||Ce(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(h(r)!==h(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=r.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:c.payloadHash,next:r};D(i),K(o,i)}else{const c=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function ne(t){const{receipts:e,...n}=t.next;return _("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const U=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Pe={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function xe(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:U.has(t)||t==="cancelling"?null:"cancelling"}function ke(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=_("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),a={...o,snapshotId:r,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},c={...o,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=_("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},l={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=_("p220-yoloop-run-event-id-v1",{runId:l.runId,operationId:l.operationId,sequence:l.sequence}),p={...l,eventId:u,eventHash:_("p220-yoloop-run-event-v1",{...l,eventId:u})},O={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,a,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},T=ne(I),g={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:T,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:T,next:{...O,receipts:[...O.receipts,g]}}}function D(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==ne(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function K(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,o.length))!==h(o)||h(n.receipts.slice(0,r.length))!==h(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(U.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const l=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(l==="budget"||l==="retry");if(!(Pe[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(h(t.predecessor)!==h(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=n.progressSnapshots.at(-2),c=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!a||!c||!i||!d||a.phase!=="before"||c.phase!=="after"||a.operationId!==e.operationId||c.operationId!==e.operationId||i.operationId!==e.operationId||a.runId!==e.runId||c.runId!==e.runId||i.runId!==e.runId||a.revision!==n.revision||c.revision!==n.revision||i.revision!==n.revision||a.parentSnapshotHash!==(t?.latestSnapshotHash??null)||c.parentSnapshotHash!==a.snapshotHash||n.latestSnapshotHash!==c.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");se(a),se(c),Ye(i,s.at(-1)?.eventHash??null)}function se(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ye(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==_("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function oe(t,e){return`lease-${He(`${t}:${e}`)}`}function He(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function re(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function Ue(t,e){const n=x(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?F(t.recovery_history):[]}}function F(t){return t.length<=j?t:t.slice(t.length-j)}const b=Object.freeze(["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"]),De=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function Ke(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(De.has(n))return 0;const s=b.indexOf(e);return s<0?b.length:b.length-1-s}const M="yoloop-round-refused-before-setup",Fe="neocortex.p230.round-refused-before-setup.v1",ie=64,be=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),Me="reasonCode,storyId",ae=/^[a-z0-9][a-z0-9-]{2,79}$/,Ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,$e=/^[a-f0-9]{64}$/;function L(t){return typeof t=="string"&&Ve.test(t)&&!t.includes("..")}function N(t){return typeof t=="string"&&$e.test(t)}function ce(t){if(!(!Array.isArray(t)||t.length===0||t.length>ie)&&t.every(L)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function de(t){return Oe(Fe,{schemaVersion:t.schemaVersion,kind:t.kind,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:t.storyIds,refusals:t.refusals.map(e=>({storyId:e.storyId,reasonCode:e.reasonCode}))})}function je(t){if(!t||!L(t.epicId)||!N(t.sessionId)||!N(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ie)return;const e=t.refusals.map(o=>({storyId:o?.storyId,reasonCode:o?.reasonCode})).sort((o,r)=>String(o.storyId).localeCompare(String(r.storyId)));if(!e.every(o=>L(o.storyId)&&typeof o.reasonCode=="string"&&ae.test(o.reasonCode)))return;const n=e.map(o=>o.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:M,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(o=>Object.freeze({storyId:o.storyId,reasonCode:o.reasonCode})))};return Object.freeze({...s,digest:de(s)})}function qe(t){return S(t)&&t.kind===M}function le(t,e){if(!S(t)||Object.keys(t).some(p=>!be.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:o,sessionId:r,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==M||!L(o)||!N(r)||!N(a)||!N(d))return!1;const l=ce(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===Me&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&ae.test(p.reasonCode))||d!==de(t))return!1;if(!e)return!0;const u=ce([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&r===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Be="story-round-no-setup-evidence";function ot(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,o=S(s?.expectedTransition)?s.expectedTransition:void 0,r=Array.isArray(o?.storyLifecycle)?o.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!r||r.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const l=new Set(i.map(f=>{const w=S(t.stories[f])?t.stories[f]:void 0;return typeof w?.epic_id=="string"?w.epic_id:f.split(".")[0]}));if(l.size!==1)return;const u=[...l][0],p=S(t.epics[u])?t.epics[u]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],I=S(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,T=Array.isArray(I?.receipts)?I.receipts:[],g=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],ue=f=>O.some(w=>S(w)&&w.storyId===f)||T.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||g.some(w=>S(w)&&w.storyId===f);for(const f of i){if(ue(f))return;const w=r.find($=>S($)&&$.storyId===f),V=S(t.stories[f])?t.stories[f]:void 0;if(!w||!V||!Number.isSafeInteger(w.remaining)||Ke(V.status)!==w.remaining)return}return je({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Be}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{X as YOLOOP_PERSISTENCE_CAPABILITIES,Be as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,M as YOLOOP_ROUND_REFUSED_KIND,st as YoloopClientStateStore,je as buildClientYoloopRoundRefusedReceipt,Ee as buildYoloopContinuationReplanPayloadHash,ne as buildYoloopRunTransitionPayloadHash,Ne as buildYoloopSessionRolloverPayloadHash,Te as buildYoloopSuccessorRunPayloadHash,me as buildYoloopSuccessorTransitionPayloadHash,F as capRecoveryHistory,Ke as clientYoloopStoryLifecycleRemaining,x as createDefaultCounters,nt as createDefaultState,ot as deriveYoloopRoundRefusedBeforeSetupReceipt,Ce as fingerprintYoloopSession,qe as isClientYoloopRoundRefusedRecord,le as isValidClientYoloopRoundRefusedReceipt};
@@ -23,7 +23,103 @@ export const COMPATIBILITY_CAPABILITIES = Object.freeze({
23
23
  * its pre-P227.23 `continuous_dag` plan.
24
24
  */
25
25
  YOLOOP_V4_RUNNER_DISPATCH: 'yoloop-v4-runner-dispatch-v1',
26
+ /**
27
+ * P228.14 (P228-CON-CHILD-CAPABILITY): the client accepts the delegated
28
+ * child `neocortex-sentinel` in task directives. Without it the server keeps
29
+ * the legacy `subagentType: 'neocortex'`.
30
+ */
31
+ AGENT_SENTINEL_CHILD: 'agent-sentinel-child-v1',
32
+ /**
33
+ * P228.14 (P228-CON-SPEC-BARRIER-SCOPE): the client understands v4 plans
34
+ * whose C04 barrier uses `specBarrier.scope: 'frontier'`. Without it the
35
+ * server keeps the legacy `epic` scope.
36
+ */
37
+ YOLOOP_V4_FRONTIER_BARRIER: 'yoloop-v4-frontier-barrier-v1',
38
+ /**
39
+ * P228.18 (ADR-P228-01): the client sends the private-execution envelope
40
+ * with a `hostKind` from {@link PRIVATE_EXECUTION_HOST_KINDS}. Without it the
41
+ * server admits only the legacy Codex envelope.
42
+ */
43
+ PRIVATE_EXECUTION_HOST_NEUTRAL: 'private-execution-host-neutral-v1',
44
+ /**
45
+ * P228.23 (G5): the client can drive the root refactor/QA control from any
46
+ * harness. Replaces the former `platformTarget === 'codex'` host test.
47
+ */
48
+ ROOT_REFACTOR_QA_CONTROL: 'root-refactor-qa-control-v1',
49
+ /**
50
+ * P228.26 (P228-CON-GOVERNANCE-RUNTIME-STORE): the client keeps story
51
+ * governance of untracked `.neocortex/` projects in the Git common-dir
52
+ * runtime store and checkpoints code only. Without it the server keeps the
53
+ * `story-worktree-state-untracked` fallback for such projects.
54
+ */
55
+ STORY_GOVERNANCE_RUNTIME_STORE: 'story-governance-runtime-store-v1',
56
+ });
57
+ /**
58
+ * P228.18: closed host enum for the private-execution envelope, one value per
59
+ * supported harness. Codex keeps its legacy literal `codex-cli`; `runner` and
60
+ * `unknown` are never private-execution hosts. The `satisfies` clause makes a
61
+ * new canonical platform a compile error until its host is decided.
62
+ */
63
+ const PRIVATE_EXECUTION_HOST_BY_PLATFORM = Object.freeze({
64
+ 'claude-code': 'claude-code',
65
+ opencode: 'opencode',
66
+ codex: 'codex-cli',
67
+ gemini: 'gemini',
68
+ vscode: 'vscode',
69
+ 'github-copilot-cli': 'github-copilot-cli',
70
+ kimi: 'kimi',
71
+ cursor: 'cursor',
72
+ antigravity: 'antigravity',
73
+ openclaw: 'openclaw',
74
+ grok: 'grok',
75
+ deepseek: 'deepseek',
26
76
  });
77
+ export const PRIVATE_EXECUTION_HOST_KINDS = Object.freeze(Object.values(PRIVATE_EXECUTION_HOST_BY_PLATFORM));
78
+ export const PRIVATE_EXECUTION_CODEX_HOST_KIND = PRIVATE_EXECUTION_HOST_BY_PLATFORM.codex;
79
+ export function isPrivateExecutionHostKind(value) {
80
+ return typeof value === 'string'
81
+ && PRIVATE_EXECUTION_HOST_KINDS.includes(value);
82
+ }
83
+ /** Maps a canonical platform target to its host; anything else is `undefined`. */
84
+ export function hostKindForPlatformTarget(platformTarget) {
85
+ if (typeof platformTarget !== 'string'
86
+ || !Object.prototype.hasOwnProperty.call(PRIVATE_EXECUTION_HOST_BY_PLATFORM, platformTarget))
87
+ return undefined;
88
+ return PRIVATE_EXECUTION_HOST_BY_PLATFORM[platformTarget];
89
+ }
90
+ /**
91
+ * P229.04 (P229-CON-REFUSAL): stable public reason codes of the private
92
+ * harness executor. They are route/client `error_code` values, deliberately
93
+ * kept outside `COMPATIBILITY_REASON_CODES` (P228.18 DEC-03).
94
+ */
95
+ export const PRIVATE_EXECUTOR_REASON_CODES = Object.freeze({
96
+ HEADLESS_UNAVAILABLE: 'private-executor-headless-unavailable',
97
+ VERSION_UNSUPPORTED: 'private-executor-version-unsupported',
98
+ TIMEOUT: 'private-executor-timeout',
99
+ PROOF_INVALID: 'private-executor-proof-invalid',
100
+ });
101
+ /**
102
+ * P229.04 (P229-CON-ADMISSION): the simple executor proof v7 is the same for
103
+ * every host (ADR-P229-02). Every verification field must be `passed`.
104
+ */
105
+ export const PRIVATE_EXECUTOR_PROOF_V7_FIELDS = Object.freeze([
106
+ 'preflight', 'hostVersion', 'stdinOnly', 'ephemeralHome', 'nativeNoPersistence', 'os',
107
+ ]);
108
+ /** Exact-shape check: no missing, extra or non-`passed` field is accepted. */
109
+ export function isPrivateExecutorProofV7(value) {
110
+ if (!value || typeof value !== 'object' || Array.isArray(value))
111
+ return false;
112
+ const record = value;
113
+ const keys = Object.keys(record);
114
+ return keys.length === PRIVATE_EXECUTOR_PROOF_V7_FIELDS.length + 1
115
+ && record.schemaVersion === 7
116
+ && PRIVATE_EXECUTOR_PROOF_V7_FIELDS.every((field) => Object.prototype.hasOwnProperty.call(record, field) && record[field] === 'passed');
117
+ }
118
+ /** True only for a valid `CompatibilityOffer/1.0` that advertises the capability. */
119
+ export function supportsPrivateExecutionHostNeutral(offer) {
120
+ return isCompatibilityOfferV1(offer)
121
+ && offer.capabilityIds.includes(COMPATIBILITY_CAPABILITIES.PRIVATE_EXECUTION_HOST_NEUTRAL);
122
+ }
27
123
  export const COMPATIBILITY_SCHEMAS = Object.freeze({
28
124
  INVOKE_REQUEST: 'invoke-request/1',
29
125
  INVOKE_RESPONSE: 'invoke-response/1',
@@ -33,9 +33,113 @@ function allowedKeys(value, allowed) {
33
33
  if (Object.keys(value).some((key) => !allowed.includes(key)))
34
34
  throw new Error('planning-unknown-field');
35
35
  }
36
+ /**
37
+ * P228.03 (CON-PB-01): one byte budget for the projected planning checkpoint.
38
+ * All values are UTF-8 bytes of `JSON.stringify`, never UTF-16 lengths. The
39
+ * intake budget is derived from the checkpoint ceiling minus worst-case
40
+ * reserves, so an accepted intake always fits with both receipts.
41
+ */
42
+ export const PLANNING_CHECKPOINT_MAX_BYTES = 32_768;
43
+ /** Envelope plus both receipts' fixed fields with empty summaries (measured 962). */
44
+ export const PLANNING_CHECKPOINT_ENVELOPE_RESERVE_BYTES = 1_024;
45
+ /** Worst UTF-8 size of the 1,024-unit receipt summary (3 bytes per BMP unit). */
46
+ export const PLANNING_RECEIPT_SUMMARY_MAX_BYTES = 3_072;
47
+ /** Worst `degradeAuthorization` with 2 x 32 kebab-case ASCII codes of <= 128 chars. */
48
+ export const PLANNING_DEGRADE_AUTHORIZATION_RESERVE_BYTES = 8_704;
49
+ export const PLANNING_INTAKE_MAX_BYTES = PLANNING_CHECKPOINT_MAX_BYTES
50
+ - PLANNING_CHECKPOINT_ENVELOPE_RESERVE_BYTES
51
+ - 2 * PLANNING_RECEIPT_SUMMARY_MAX_BYTES
52
+ - PLANNING_DEGRADE_AUTHORIZATION_RESERVE_BYTES;
53
+ /** Compatibility floor: every intake accepted before P228.03 stays acceptable. */
54
+ const PLANNING_INTAKE_COMPAT_FLOOR_BYTES = 16_384;
55
+ if (PLANNING_INTAKE_MAX_BYTES < PLANNING_INTAKE_COMPAT_FLOOR_BYTES) {
56
+ throw new Error('planning-budget-constants-invalid');
57
+ }
58
+ /** Typed P01 refusal; carries integer counts only, never intake content. */
59
+ export class PlanningIntakeBudgetError extends Error {
60
+ byteLength;
61
+ targetBytes;
62
+ reasonCode = 'planning-intake-budget-exceeded';
63
+ constructor(byteLength, targetBytes) {
64
+ super('planning-intake-budget-exceeded');
65
+ this.byteLength = byteLength;
66
+ this.targetBytes = targetBytes;
67
+ this.name = 'PlanningIntakeBudgetError';
68
+ }
69
+ }
70
+ function collapse(value) {
71
+ return typeof value === 'string' ? value.trim().replace(/\s+/g, ' ') : value;
72
+ }
73
+ /**
74
+ * CON-PB-02: lossless, deterministic and idempotent compaction applied by P01
75
+ * before the revision. `rawIntent` is never touched (P01 binds it to the idea
76
+ * artifact). Unknown keys and non-string values pass through unchanged so the
77
+ * canonical validator still rejects them with its own reason codes.
78
+ */
79
+ export function compactPlanningIntake(value) {
80
+ if (!record(value))
81
+ throw new Error('planning-intake-shape');
82
+ const result = { ...value };
83
+ for (const key of SCALARS) {
84
+ if (key !== 'rawIntent' && result[key] !== undefined)
85
+ result[key] = collapse(result[key]);
86
+ }
87
+ for (const key of LISTS) {
88
+ const entries = result[key];
89
+ if (!Array.isArray(entries))
90
+ continue;
91
+ const seen = new Set();
92
+ const compacted = [];
93
+ for (const entry of entries) {
94
+ const item = collapse(entry);
95
+ if (typeof item === 'string') {
96
+ if (!item || seen.has(item))
97
+ continue;
98
+ seen.add(item);
99
+ }
100
+ compacted.push(item);
101
+ }
102
+ result[key] = compacted;
103
+ }
104
+ for (const key of ['examples', 'contracts']) {
105
+ const entries = result[key];
106
+ if (!Array.isArray(entries))
107
+ continue;
108
+ const seen = new Set();
109
+ const compacted = [];
110
+ for (const entry of entries) {
111
+ if (!record(entry)) {
112
+ compacted.push(entry);
113
+ continue;
114
+ }
115
+ const copy = {};
116
+ for (const [field, item] of Object.entries(entry))
117
+ copy[field] = collapse(item);
118
+ // Structural identity is independent of client key order.
119
+ const identity = JSON.stringify(Object.keys(copy).sort().map((field) => [field, copy[field]]));
120
+ if (seen.has(identity))
121
+ continue;
122
+ seen.add(identity);
123
+ compacted.push(copy);
124
+ }
125
+ result[key] = compacted;
126
+ }
127
+ return result;
128
+ }
129
+ /** P01 entry point: compact, enforce the derived budget, then canonicalize and revise. */
130
+ export function preparePlanningIntake(value) {
131
+ const compacted = compactPlanningIntake(value);
132
+ const byteLength = Buffer.byteLength(JSON.stringify(compacted));
133
+ if (byteLength > PLANNING_INTAKE_MAX_BYTES) {
134
+ throw new PlanningIntakeBudgetError(byteLength, PLANNING_INTAKE_MAX_BYTES);
135
+ }
136
+ const intake = canonicalPlanningIntake(compacted);
137
+ return { intake, intakeRevision: planningIntakeRevision(intake), byteLength,
138
+ compacted: !isDeepStrictEqual(compacted, value) };
139
+ }
36
140
  /** Stable revision input shared by the server and the physical root checkpoint. */
37
141
  export function canonicalPlanningIntake(value) {
38
- if (!record(value) || Buffer.byteLength(JSON.stringify(value)) > 16_384) {
142
+ if (!record(value) || Buffer.byteLength(JSON.stringify(value)) > PLANNING_INTAKE_MAX_BYTES) {
39
143
  throw new Error('planning-intake-shape');
40
144
  }
41
145
  allowedKeys(value, [...SCALARS, ...LISTS, ...BOOLEANS, 'examples', 'contracts']);
@@ -61,7 +61,20 @@ export const PROJECT_MEMORY_TARGET_IDS = [
61
61
  'openclaw',
62
62
  'kimi',
63
63
  'github-copilot-cli',
64
+ 'deepseek',
64
65
  ];
66
+ /**
67
+ * P228.20: native per-story child profiles (`neocortex-sentinel`). The child
68
+ * receives only the server-authored per-story prompt, so these paths are never
69
+ * memory wrappers: no target lists them as primary or secondary file. The
70
+ * orchestrator `neocortex` and the alias `neocortex-root` keep their wrappers.
71
+ */
72
+ export const PROJECT_MEMORY_CHILD_PROFILE_PATHS = Object.freeze([
73
+ '.claude/agents/neocortex-sentinel.md',
74
+ '.gemini/agents/neocortex-sentinel.md',
75
+ '.opencode/agents/neocortex-sentinel.md',
76
+ '.codex/agents/neocortex-sentinel.toml',
77
+ ]);
65
78
  export const PROJECT_MEMORY_TARGETS = {
66
79
  canonical: {
67
80
  targetId: 'canonical',
@@ -83,7 +96,8 @@ export const PROJECT_MEMORY_TARGETS = {
83
96
  canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
84
97
  primaryFile: 'CLAUDE.md',
85
98
  // .claude/agents/ is the subagent discovery directory; a memory wrapper there
86
- // shadows the real `neocortex` agent, so CLAUDE.md is the only wrapper.
99
+ // shadows the orchestrator `neocortex`, the alias `neocortex-root` or the
100
+ // child `neocortex-sentinel`, so CLAUDE.md is the only wrapper.
87
101
  secondaryFiles: projectFileRefs(),
88
102
  ownedBlockName: 'NEOCORTEX-MEMORY',
89
103
  templateKind: 'claude-md',
@@ -98,6 +112,7 @@ export const PROJECT_MEMORY_TARGETS = {
98
112
  platformName: 'Codex CLI',
99
113
  canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
100
114
  primaryFile: 'AGENTS.md',
115
+ // Orchestrator profile; the child neocortex-sentinel.toml gets no memory.
101
116
  secondaryFiles: projectFileRefs('.codex/agents/neocortex.toml'),
102
117
  ownedBlockName: 'NEOCORTEX-MEMORY',
103
118
  templateKind: 'agents-md',
@@ -126,8 +141,8 @@ export const PROJECT_MEMORY_TARGETS = {
126
141
  platformName: 'Gemini CLI',
127
142
  canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
128
143
  primaryFile: 'GEMINI.md',
129
- // .gemini/agents/neocortex.md is the native subagent written by the installer;
130
- // GEMINI.md is the only memory wrapper.
144
+ // .gemini/agents/ holds the native agent profiles written by the installer
145
+ // (including the child neocortex-sentinel.md); GEMINI.md is the only memory wrapper.
131
146
  secondaryFiles: projectFileRefs(),
132
147
  ownedBlockName: 'NEOCORTEX-MEMORY',
133
148
  templateKind: 'gemini-md',
@@ -142,8 +157,8 @@ export const PROJECT_MEMORY_TARGETS = {
142
157
  platformName: 'Antigravity',
143
158
  canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
144
159
  primaryFile: 'GEMINI.md',
145
- // .gemini/agents/neocortex.md is the native subagent written by the installer;
146
- // GEMINI.md is the only memory wrapper.
160
+ // .gemini/agents/ holds the native agent profiles written by the installer
161
+ // (including the child neocortex-sentinel.md); GEMINI.md is the only memory wrapper.
147
162
  secondaryFiles: projectFileRefs(),
148
163
  ownedBlockName: 'NEOCORTEX-MEMORY',
149
164
  templateKind: 'gemini-md',
@@ -186,6 +201,8 @@ export const PROJECT_MEMORY_TARGETS = {
186
201
  platformName: 'OpenCode',
187
202
  canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
188
203
  primaryFile: 'AGENTS.md',
204
+ // Orchestrator neocortex.md and alias neocortex-root.md; the child
205
+ // neocortex-sentinel.md gets no memory.
189
206
  secondaryFiles: projectFileRefs('.opencode/AGENTS.md', '.opencode/agents/neocortex-root.md', '.opencode/agents/neocortex.md', '.agent/skills/neocortex/SKILL.md'),
190
207
  ownedBlockName: 'NEOCORTEX-MEMORY',
191
208
  templateKind: 'agents-md',
@@ -237,6 +254,20 @@ export const PROJECT_MEMORY_TARGETS = {
237
254
  requiresWrapperPreservation: true,
238
255
  notes: 'GitHub Copilot CLI or gh alias instructions. Resolve compact memory back to NEOCORTEX.md without copying private prompt bodies.',
239
256
  },
257
+ deepseek: {
258
+ targetId: 'deepseek',
259
+ platformName: 'DeepSeek Harness',
260
+ canonicalSource: CANONICAL_PROJECT_MEMORY_SOURCE,
261
+ primaryFile: '.dsh/skills/neocortex/SKILL.md',
262
+ secondaryFiles: [{ scope: 'user', path: '.dsh/skills/neocortex/SKILL.md' }],
263
+ ownedBlockName: 'NEOCORTEX-MEMORY',
264
+ templateKind: 'agents-md',
265
+ budget: { maxLines: 220, maxBytes: 18_000 },
266
+ linkRequirement: SAFE_INCLUDE_FALLBACK,
267
+ bidirectionalReference: bidirectionalReference(SAFE_INCLUDE_FALLBACK),
268
+ requiresWrapperPreservation: true,
269
+ notes: 'DeepSeek Harness Skill thin-client memory entrypoint (P228.04). Use the project Skill path when --create-project is requested and keep memory content public-safe.',
270
+ },
240
271
  };
241
272
  export function getProjectMemoryTarget(targetId) {
242
273
  return PROJECT_MEMORY_TARGETS[targetId];
@@ -24,7 +24,7 @@ neocortex activate YOUR-LICENSE-KEY # Get yours at https://neocortex.sh/portal/
24
24
  |---|---|
25
25
  | `skill/SKILL.md` | Thin-client skill stub (delegates to neocortex-client) |
26
26
  | `gemini.md` | Thin-client GEMINI.md (no @import directives) |
27
- | `mcp-config.json` | MCP server configuration (Playwright + Context7) |
27
+ | `mcp-config.json` | MCP server configuration (Playwright) |
28
28
 
29
29
  ## How It Works
30
30
 
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.65.1 | OrNexus Team
1
+ # 🧠 Neocortex v4.66.1 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -15,7 +15,7 @@ _merge_antigravity_mcp() {
15
15
  echo "[ANTIGRAVITY] ERROR: MCP_MERGE_HELPER_UNAVAILABLE; leaving $dest_file untouched" >&2
16
16
  return 1
17
17
  fi
18
- node "$helper" json "$stub_file" "$dest_file" mcpServers ANTIGRAVITY "playwright,context7,browser_use,figma,shadcn,chrome-devtools"
18
+ node "$helper" json "$stub_file" "$dest_file" mcpServers ANTIGRAVITY "playwright,browser_use,figma,shadcn,chrome-devtools"
19
19
  }
20
20
 
21
21
  install_antigravity() {
@@ -4,9 +4,6 @@
4
4
  "command": "npx",
5
5
  "args": ["-y", "@playwright/mcp@latest"]
6
6
  },
7
- "context7": {
8
- "serverUrl": "https://mcp.context7.com/mcp"
9
- },
10
7
  "browser_use": {
11
8
  "command": "uvx",
12
9
  "args": ["--from", "browser-use[cli]", "browser-use", "--mcp"],