@ornexus/neocortex 4.61.6 → 4.64.0

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 (99) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  3. package/install.ps1 +31 -34
  4. package/install.sh +28 -5
  5. package/package.json +6 -4
  6. package/packages/client/dist/agent/refresh-stubs.d.ts +6 -0
  7. package/packages/client/dist/agent/refresh-stubs.js +2 -2
  8. package/packages/client/dist/agent/update-description.d.ts +8 -1
  9. package/packages/client/dist/agent/update-description.js +2 -1
  10. package/packages/client/dist/commands/invoke.d.ts +24 -0
  11. package/packages/client/dist/commands/invoke.js +73 -73
  12. package/packages/client/dist/commands/refresh-memory.d.ts +10 -0
  13. package/packages/client/dist/commands/refresh-memory.js +5 -3
  14. package/packages/client/dist/errors/frontmatter-diagnostics.d.ts +10 -1
  15. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -1
  16. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +110 -10
  17. package/packages/client/dist/git/direct-yolo-checkpoint.js +3 -4
  18. package/packages/client/dist/git/git-lifecycle-store.d.ts +96 -2
  19. package/packages/client/dist/git/git-lifecycle-store.js +8 -7
  20. package/packages/client/dist/git/legacy-branch-mode-conversion.d.ts +58 -0
  21. package/packages/client/dist/git/legacy-branch-mode-conversion.js +4 -0
  22. package/packages/client/dist/git/release-gate-env.d.ts +23 -0
  23. package/packages/client/dist/git/release-gate-env.js +1 -0
  24. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +24 -0
  25. package/packages/client/dist/git/secure-filesystem-boundary.js +20 -9
  26. package/packages/client/dist/git/state-json-field-merge.d.ts +76 -0
  27. package/packages/client/dist/git/state-json-field-merge.js +2 -0
  28. package/packages/client/dist/git/story-worktree-cleanup.d.ts +22 -1
  29. package/packages/client/dist/git/story-worktree-cleanup.js +4 -4
  30. package/packages/client/dist/git/story-worktree-integration.d.ts +48 -0
  31. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  32. package/packages/client/dist/git/story-worktree-manager.d.ts +57 -0
  33. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  34. package/packages/client/dist/git/story-worktree-paths.d.ts +23 -1
  35. package/packages/client/dist/git/story-worktree-paths.js +1 -1
  36. package/packages/client/dist/git/story-write-set-extension.d.ts +3 -0
  37. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  38. package/packages/client/dist/private-execution/root-memory-writer.js +1 -1
  39. package/packages/client/dist/runner/headless/child-env.d.ts +92 -0
  40. package/packages/client/dist/runner/headless/child-env.js +1 -0
  41. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -11
  42. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +31 -0
  43. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -10
  44. package/packages/client/dist/runner/headless/run-yolo.d.ts +15 -0
  45. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  46. package/packages/client/dist/runner/headless/run-yoloop.d.ts +55 -0
  47. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2
  48. package/packages/client/dist/runner/headless/types.d.ts +9 -1
  49. package/packages/client/dist/runner/headless/types.js +2 -2
  50. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  51. package/packages/client/dist/state/state-json-repair.d.ts +23 -0
  52. package/packages/client/dist/state/state-json-repair.js +4 -3
  53. package/packages/client/dist/yolo/change-evidence-collector.js +1 -1
  54. package/packages/client/dist/yolo/invoke-envelope-capability.d.ts +2 -0
  55. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -1
  56. package/packages/client/dist/yolo/project-manifest-projection-collector.d.ts +28 -0
  57. package/packages/client/dist/yolo/project-manifest-projection-collector.js +1 -0
  58. package/packages/client/dist/yolo/spec-envelope-collector.d.ts +9 -0
  59. package/packages/client/dist/yolo/spec-envelope-collector.js +3 -3
  60. package/packages/client/dist/yoloop/discovery-hook.d.ts +2 -0
  61. package/packages/client/dist/yoloop/discovery-hook.js +2 -2
  62. package/packages/client/dist/yoloop/invoke-hooks.d.ts +17 -0
  63. package/packages/client/dist/yoloop/invoke-hooks.js +14 -10
  64. package/packages/client/dist/yoloop/legacy-story-scope.d.ts +23 -0
  65. package/packages/client/dist/yoloop/legacy-story-scope.js +1 -0
  66. package/packages/client/dist/yoloop/legacy-yoloop-adoption.d.ts +69 -0
  67. package/packages/client/dist/yoloop/legacy-yoloop-adoption.js +1 -0
  68. package/packages/client/dist/yoloop/shared-discover-epics.d.ts +62 -1
  69. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1
  70. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +23 -0
  71. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  72. package/packages/client/dist/yoloop/yoloop-start-origin-binding.d.ts +92 -0
  73. package/packages/client/dist/yoloop/yoloop-start-origin-binding.js +1 -0
  74. package/packages/shared/dist/compatibility/index.js +6 -0
  75. package/packages/shared/dist/frontmatter-context-contract.js +164 -52
  76. package/packages/shared/dist/project-manifest-projection.js +202 -0
  77. package/packages/shared/dist/project-validation-commands.js +14 -6
  78. package/packages/shared/dist/release-gate-env-contract.js +129 -0
  79. package/packages/shared/dist/yolo/spec-envelope-rules.js +85 -0
  80. package/packages/shared/dist/yolo/spec-envelope.js +33 -7
  81. package/packages/shared/dist/yoloop/branch-unit.js +119 -3
  82. package/packages/shared/dist/yoloop/epic-terminal-git.js +98 -6
  83. package/packages/shared/dist/yoloop/story-write-scope.js +212 -0
  84. package/targets-stubs/antigravity/gemini.md +1 -1
  85. package/targets-stubs/antigravity/install-antigravity.sh +13 -4
  86. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  87. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  88. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  89. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  90. package/targets-stubs/claude-code/neocortex.md +5 -5
  91. package/targets-stubs/codex/AGENTS.md +1 -1
  92. package/targets-stubs/codex/install-codex.sh +12 -4
  93. package/targets-stubs/cursor/agent.md +2 -2
  94. package/targets-stubs/gemini-cli/agent.md +2 -2
  95. package/targets-stubs/lib/managed-config-merge.js +459 -5
  96. package/targets-stubs/lib/managed-profile.sh +54 -7
  97. package/targets-stubs/opencode/neocortex-root.md +1 -1
  98. package/targets-stubs/vscode/install-vscode.sh +21 -0
  99. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1 @@
1
- import{promises as O}from"node:fs";import{existsSync as z}from"node:fs";import{createHash as X}from"node:crypto";import{join as S,dirname as W}from"node:path";import{hostname as w}from"node:os";import{setSecureFilePermissions as G,setSecureDirPermissions as Z}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as A}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as P,epicOperationalCanonicalJson as x,epicOperationalHash as f,mutateEpicOperationalState as Q,readEpicOperationalState as k}from"../git/epic-operational-state.js";const ee=".neocortex",Y="yoloop-state.json",te="yoloop.lock",ne="yoloop-state.mutation.lock",H="yoloop-session-rollover.json",U="yoloop-successor-transition.json",D=360*60*1e3,se=3e4,oe=200,F=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),re={warn:()=>{},info:()=>{},error:()=>{}};function R(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 ge(t){return{lock:null,state:R(t),capabilities:F}}class Ae{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=re){this.projectRoot=e,this.stateDir=S(e,ee),this.statePath=S(this.stateDir,Y),this.lockPath=S(this.stateDir,te),this.mutationLockPath=S(this.stateDir,ne),this.rolloverManifestPath=S(this.stateDir,H),this.successorTransitionManifestPath=S(this.stateDir,U),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:F}}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(N.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 P(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=k(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"&&!z(S(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 P(this.projectRoot,e);return}const{document:s,operational:o}=k(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:w(),ownerKind:"client",leaseId:e.lock.leaseId??j(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??D,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(x(_)!==x(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||f("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(f("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||f("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:m([...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})}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...c}=e;if(ie(c)!==e.payloadHash||!K(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(!K(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=m([...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:w(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??j(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??D,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"),R(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){C(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();V(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();V(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 C(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){E(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(T(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}M(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(!T(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(!T(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 E(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){v(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");L(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){b(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 v(i),L(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=B(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!==w())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(B(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==w())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===w()}async cleanupOrphanTempFiles(){try{const e=W(this.statePath),n=await O.readdir(e),s=[`${Y}.tmp.`,`${H}.tmp.`,`${U}.tmp.`],o=n.filter(r=>s.some(c=>r.startsWith(c)));for(const r of o)try{await O.unlink(S(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 X("sha256").update(`${t}\0${l(e)}`).digest("hex")}function ie(t){return y("p222-yoloop-continuation-replan-v1",t)}function K(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 E(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;b(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 M(t,e){if(E(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){M(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 T(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 C(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 b(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 V(t,e,n){C(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};v(i),L(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 $(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 N=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:N.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=$(I),J={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,J]}}}function v(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!==$(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function L(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(N.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");q(c),q(a),Se(i,s.at(-1)?.eventHash??null)}function q(t){const{snapshotHash:e,...n}=t;if(e!==y("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Se(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-${we(`${t}:${e}`)}`}function we(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function B(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function fe(t,e){const n=R(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?m(t.recovery_history):[]}}function m(t){return t.length<=A?t:t.slice(t.length-A)}export{F as YOLOOP_PERSISTENCE_CAPABILITIES,Ae as YoloopClientStateStore,ie as buildYoloopContinuationReplanPayloadHash,$ as buildYoloopRunTransitionPayloadHash,ce as buildYoloopSessionRolloverPayloadHash,de as buildYoloopSuccessorRunPayloadHash,le as buildYoloopSuccessorTransitionPayloadHash,m as capRecoveryHistory,R as createDefaultCounters,ge as createDefaultState,ae as fingerprintYoloopSession};
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};
@@ -0,0 +1,92 @@
1
+ /**
2
+ * `*yoloop` start adaptations entry point, run before the state snapshot is
3
+ * projected. The P227.16 legacy policy adoption (`legacy-yoloop-adoption.ts`)
4
+ * runs separately in `readYoloopForRequest`.
5
+ *
6
+ * P227.21 (P227-REQ-11, P227-CON-V4-BASE): for the resolved target epic,
7
+ * (1) one bounded fetch of the recorded origin when needed, (2) the P227.20
8
+ * legacy branch-mode conversion (DEC-15), then (3) the root capture of the
9
+ * epic `origin_binding`, without a story lease or story progress, so the
10
+ * first plan can already be v4. Git and runtime CAS logic lives in
11
+ * `direct-yolo-checkpoint.ts` and `legacy-branch-mode-conversion.ts`; this
12
+ * module only orders the steps and shapes public receipts.
13
+ */
14
+ import { type OriginBindingStartReceipt } from '../git/direct-yolo-checkpoint.js';
15
+ import { type LegacyBranchModeConversionPrProvider } from '../git/legacy-branch-mode-conversion.js';
16
+ export type { OriginBindingStartReceipt } from '../git/direct-yolo-checkpoint.js';
17
+ export interface YoloopStartTarget {
18
+ readonly epicId: string;
19
+ readonly source: 'explicit' | 'persisted';
20
+ }
21
+ /**
22
+ * P227.21 DEC-04: the target epic is the explicit `@docs/epics/epic-<ID>.md`
23
+ * of the args; otherwise the persisted yoloop `currentEpicId`. Several
24
+ * explicit epic targets, or none, are ambiguous.
25
+ */
26
+ export declare function resolveYoloopStartTarget(args: string, persistedCurrentEpicId?: unknown): YoloopStartTarget | undefined;
27
+ export declare function resolveYoloopStartTargetEpic(args: string, persistedCurrentEpicId?: unknown): string | undefined;
28
+ /** P227.21 DEC-15: public-safe outcome of the start branch-mode conversion (reason codes and digests only). */
29
+ export interface BranchModeConversionStartReceipt {
30
+ readonly schemaVersion: 1;
31
+ readonly kind: 'branch-mode-conversion-start';
32
+ readonly epicId: string;
33
+ readonly outcome: 'converted' | 'already-converted' | 'not-required' | 'refused';
34
+ readonly reasonCode?: string;
35
+ readonly receiptDigest?: string;
36
+ readonly attempts: number;
37
+ }
38
+ export interface YoloopStartAdaptationOptions {
39
+ readonly projectRoot: string;
40
+ readonly epicId: string;
41
+ readonly nowIso?: string;
42
+ /** Test seams forwarded to P227.20; production uses its `gh` provider and origin URL. */
43
+ readonly prProvider?: LegacyBranchModeConversionPrProvider;
44
+ readonly repository?: string;
45
+ }
46
+ /**
47
+ * P227.21 DEC-15 (closes DEC-14): run P227.20's legacy branch-mode conversion
48
+ * for one epic. Only a `convert` plan is applied, immediately after planning;
49
+ * a git/state race re-plans once. `already-converted` and `not-required` are
50
+ * no-ops. Writer-lease, open-PR and integration proofs stay inside P227.20;
51
+ * every refusal is returned as a reason code and never throws.
52
+ */
53
+ export declare function runYoloopStartBranchModeConversion(options: YoloopStartAdaptationOptions): Promise<BranchModeConversionStartReceipt>;
54
+ export interface YoloopStartAdaptationsResult {
55
+ readonly epicId?: string;
56
+ readonly branchModeConversion?: BranchModeConversionStartReceipt;
57
+ readonly originBinding: OriginBindingStartReceipt;
58
+ /** Number of origin fetches this start performed (0 or 1). */
59
+ readonly fetches: number;
60
+ }
61
+ /**
62
+ * P227.21 R8 + DEC-15 + C11 F2/F5/F6/F8: the start adaptations for the
63
+ * resolved target epic, in order:
64
+ * - target: explicit epic file, else a non-terminal persisted current epic;
65
+ * - one bounded fetch, only when a conversion or a capture needs fresh refs
66
+ * (an epic that is already epic-mode and bound fetches nothing, AC4);
67
+ * - conversion: an unset mode that resolves to epic with no legacy evidence is
68
+ * `not-required` (no tracked write); a conversion candidate never plans
69
+ * against refs that the fetch could not refresh;
70
+ * - origin binding, reusing the same fetch result.
71
+ */
72
+ export declare function runYoloopStartAdaptations(options: {
73
+ readonly args: string;
74
+ readonly projectRoot: string;
75
+ readonly persistedCurrentEpicId?: unknown;
76
+ readonly nowIso?: string;
77
+ readonly fetchTimeoutMs?: number;
78
+ readonly prProvider?: LegacyBranchModeConversionPrProvider;
79
+ readonly repository?: string;
80
+ }): Promise<YoloopStartAdaptationsResult>;
81
+ /**
82
+ * P227.21 R1-R8: binding-only start capture for the target epic. Never
83
+ * throws; every failure is a `refused` receipt so `*yoloop` keeps running on
84
+ * the existing `story-worktree-base-unverified` fallback (DEC-06).
85
+ */
86
+ export declare function planYoloopStartOriginBinding(options: {
87
+ readonly args: string;
88
+ readonly projectRoot: string;
89
+ readonly persistedCurrentEpicId?: unknown;
90
+ readonly nowIso?: string;
91
+ readonly fetchTimeoutMs?: number;
92
+ }): Promise<OriginBindingStartReceipt>;
@@ -0,0 +1 @@
1
+ import{captureEpicOriginBindingAtYoloopStart as g,fetchOriginForYoloopStart as h,readYoloopStartEpic as f}from"../git/direct-yolo-checkpoint.js";import{applyLegacyBranchModeConversion as l,LegacyBranchModeConversionError as I,planLegacyBranchModeConversion as w}from"../git/legacy-branch-mode-conversion.js";const b=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function d(e,r){const t=[...e.matchAll(/(?:^|\s)@?(?:\.\/)?docs\/epics\/epic-([A-Za-z][A-Za-z0-9_-]{0,63})\.md(?=\s|$)/g)].map(n=>n[1]),o=[...new Set(t)];if(!(o.length>1))return o.length===1?{epicId:o[0],source:"explicit"}:typeof r=="string"&&b.test(r)?{epicId:r,source:"persisted"}:void 0}function M(e,r){return d(e,r)?.epicId}function a(e,r,t){return Object.freeze({schemaVersion:1,kind:"origin-binding-start",epicId:e,outcome:"refused",reasonCode:r,executionRefCreated:!1,capturedAt:new Date(t&&Number.isFinite(Date.parse(t))?Date.parse(t):Date.now()).toISOString()})}const v=new Set(["branch-mode-conversion-git-raced","branch-mode-conversion-state-raced"]),u=2;async function R(e){const r={schemaVersion:1,kind:"branch-mode-conversion-start",epicId:e.epicId},t=e.nowIso&&Number.isFinite(Date.parse(e.nowIso))?()=>new Date(Date.parse(e.nowIso)):void 0;let o="branch-mode-conversion-internal-error";for(let n=1;n<=u;n+=1)try{const c=await w({projectRoot:e.projectRoot,epicId:e.epicId,...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{},...t?{now:t}:{}});if(c.kind!=="convert")return Object.freeze({...r,outcome:c.kind,attempts:n});const i=l(e.projectRoot,c,t?{now:t}:{});return Object.freeze({...r,outcome:"converted",attempts:n,...i.receipt?{receiptDigest:i.receipt.receiptDigest}:{}})}catch(c){if(o=c instanceof I?c.reasonCode:"branch-mode-conversion-internal-error",!v.has(o)||n===u)return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:n})}return Object.freeze({...r,outcome:"refused",reasonCode:o,attempts:u})}async function S(e){const r=d(e.args,e.persistedCurrentEpicId);if(!r)return{originBinding:a("unknown","origin-binding-start-target-ambiguous",e.nowIso),fetches:0};const{epicId:t}=r,o=await f(e.projectRoot,t);if(!o.exists)return{epicId:t,originBinding:a(t,"origin-binding-start-target-ambiguous",e.nowIso),fetches:0};if(r.source==="persisted"&&o.terminal)return{epicId:t,originBinding:a(t,"origin-binding-start-target-terminal",e.nowIso),fetches:0};const n=o.mode==="not-epic",c=n||!o.bound;let i;c&&o.originBranch&&(i=await h({projectRoot:e.projectRoot,originBranch:o.originBranch,...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}));const p={projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...e.prProvider?{prProvider:e.prProvider}:{},...e.repository?{repository:e.repository}:{}};let s;o.mode==="resolved-epic"?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"not-required",attempts:0}):n&&i&&!i.ok?s=Object.freeze({schemaVersion:1,kind:"branch-mode-conversion-start",epicId:t,outcome:"refused",reasonCode:i.reasonCode,attempts:0}):s=await R(p);const m=await g({projectRoot:e.projectRoot,epicId:t,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{},...i?{originFetch:i}:{}});return{epicId:t,branchModeConversion:s,originBinding:m,fetches:i?1:0}}async function B(e){const r=d(e.args,e.persistedCurrentEpicId);return r?r.source==="persisted"&&(await f(e.projectRoot,r.epicId)).terminal?a(r.epicId,"origin-binding-start-target-terminal",e.nowIso):g({projectRoot:e.projectRoot,epicId:r.epicId,...e.nowIso?{nowIso:e.nowIso}:{},...e.fetchTimeoutMs?{fetchTimeoutMs:e.fetchTimeoutMs}:{}}):a("unknown","origin-binding-start-target-ambiguous",e.nowIso)}export{B as planYoloopStartOriginBinding,d as resolveYoloopStartTarget,M as resolveYoloopStartTargetEpic,S as runYoloopStartAdaptations,R as runYoloopStartBranchModeConversion};
@@ -17,6 +17,12 @@ export const COMPATIBILITY_CAPABILITIES = Object.freeze({
17
17
  RELEASE_LIFECYCLE: 'release-lifecycle-v1',
18
18
  RELEASE_BLOCKED_TERMINAL: 'release-blocked-terminal-v1',
19
19
  REVIEW_RECONCILIATION: 'review-reconciliation-v1',
20
+ /**
21
+ * P227.23 (H1): the client runner admits and dispatches v4
22
+ * `two_phase_worktree_dag` plans. Without it the server keeps the runner on
23
+ * its pre-P227.23 `continuous_dag` plan.
24
+ */
25
+ YOLOOP_V4_RUNNER_DISPATCH: 'yoloop-v4-runner-dispatch-v1',
20
26
  });
21
27
  export const COMPATIBILITY_SCHEMAS = Object.freeze({
22
28
  INVOKE_REQUEST: 'invoke-request/1',