@ornexus/neocortex 4.66.0 → 4.66.2

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 (94) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1206 -1193
  3. package/docs/install/linux-global-install.md +21 -1
  4. package/install.js +22 -28
  5. package/install.ps1 +19 -24
  6. package/install.sh +26 -30
  7. package/package.json +2 -2
  8. package/packages/client/dist/commands/doctor.d.ts +26 -1
  9. package/packages/client/dist/commands/doctor.js +2 -2
  10. package/packages/client/dist/commands/invoke.d.ts +149 -1
  11. package/packages/client/dist/commands/invoke.js +88 -83
  12. package/packages/client/dist/commands/planning-qa.d.ts +57 -0
  13. package/packages/client/dist/commands/planning-qa.js +1 -1
  14. package/packages/client/dist/commands/story-checkpoint.d.ts +2 -0
  15. package/packages/client/dist/commands/story-checkpoint.js +1 -1
  16. package/packages/client/dist/commands/story-worktree.d.ts +1 -1
  17. package/packages/client/dist/commands/story-worktree.js +1 -1
  18. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +51 -0
  19. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -3
  20. package/packages/client/dist/git/epic-lifecycle-evidence.d.ts +184 -0
  21. package/packages/client/dist/git/epic-lifecycle-evidence.js +6 -0
  22. package/packages/client/dist/git/git-lifecycle-store.d.ts +9 -0
  23. package/packages/client/dist/git/git-lifecycle-store.js +9 -8
  24. package/packages/client/dist/git/story-worktree-cleanup.js +1 -1
  25. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  26. package/packages/client/dist/git/story-worktree-manager.d.ts +39 -0
  27. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  28. package/packages/client/dist/git/story-write-set-extension.d.ts +62 -0
  29. package/packages/client/dist/git/story-write-set-extension.js +1 -1
  30. package/packages/client/dist/private-execution/codex-executor.d.ts +13 -0
  31. package/packages/client/dist/private-execution/codex-executor.js +4 -4
  32. package/packages/client/dist/private-execution/harness-adapters/antigravity.d.ts +9 -0
  33. package/packages/client/dist/private-execution/harness-adapters/antigravity.js +1 -0
  34. package/packages/client/dist/private-execution/harness-adapters/claude-code.d.ts +8 -0
  35. package/packages/client/dist/private-execution/harness-adapters/claude-code.js +1 -0
  36. package/packages/client/dist/private-execution/harness-adapters/codex.d.ts +7 -0
  37. package/packages/client/dist/private-execution/harness-adapters/codex.js +1 -0
  38. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.d.ts +8 -0
  39. package/packages/client/dist/private-execution/harness-adapters/copilot-cli.js +1 -0
  40. package/packages/client/dist/private-execution/harness-adapters/cursor.d.ts +9 -0
  41. package/packages/client/dist/private-execution/harness-adapters/cursor.js +1 -0
  42. package/packages/client/dist/private-execution/harness-adapters/deepseek.d.ts +9 -0
  43. package/packages/client/dist/private-execution/harness-adapters/deepseek.js +1 -0
  44. package/packages/client/dist/private-execution/harness-adapters/gemini.d.ts +8 -0
  45. package/packages/client/dist/private-execution/harness-adapters/gemini.js +1 -0
  46. package/packages/client/dist/private-execution/harness-adapters/grok.d.ts +9 -0
  47. package/packages/client/dist/private-execution/harness-adapters/grok.js +1 -0
  48. package/packages/client/dist/private-execution/harness-adapters/index.d.ts +73 -0
  49. package/packages/client/dist/private-execution/harness-adapters/index.js +1 -0
  50. package/packages/client/dist/private-execution/harness-adapters/kimi.d.ts +9 -0
  51. package/packages/client/dist/private-execution/harness-adapters/kimi.js +1 -0
  52. package/packages/client/dist/private-execution/harness-adapters/openclaw.d.ts +9 -0
  53. package/packages/client/dist/private-execution/harness-adapters/openclaw.js +1 -0
  54. package/packages/client/dist/private-execution/harness-adapters/opencode.d.ts +7 -0
  55. package/packages/client/dist/private-execution/harness-adapters/opencode.js +1 -0
  56. package/packages/client/dist/private-execution/harness-ephemeral-home.d.ts +19 -0
  57. package/packages/client/dist/private-execution/harness-ephemeral-home.js +1 -0
  58. package/packages/client/dist/private-execution/harness-executor.d.ts +79 -0
  59. package/packages/client/dist/private-execution/harness-executor.js +1 -0
  60. package/packages/client/dist/private-execution/harness-process.d.ts +43 -0
  61. package/packages/client/dist/private-execution/harness-process.js +1 -0
  62. package/packages/client/dist/private-execution/isolated-admission.js +12 -12
  63. package/packages/client/dist/private-execution/isolated-workspace.d.ts +16 -1
  64. package/packages/client/dist/private-execution/isolated-workspace.js +1 -1
  65. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.d.ts +2 -3
  66. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +7 -4
  67. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +1 -22
  68. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +6 -10
  69. package/packages/client/dist/state/project-state-snapshot.d.ts +10 -0
  70. package/packages/client/dist/state/project-state-snapshot.js +1 -1
  71. package/packages/client/dist/state/structural-dag-projection.d.ts +26 -0
  72. package/packages/client/dist/state/structural-dag-projection.js +1 -1
  73. package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +67 -0
  74. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
  75. package/packages/shared/dist/compatibility/index.js +28 -0
  76. package/targets-stubs/antigravity/gemini.md +1 -1
  77. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  78. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  79. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  80. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  81. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  82. package/targets-stubs/claude-code/neocortex.md +2 -2
  83. package/targets-stubs/codex/AGENTS.md +1 -1
  84. package/targets-stubs/cursor/agent.md +2 -2
  85. package/targets-stubs/gemini-cli/agent.md +2 -2
  86. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  87. package/targets-stubs/grok/SKILL.md +3 -3
  88. package/targets-stubs/grok/agents/{neocortex.md → neocortex-sentinel.md} +2 -2
  89. package/targets-stubs/grok/install-grok.sh +45 -8
  90. package/targets-stubs/lib/managed-config-merge.js +21 -1
  91. package/targets-stubs/lib/mcp-merge.js +18 -7
  92. package/targets-stubs/opencode/neocortex-root.md +1 -1
  93. package/targets-stubs/opencode/neocortex.md +1 -1
  94. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -73,6 +73,16 @@ export declare class YoloopClientStateStore {
73
73
  * single atomic filesystem mutation. Next invoke's readAll() reconciles.
74
74
  */
75
75
  applyUpdate(update: YoloopStateUpdate, nowIso?: string): Promise<void>;
76
+ /**
77
+ * P230.01 (P230-CON-CONTINUATION C2): records a closed
78
+ * `yoloop-round-refused-before-setup` receipt next to the continuation
79
+ * receipts. Compare-bound to the single pending authority with the same
80
+ * `idempotencyKey` (same `sessionId` and story set); the authority itself is
81
+ * retired once by the server acknowledgement operation. Identical replays are
82
+ * no-ops; a different receipt for the same key is a conflict. Covers both the
83
+ * common v2 authority and the legacy checkout-local file.
84
+ */
85
+ recordRoundRefusedBeforeSetup(receipt: YoloopRoundRefusedBeforeSetupReceipt, nowIso?: string): Promise<'recorded' | 'unchanged'>;
76
86
  /**
77
87
  * Local typed lifecycle-control API. Server transitions and local
78
88
  * pause/resume/cancel requests share this serialized CAS boundary.
@@ -223,4 +233,61 @@ export declare function buildYoloopRunTransitionPayloadHash(input: {
223
233
  * head). Pure: input is not mutated.
224
234
  */
225
235
  export declare function capRecoveryHistory(history: readonly YoloopRecoveryAttemptRef[]): readonly YoloopRecoveryAttemptRef[];
236
+ /** Mirror of `yoloopStoryLifecycleRemaining` (`shared/src/yoloop/convergence-rank.ts`). */
237
+ export declare function clientYoloopStoryLifecycleRemaining(statusValue: unknown): number;
238
+ export declare const YOLOOP_ROUND_REFUSED_KIND: "yoloop-round-refused-before-setup";
239
+ /** Mirror of `YoloopRoundRefusedBeforeSetupReceipt` (`shared/src/yoloop/superseded-receipt.ts`). */
240
+ export interface YoloopRoundRefusedBeforeSetupReceipt {
241
+ readonly schemaVersion: 1;
242
+ readonly kind: typeof YOLOOP_ROUND_REFUSED_KIND;
243
+ readonly epicId: string;
244
+ readonly sessionId: string;
245
+ readonly idempotencyKey: string;
246
+ readonly storyIds: readonly string[];
247
+ readonly refusals: readonly {
248
+ readonly storyId: string;
249
+ readonly reasonCode: string;
250
+ }[];
251
+ readonly digest: string;
252
+ }
253
+ /** Mirror of `buildYoloopRoundRefusedReceipt`. */
254
+ export declare function buildClientYoloopRoundRefusedReceipt(input: {
255
+ readonly epicId: string;
256
+ readonly sessionId: string;
257
+ readonly idempotencyKey: string;
258
+ readonly refusals: readonly {
259
+ readonly storyId: string;
260
+ readonly reasonCode: string;
261
+ }[];
262
+ }): YoloopRoundRefusedBeforeSetupReceipt | undefined;
263
+ /** Mirror of `isYoloopRoundRefusedRecord`. */
264
+ export declare function isClientYoloopRoundRefusedRecord(value: unknown): boolean;
265
+ /**
266
+ * Mirror of `validateYoloopRoundRefusedReceipt`, reduced to the verdict: the
267
+ * same structural, digest and binding rules; never echoes input values.
268
+ */
269
+ export declare function isValidClientYoloopRoundRefusedReceipt(value: unknown, authority?: {
270
+ readonly sessionId: string;
271
+ readonly idempotencyKey: string;
272
+ readonly storyIds: readonly string[];
273
+ }): boolean;
274
+ /** Public reason code of a story with no setup evidence after its round closed. */
275
+ export declare const YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON: "story-round-no-setup-evidence";
276
+ /**
277
+ * P230.01 (P230-CON-CONTINUATION C2): derives the
278
+ * `yoloop-round-refused-before-setup` receipt at a `*yoloop` re-invocation.
279
+ * The root re-invokes only after every child of the round returned, and a live
280
+ * child holds a story-worktree lease (adopt is its first action), so a round
281
+ * whose stories all lack setup evidence was refused before setup. Returns
282
+ * undefined (fail closed: no receipt, the legacy path applies) unless there is
283
+ * exactly one pending authority with a valid certificate, it was neither
284
+ * acknowledged nor already receipted, and for every story of it: no live lease,
285
+ * no `story-worktree-lease`/`phase-one-receipt` receipt, no spec acceptance and
286
+ * no root lifecycle advance since the authority was issued.
287
+ */
288
+ export declare function deriveYoloopRoundRefusedBeforeSetupReceipt(input: {
289
+ readonly persisted: YoloopPersistedCounters;
290
+ readonly epics: Readonly<Record<string, unknown>>;
291
+ readonly stories: Readonly<Record<string, unknown>>;
292
+ }): YoloopRoundRefusedBeforeSetupReceipt | undefined;
226
293
  export {};
@@ -1 +1 @@
1
- import{promises as O}from"node:fs";import{existsSync as S}from"node:fs";import{createHash as R}from"node:crypto";import{join as w,dirname as X}from"node:path";import{hostname as f}from"node:os";import{setSecureFilePermissions as G,setSecureDirPermissions as Z}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as x}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as k,epicOperationalCanonicalJson as Y,epicOperationalHash as E,mutateEpicOperationalState as Q,readEpicOperationalState as H}from"../git/epic-operational-state.js";const ee=".neocortex",U="yoloop-state.json",te="yoloop.lock",ne="yoloop-state.mutation.lock",D="yoloop-session-rollover.json",F="yoloop-successor-transition.json",K=360*60*1e3,se=3e4,oe=200,M=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),re={warn:()=>{},info:()=>{},error:()=>{}};function T(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function Ae(t){return{lock:null,state:T(t),capabilities:M}}class Pe{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=re){this.projectRoot=e,this.stateDir=w(e,ee),this.statePath=w(this.stateDir,U),this.lockPath=w(this.stateDir,te),this.mutationLockPath=w(this.stateDir,ne),this.rolloverManifestPath=w(this.stateDir,D),this.successorTransitionManifestPath=w(this.stateDir,F),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s)return{lock:s.yoloop.lock,state:s.yoloop.state,capabilities:s.yoloop.capabilities};await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[o,r]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(o,n),state:r,capabilities:M}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const o of e.operations)await this.applyCommonOperation(o,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const c=(await this.readState(o)).runControl;if(!c)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${a}`,d=n.idempotencyKey??`idem-${e}-${a}`,h=c.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(h){if(h.operationId===i&&h.idempotencyKey===d)return h;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=_e(c.status,e);if(!u)throw new Error(L.has(c.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(Ie({current:c,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await k(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=H(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!S(w(this.projectRoot,".git")))return null;throw e}}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await k(this.projectRoot,e);return}const{document:s,operational:o}=H(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const c=r[0];await Q(this.projectRoot,{identityHash:c,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},a=>{const i=a.yoloop.state;let d=a.yoloop.lock,h=i;switch(e.type){case"acquire_lock":{if(d&&d.sessionId!==e.lock.sessionId)throw new Error("YOLOOP_LOCK_HELD");d={...e.lock,pid:process.pid,hostname:f(),ownerKind:"client",leaseId:e.lock.leaseId??J(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??K,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;h={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;h={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),_=u.find(I=>I.idempotencyKey===p);if(_){if(Y(_)!==Y(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");h={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const _=i.continuationReceipts??[];if(_.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");h={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[..._,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||E("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");h={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");h={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");h={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":h={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":h=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(E("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||E("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(_=>_.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");h={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":h={...i,recovery_history:P([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(_=>_.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),h={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}a.yoloop={...a.yoloop,lock:d,state:h}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const c=o.find(a=>a.idempotencyKey===r);if(c){if(l(c)===l(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],c=r.findIndex(h=>h.idempotencyKey===e);if(c<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const a=r[c];if(n.idempotencyKey!==e||n.sessionId!==a.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(a.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((h,u)=>u!==c),d=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),c=r.pendingContinuationAuthorities??[],a=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=a.find(p=>p.idempotencyKey===i);if(d){if(l(d)===l(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(c.length!==1||y("p208-legacy-authority-before-v1",c[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const h=y("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==h)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||y("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...a.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await O.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await O.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:S(this.lockPath),rolloverManifestPresent:S(this.rolloverManifestPath),successorTransitionManifestPresent:S(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await O.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(R("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(S(this.lockPath)||S(this.rolloverManifestPath)||S(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:R("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await O.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await O.rename(s,e),await this.syncStateDirectory()}catch(o){throw await O.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...c}=e;if(ie(c)!==e.payloadHash||!b(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const a={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:y("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===y("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(l(e.receipt)!==l(a))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const h=i.continuationReplanReceipts??[],u=h.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(l(u)===l(a)&&l(i.continuationSession)===l(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,_=i.pendingContinuationAuthorities??[];if(!b(p)||y("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||y("p222-yoloop-replan-pending-v1",_)!==e.expectedPendingHash||_.length>1||_.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...h.slice(-63),a]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const c=P([...o,e]),a={...s,recovery_history:c};await this.writeState(a),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:c.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],c=r.findIndex(h=>h.recovery_step_id_tokenized===e);if(c===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const a=r[c];if(a.outcome===n&&a.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[c]={...a,outcome:n,finished_at:s};const d={...o,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:f(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??J(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??K,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await O.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const c=r;if(c.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:c.message},"failed to acquire yoloop lock"),r;const a=await this.readLock();if(a&&this.isSameClientSessionLock(a,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const d=await O.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await O.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await O.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await O.readFile(this.statePath,"utf8"),s=JSON.parse(n);return fe(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),T(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await O.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await O.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await O.unlink(n)}catch{}throw o}}async rolloverSession(e,n){v(e);const s=await this.readRolloverManifest();if(s){if(Oe(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();q(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=l(s)===l(e.next);if(!o){const c=await this.readLock();q(e,s,c),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await O.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await O.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await O.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return v(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await O.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await O.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){C(e);const s=await this.readSuccessorTransitionManifest();if(s){if(ue(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(n);if(N(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}V(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!N(e,s)){l(s.runControl)===l(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=pe(e,s);await this.writeState(r),s=await this.readState(n)}if(!N(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await O.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await O.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return C(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await O.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await O.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await O.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await O.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<oe;s+=1)try{n=await O.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await O.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>se){await O.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await O.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){m(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");A(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){$(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},c=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(c){if(c.operationId===e.operationId&&c.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===c.payloadHash&&l(o?.predecessor)===l(r))return c;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const a=e.next.receipts.at(-1);if(!a||l(e.next.predecessor)!==l(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:a.payloadHash,next:e.next};return m(i),A(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),a}trySetFilePerms(e){try{G(e)}catch{}}trySetDirPerms(e){try{Z(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=z(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==f())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(z(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==f())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await O.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===f()}async cleanupOrphanTempFiles(){try{const e=X(this.statePath),n=await O.readdir(e),s=[`${U}.tmp.`,`${D}.tmp.`,`${F}.tmp.`],o=n.filter(r=>s.some(c=>r.startsWith(c)));for(const r of o)try{await O.unlink(w(e,r))}catch{}}catch{}}}function l(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(l).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${l(n)}`).join(",")}}`}function y(t,e){return R("sha256").update(`${t}\0${l(e)}`).digest("hex")}function ie(t){return y("p222-yoloop-continuation-replan-v1",t)}function b(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===y("p205-yoloop-session-v1",n)}function ae(t){return y("p9390812898200217364-yoloop-session-v1",t)}function ce(t){return y("p9390812898200217364-yoloop-rollover-v1",t)}function de(t){return y("p9390812898200217364-yoloop-successor-run-v1",t)}function le(t){return y("p9046281030721413419-yoloop-successor-transition-v1",t)}function ue(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function C(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;$(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==le(n)||Buffer.byteLength(l(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||o!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||s!==void 0&&r===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function V(t,e){if(C(t),!(l(e.runControl)===l(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}he(t,e)}function he(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],o=t.acknowledgement;if(o){const d=n.find(p=>p.idempotencyKey===o.idempotencyKey);if(!d||o.receipt.sessionId!==d.sessionId||l(o.receipt.storyIds)!==l(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const h=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(l(t.state.pendingContinuationAuthorities??[])!==l(h)||l(t.state.continuationReceipts??[])!==l(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(l(t.state.pendingContinuationAuthorities??[])!==l(n)||l(t.state.continuationReceipts??[])!==l(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const c=String(r.idempotencyKey??""),a=t.state.pendingContinuationAuthorities??[],i=a.find(d=>d.idempotencyKey===c);if(i&&l(i)!==l(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&a.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function pe(t,e){V(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function N(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n);const o={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return l(e)===l(o)}function Oe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function v(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==ce(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function $(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==de(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function q(t,e,n){v(t);const s=e.currentSession;if(!s||ae(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(l(r)!==l(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const a=r.receipts.at(-1);if(!a)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:a.operationId,idempotencyKey:a.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:a.payloadHash,next:r};m(i),A(o,i)}else{const a=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||a?.runId!==t.runId||a.revision!==1||a.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const c={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(l(c)!==l(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function B(t){const{receipts:e,...n}=t.next;return y("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const L=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ye={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function _e(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:L.has(t)||t==="cancelling"?null:"cancelling"}function Ie(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=y("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),c={...o,snapshotId:r,snapshotHash:y("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},a={...o,sequence:c.sequence+1,phase:"after",status:t.target,parentSnapshotHash:c.snapshotHash},i=y("p220-yoloop-progress-snapshot-id-v1",{runId:a.runId,operationId:a.operationId,sequence:a.sequence,phase:a.phase}),d={...a,snapshotId:i,snapshotHash:y("p220-yoloop-progress-snapshot-v1",{...a,snapshotId:i})},h={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=y("p220-yoloop-run-event-id-v1",{runId:h.runId,operationId:h.operationId,sequence:h.sequence}),p={...h,eventId:u,eventHash:y("p220-yoloop-run-event-v1",{...h,eventId:u})},_={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,c,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:_},g=B(I),W={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:g,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:g,next:{..._,receipts:[..._.receipts,W]}}}function m(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==B(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function A(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||l(n.events.slice(0,s.length))!==l(s)||l(n.progressSnapshots.slice(0,o.length))!==l(o)||l(n.receipts.slice(0,r.length))!==l(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(L.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const h=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(h==="budget"||h==="retry");if(!(ye[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(l(t.predecessor)!==l(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=n.progressSnapshots.at(-2),a=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!c||!a||!i||!d||c.phase!=="before"||a.phase!=="after"||c.operationId!==e.operationId||a.operationId!==e.operationId||i.operationId!==e.operationId||c.runId!==e.runId||a.runId!==e.runId||i.runId!==e.runId||c.revision!==n.revision||a.revision!==n.revision||i.revision!==n.revision||c.parentSnapshotHash!==(t?.latestSnapshotHash??null)||a.parentSnapshotHash!==c.snapshotHash||n.latestSnapshotHash!==a.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");j(c),j(a),we(i,s.at(-1)?.eventHash??null)}function j(t){const{snapshotHash:e,...n}=t;if(e!==y("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function we(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==y("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function J(t,e){return`lease-${Se(`${t}:${e}`)}`}function Se(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function z(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function fe(t,e){const n=T(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?P(t.recovery_history):[]}}function P(t){return t.length<=x?t:t.slice(t.length-x)}export{M as YOLOOP_PERSISTENCE_CAPABILITIES,Pe as YoloopClientStateStore,ie as buildYoloopContinuationReplanPayloadHash,B as buildYoloopRunTransitionPayloadHash,ce as buildYoloopSessionRolloverPayloadHash,de as buildYoloopSuccessorRunPayloadHash,le as buildYoloopSuccessorTransitionPayloadHash,P as capRecoveryHistory,T as createDefaultCounters,Ae as createDefaultState,ae as fingerprintYoloopSession};
1
+ import{promises as y}from"node:fs";import{existsSync as E}from"node:fs";import{createHash as A}from"node:crypto";import{join as R,dirname as he}from"node:path";import{hostname as C}from"node:os";import{setSecureFilePermissions as pe,setSecureDirPermissions as ye}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as j}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as q,epicOperationalCanonicalJson as m,epicOperationalHash as v,mutateEpicOperationalState as B,readEpicOperationalState as P}from"../git/epic-operational-state.js";import{yoloopDomainHash as Oe}from"../../../shared/dist/yoloop/canonical.js";const _e=".neocortex",z="yoloop-state.json",Ie="yoloop.lock",fe="yoloop-state.mutation.lock",J="yoloop-session-rollover.json",G="yoloop-successor-transition.json",W=360*60*1e3,we=3e4,Se=200,X=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1"]),Re={warn:()=>{},info:()=>{},error:()=>{}};function x(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function nt(t){return{lock:null,state:x(t),capabilities:X}}class st{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Re){this.projectRoot=e,this.stateDir=R(e,_e),this.statePath=R(this.stateDir,z),this.lockPath=R(this.stateDir,Ie),this.mutationLockPath=R(this.stateDir,fe),this.rolloverManifestPath=R(this.stateDir,J),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s)return{lock:s.yoloop.lock,state:s.yoloop.state,capabilities:s.yoloop.capabilities};await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[o,r]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(o,n),state:r,capabilities:X}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const o of e.operations)await this.applyCommonOperation(o,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const o of e.operations)await this.applyOperation(o,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!le(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const o=r=>{const a=(r.pendingContinuationAuthorities??[]).find(l=>l.idempotencyKey===e.idempotencyKey);if(!a)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c={sessionId:String(a.sessionId??""),idempotencyKey:e.idempotencyKey,storyIds:Array.isArray(a.storyIds)?a.storyIds.map(String):[]};if(!le(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.continuationReceipts??[],d=i.find(l=>qe(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(m(d)===m(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...r,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:r,operational:a}=P(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return o(a.yoloop.state)==="unchanged"?"unchanged":(await B(this.projectRoot,{identityHash:c[0],expectedRevision:r.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=o(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const r=o(await this.readState(s));return r==="unchanged"?"unchanged":(await this.writeState(r),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const o=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(o)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(o).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,l=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(l){if(l.operationId===i&&l.idempotencyKey===d)return l;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=xe(a.status,e);if(!u)throw new Error(U.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(ke({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:o}),o)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:o,...r}=e.state;await this.writeState({...r,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await q(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=P(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!E(R(this.projectRoot,".git")))return null;throw e}}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await q(this.projectRoot,e);return}const{document:s,operational:o}=P(this.projectRoot),r=Object.keys(o.identities);if(r.length!==1)throw new Error("epic-operational-identity-mismatch");const a=r[0];await B(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:o.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d&&d.sessionId!==e.lock.sessionId)throw new Error("YOLOOP_LOCK_HELD");d={...e.lock,pid:process.pid,hostname:C(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??W,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;l={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;l={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=u.find(I=>I.idempotencyKey===p);if(O){if(m(O)!==m(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const O=i.continuationReceipts??[];if(O.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||v("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");l={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");l={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":l={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":l=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(v("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||v("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(O=>O.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":l={...i,recovery_history:F([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),l={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}c.yoloop={...c.yoloop,lock:d,state:l}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),o=s.pendingContinuationAuthorities??[],r=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!r)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=o.find(c=>c.idempotencyKey===r);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(o.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...o,e]})}async acknowledgeContinuationAuthority(e,n,s){const o=await this.readState(s),r=o.pendingContinuationAuthorities??[],a=r.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=r[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=r.filter((l,u)=>u!==a),d=o.continuationReceipts??[];await this.writeState({...o,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,o){const r=await this.readState(o),a=r.pendingContinuationAuthorities??[],c=r.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||_("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const l=_("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==l)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||_("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...r,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const o=await this.readState(s);if(o.currentSession||(o.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(r){if(r.code!=="ENOENT")throw r}await this.writeState({...o,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:E(this.lockPath),rolloverManifestPresent:E(this.rolloverManifestPath),successorTransitionManifestPresent:E(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(o){throw o.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):o}if(A("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(E(this.lockPath)||E(this.rolloverManifestPath)||E(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:A("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const o=await y.open(s,"w",384);try{await o.writeFile(n),await o.sync()}finally{await o.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(o){throw await y.unlink(s).catch(()=>{}),o}}async replanContinuationSession(e,n){const{type:s,payloadHash:o,receipt:r,...a}=e;if(Ee(a)!==e.payloadHash||!Z(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const c={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:_("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===_("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(h(e.receipt)!==h(c))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const l=i.continuationReplanReceipts??[],u=l.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(h(u)===h(c)&&h(i.continuationSession)===h(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,O=i.pendingContinuationAuthorities??[];if(!Z(p)||_("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||_("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...l.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),o=s.recovery_history??[];if(o.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=F([...o,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const o=await this.readState(s),r=o.recovery_history??[],a=r.findIndex(l=>l.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=r[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=r.slice();i[a]={...c,outcome:n,finished_at:s};const d={...o,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:C(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??W,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},o=JSON.stringify(s,null,2);try{const r=await y.open(this.lockPath,"wx");try{await r.writeFile(o,"utf8")}finally{await r.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(r){const a=r;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),r;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),r;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(o,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(!s||e.expectedSessionId!==s.sessionId||e.expectedLeaseId!==s.leaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(o){const r=o;if(r.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:r.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Ue(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),x(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const o=await y.open(n,"w",384);try{await o.writeFile(s,"utf8"),await o.sync()}finally{await o.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(o){const r=o;this.logger.error({event:"yoloop_state_write_error",err:r.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw o}}async rolloverSession(e,n){H(e);const s=await this.readRolloverManifest();if(s){if(ve(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const o=await this.readState(n),r=await this.readLock();te(e,o,r),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let o=h(s)===h(e.next);if(!o){const a=await this.readLock();te(e,s,a),await this.writeState(e.next),o=!0}const r=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(r){if(r.sessionId!==e.expectedSessionId||r.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return H(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){k(e);const s=await this.readSuccessorTransitionManifest();if(s){if(Le(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const o=await this.readState(n);if(Y(e,o)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}Q(e,o),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!Y(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const r=Ae(e,s);await this.writeState(r),s=await this.readState(n)}if(!Y(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await y.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await y.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return k(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const o=await this.readState(s);if(!o.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const r={...o,currentSession:{...o.currentSession,currentEpicIndex:e}};await this.writeState(r),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Se;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(o){if(o.code!=="EEXIST")throw o;try{const r=await y.stat(this.mutationLockPath);if(Date.now()-r.mtimeMs>we){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(r=>setTimeout(r,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){D(e);const s=await this.readState(n),o=s.runControl,r=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(r){if(r.operationId===e.operationId&&r.idempotencyKey===e.idempotencyKey&&r.payloadHash===e.payloadHash)return r;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(o&&o.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((o?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");K(o,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){ee(e);const s=await this.readState(n),o=s.runControl,r={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=o?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(o?.predecessor)===h(r))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!o||o.runId!==e.previousRunId||!["exhausted","success"].includes(o.status)||o.revision!==e.expectedRevision||o.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(r))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return D(i),K(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{pe(e)}catch{}}trySetDirPerms(e){try{ye(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=re(e,n),o={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!o.pid||o.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(o.hostname&&o.hostname!==C())return{...o,ownerPidState:"unknown"};try{return process.kill(o.pid,0),{...o,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(re(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==C())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await y.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===C()}async cleanupOrphanTempFiles(){try{const e=he(this.statePath),n=await y.readdir(e),s=[`${z}.tmp.`,`${J}.tmp.`,`${G}.tmp.`],o=n.filter(r=>s.some(a=>r.startsWith(a)));for(const r of o)try{await y.unlink(R(e,r))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function _(t,e){return A("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ee(t){return _("p222-yoloop-continuation-replan-v1",t)}function Z(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===_("p205-yoloop-session-v1",n)}function Ce(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Ne(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function Te(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function me(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function Le(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function k(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;ee(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,o=t.acknowledgement?.receipt.idempotencyKey,r=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==me(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||o!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof r!="string"||!e.test(r))||s!==void 0&&r===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function Q(t,e){if(k(t),!(h(e.runControl)===h(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ge(t,e)}function ge(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],o=t.acknowledgement;if(o){const d=n.find(p=>p.idempotencyKey===o.idempotencyKey);if(!d||o.receipt.sessionId!==d.sessionId||h(o.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==o.idempotencyKey),u=[...s.slice(-63),o.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(l)||h(t.state.continuationReceipts??[])!==h(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const r=t.reservation?.authority;if(!r)return;const a=String(r.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(r))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Ae(t,e){Q(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function Y(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n);const o={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(o)}function ve(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Ne(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function ee(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==Te(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function te(t,e,n){H(t);const s=e.currentSession;if(!s||Ce(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const o=e.runControl;if((o?.revision??0)!==t.expectedRevision||(o?.latestSnapshotHash??null)!==t.expectedSnapshotHash||o&&o.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const r=t.exhaustedRun;if(o)if(o.status==="exhausted"){if(h(r)!==h(o))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!r||r.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=r.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:o.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:o.revision,expectedSnapshotHash:o.latestSnapshotHash,payloadHash:c.payloadHash,next:r};D(i),K(o,i)}else{const c=r?.receipts[0],i=r?.receipts[1];if(r&&(r.runId!==t.runId||r.status!=="exhausted"||r.revision!==2||r.events.length!==2||r.progressSnapshots.length!==4||r.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||r.latestSnapshotHash!==i.snapshotHash||r.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...r?{runControl:r}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function ne(t){const{receipts:e,...n}=t.next;return _("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const U=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),Pe={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function xe(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:U.has(t)||t==="cancelling"?null:"cancelling"}function ke(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},o={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},r=_("p220-yoloop-progress-snapshot-id-v1",{runId:o.runId,operationId:o.operationId,sequence:o.sequence,phase:o.phase}),a={...o,snapshotId:r,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...o,snapshotId:r})},c={...o,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=_("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},l={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=_("p220-yoloop-run-event-id-v1",{runId:l.runId,operationId:l.operationId,sequence:l.sequence}),p={...l,eventId:u,eventHash:_("p220-yoloop-run-event-v1",{...l,eventId:u})},O={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,a,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},T=ne(I),g={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:T,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:T,next:{...O,receipts:[...O.receipts,g]}}}function D(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==ne(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function K(t,e){const n=e.next,s=t?.events??[],o=t?.progressSnapshots??[],r=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==o.length+2||n.receipts.length!==r.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,o.length))!==h(o)||h(n.receipts.slice(0,r.length))!==h(r))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(U.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const l=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(l==="budget"||l==="retry");if(!(Pe[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(h(t.predecessor)!==h(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=n.progressSnapshots.at(-2),c=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!a||!c||!i||!d||a.phase!=="before"||c.phase!=="after"||a.operationId!==e.operationId||c.operationId!==e.operationId||i.operationId!==e.operationId||a.runId!==e.runId||c.runId!==e.runId||i.runId!==e.runId||a.revision!==n.revision||c.revision!==n.revision||i.revision!==n.revision||a.parentSnapshotHash!==(t?.latestSnapshotHash??null)||c.parentSnapshotHash!==a.snapshotHash||n.latestSnapshotHash!==c.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");se(a),se(c),Ye(i,s.at(-1)?.eventHash??null)}function se(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ye(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==_("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function oe(t,e){return`lease-${He(`${t}:${e}`)}`}function He(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function re(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),o=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(o)?"unknown":s<=o?"expired":"active"}function Ue(t,e){const n=x(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?F(t.recovery_history):[]}}function F(t){return t.length<=j?t:t.slice(t.length-j)}const b=Object.freeze(["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"]),De=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function Ke(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(De.has(n))return 0;const s=b.indexOf(e);return s<0?b.length:b.length-1-s}const M="yoloop-round-refused-before-setup",Fe="neocortex.p230.round-refused-before-setup.v1",ie=64,be=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),Me="reasonCode,storyId",ae=/^[a-z0-9][a-z0-9-]{2,79}$/,Ve=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,$e=/^[a-f0-9]{64}$/;function L(t){return typeof t=="string"&&Ve.test(t)&&!t.includes("..")}function N(t){return typeof t=="string"&&$e.test(t)}function ce(t){if(!(!Array.isArray(t)||t.length===0||t.length>ie)&&t.every(L)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function de(t){return Oe(Fe,{schemaVersion:t.schemaVersion,kind:t.kind,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:t.storyIds,refusals:t.refusals.map(e=>({storyId:e.storyId,reasonCode:e.reasonCode}))})}function je(t){if(!t||!L(t.epicId)||!N(t.sessionId)||!N(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ie)return;const e=t.refusals.map(o=>({storyId:o?.storyId,reasonCode:o?.reasonCode})).sort((o,r)=>String(o.storyId).localeCompare(String(r.storyId)));if(!e.every(o=>L(o.storyId)&&typeof o.reasonCode=="string"&&ae.test(o.reasonCode)))return;const n=e.map(o=>o.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:M,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(o=>Object.freeze({storyId:o.storyId,reasonCode:o.reasonCode})))};return Object.freeze({...s,digest:de(s)})}function qe(t){return S(t)&&t.kind===M}function le(t,e){if(!S(t)||Object.keys(t).some(p=>!be.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:o,sessionId:r,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==M||!L(o)||!N(r)||!N(a)||!N(d))return!1;const l=ce(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===Me&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&ae.test(p.reasonCode))||d!==de(t))return!1;if(!e)return!0;const u=ce([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&r===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Be="story-round-no-setup-evidence";function ot(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,o=S(s?.expectedTransition)?s.expectedTransition:void 0,r=Array.isArray(o?.storyLifecycle)?o.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!r||r.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const l=new Set(i.map(f=>{const w=S(t.stories[f])?t.stories[f]:void 0;return typeof w?.epic_id=="string"?w.epic_id:f.split(".")[0]}));if(l.size!==1)return;const u=[...l][0],p=S(t.epics[u])?t.epics[u]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],I=S(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,T=Array.isArray(I?.receipts)?I.receipts:[],g=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],ue=f=>O.some(w=>S(w)&&w.storyId===f)||T.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||g.some(w=>S(w)&&w.storyId===f);for(const f of i){if(ue(f))return;const w=r.find($=>S($)&&$.storyId===f),V=S(t.stories[f])?t.stories[f]:void 0;if(!w||!V||!Number.isSafeInteger(w.remaining)||Ke(V.status)!==w.remaining)return}return je({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Be}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{X as YOLOOP_PERSISTENCE_CAPABILITIES,Be as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,M as YOLOOP_ROUND_REFUSED_KIND,st as YoloopClientStateStore,je as buildClientYoloopRoundRefusedReceipt,Ee as buildYoloopContinuationReplanPayloadHash,ne as buildYoloopRunTransitionPayloadHash,Ne as buildYoloopSessionRolloverPayloadHash,Te as buildYoloopSuccessorRunPayloadHash,me as buildYoloopSuccessorTransitionPayloadHash,F as capRecoveryHistory,Ke as clientYoloopStoryLifecycleRemaining,x as createDefaultCounters,nt as createDefaultState,ot as deriveYoloopRoundRefusedBeforeSetupReceipt,Ce as fingerprintYoloopSession,qe as isClientYoloopRoundRefusedRecord,le as isValidClientYoloopRoundRefusedReceipt};
@@ -87,6 +87,34 @@ export function hostKindForPlatformTarget(platformTarget) {
87
87
  return undefined;
88
88
  return PRIVATE_EXECUTION_HOST_BY_PLATFORM[platformTarget];
89
89
  }
90
+ /**
91
+ * P229.04 (P229-CON-REFUSAL): stable public reason codes of the private
92
+ * harness executor. They are route/client `error_code` values, deliberately
93
+ * kept outside `COMPATIBILITY_REASON_CODES` (P228.18 DEC-03).
94
+ */
95
+ export const PRIVATE_EXECUTOR_REASON_CODES = Object.freeze({
96
+ HEADLESS_UNAVAILABLE: 'private-executor-headless-unavailable',
97
+ VERSION_UNSUPPORTED: 'private-executor-version-unsupported',
98
+ TIMEOUT: 'private-executor-timeout',
99
+ PROOF_INVALID: 'private-executor-proof-invalid',
100
+ });
101
+ /**
102
+ * P229.04 (P229-CON-ADMISSION): the simple executor proof v7 is the same for
103
+ * every host (ADR-P229-02). Every verification field must be `passed`.
104
+ */
105
+ export const PRIVATE_EXECUTOR_PROOF_V7_FIELDS = Object.freeze([
106
+ 'preflight', 'hostVersion', 'stdinOnly', 'ephemeralHome', 'nativeNoPersistence', 'os',
107
+ ]);
108
+ /** Exact-shape check: no missing, extra or non-`passed` field is accepted. */
109
+ export function isPrivateExecutorProofV7(value) {
110
+ if (!value || typeof value !== 'object' || Array.isArray(value))
111
+ return false;
112
+ const record = value;
113
+ const keys = Object.keys(record);
114
+ return keys.length === PRIVATE_EXECUTOR_PROOF_V7_FIELDS.length + 1
115
+ && record.schemaVersion === 7
116
+ && PRIVATE_EXECUTOR_PROOF_V7_FIELDS.every((field) => Object.prototype.hasOwnProperty.call(record, field) && record[field] === 'passed');
117
+ }
90
118
  /** True only for a valid `CompatibilityOffer/1.0` that advertises the capability. */
91
119
  export function supportsPrivateExecutionHostNeutral(offer) {
92
120
  return isCompatibilityOfferV1(offer)
@@ -1,4 +1,4 @@
1
- # 🧠 Neocortex v4.66.0 | OrNexus Team
1
+ # 🧠 Neocortex v4.66.2 | OrNexus Team
2
2
 
3
3
  This project uses Neocortex, a Development Orchestrator.
4
4
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.2 | OrNexus Team"
4
4
  ---
5
5
 
6
6
  <!--
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex Root Agent'
5
5
  title: 'Development Orchestrator (Root alias of neocortex)'
6
6
  icon: '>'
7
- version: '4.66.0'
7
+ version: '4.66.2'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex Root Agent v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex Root Agent v4.66.2 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  tools:
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
113
113
  ┌────────────────────────────────────────────────────────────┐
114
114
  │ │
115
115
  │ ####### N E O C O R T E X │
116
- │ ### ######## v4.66.0 │
116
+ │ ### ######## v4.66.2 │
117
117
  │ ######### ##### │
118
118
  │ ## ############## Development Orchestrator │
119
119
  │ ## ### ###### ## OrNexus Team │
@@ -102,7 +102,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
102
102
  ┌────────────────────────────────────────────────────────────┐
103
103
  │ │
104
104
  │ ####### N E O C O R T E X │
105
- │ ### ######## v4.66.0 │
105
+ │ ### ######## v4.66.2 │
106
106
  │ ######### ##### │
107
107
  │ ## ############## Development Orchestrator │
108
108
  │ ## ### ###### ## OrNexus Team │
@@ -4,7 +4,7 @@ agent:
4
4
  name: 'Neocortex'
5
5
  title: 'Development Orchestrator'
6
6
  icon: '>'
7
- version: '4.66.0'
7
+ version: '4.66.2'
8
8
  architecture: 'thin-client'
9
9
  module: stand-alone
10
10
  hasSidecar: false
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.2 | OrNexus Team"
4
4
  model: opus
5
5
  color: blue
6
6
  permissionMode: bypassPermissions
@@ -113,7 +113,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
113
113
  ┌────────────────────────────────────────────────────────────┐
114
114
  │ │
115
115
  │ ####### N E O C O R T E X │
116
- │ ### ######## v4.66.0 │
116
+ │ ### ######## v4.66.2 │
117
117
  │ ######### ##### │
118
118
  │ ## ############## Development Orchestrator │
119
119
  │ ## ### ###### ## OrNexus Team │
@@ -32,7 +32,7 @@ Codex built-in commands or actions.
32
32
 
33
33
  <!-- END: Plugin Conflict Prevention -->
34
34
 
35
- # Neocortex v4.66.0 | OrNexus Team
35
+ # Neocortex v4.66.2 | OrNexus Team
36
36
 
37
37
  You are a Development Orchestrator. All orchestration logic is delivered by the remote Neocortex server.
38
38
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.2 | OrNexus Team"
4
4
  model: inherit
5
5
  readonly: false
6
6
  is_background: false
@@ -115,7 +115,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
115
115
  ┌────────────────────────────────────────────────────────────┐
116
116
  │ │
117
117
  │ ####### N E O C O R T E X │
118
- │ ### ######## v4.66.0 │
118
+ │ ### ######## v4.66.2 │
119
119
  │ ######### ##### │
120
120
  │ ## ############## Development Orchestrator │
121
121
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex-root
3
- description: "🧠 Neocortex v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.2 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -73,7 +73,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
73
73
  ┌────────────────────────────────────────────────────────────┐
74
74
  │ │
75
75
  │ ####### N E O C O R T E X │
76
- │ ### ######## v4.66.0 │
76
+ │ ### ######## v4.66.2 │
77
77
  │ ######### ##### │
78
78
  │ ## ############## Development Orchestrator │
79
79
  │ ## ### ###### ## OrNexus Team │
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: neocortex
3
- description: "🧠 Neocortex v4.66.0 | OrNexus Team"
3
+ description: "🧠 Neocortex v4.66.2 | OrNexus Team"
4
4
  kind: local
5
5
  tools:
6
6
  # File operations (Gemini CLI built-ins)
@@ -72,7 +72,7 @@ SEMPRE que este agente for invocado, imprima o banner abaixo como PRIMEIRO outpu
72
72
  ┌────────────────────────────────────────────────────────────┐
73
73
  │ │
74
74
  │ ####### N E O C O R T E X │
75
- │ ### ######## v4.66.0 │
75
+ │ ### ######## v4.66.2 │
76
76
  │ ######### ##### │
77
77
  │ ## ############## Development Orchestrator │
78
78
  │ ## ### ###### ## OrNexus Team │
@@ -42,7 +42,7 @@ Grok native subagents when the host exposes them:
42
42
  `storyIds` (and matching `promptTemplates`, when present).
43
43
  - `mode: continuous_dag`: take the plan's ready `storyIds` (and matching
44
44
  `promptTemplates`, when present).
45
- - Spawn ONE `neocortex` child per story **in a single turn with multiple subagent calls**, so the children truly run
45
+ - Spawn ONE `neocortex-sentinel` child per story **in a single turn with multiple subagent calls**, so the children truly run
46
46
  in parallel. When the plan gives `maxConcurrency`, launch at most that many at
47
47
  once and start the remainder as earlier children return.
48
48
  - Each child receives only its server-authored per-story prompt, for example
@@ -62,8 +62,8 @@ When the Grok host offers no subagent primitive, the root keeps the conservative
62
62
  ### Native child dispatch (Grok Build)
63
63
 
64
64
  Grok Build starts children with `spawn_subagent`. For each authorized story,
65
- call it with `subagent_type: "neocortex"` (the published `.grok/agents/neocortex.md`
66
- child), `description` set to a short story label and `prompt` set to that
65
+ call it with `subagent_type: "neocortex-sentinel"` (the published
66
+ `.grok/agents/neocortex-sentinel.md` child), `description` set to a short story label and `prompt` set to that
67
67
  story's server-authored per-story prompt. For a v4 `client_managed_worktree`
68
68
  plan, give the child the managed worktree path from
69
69
  `neocortex-client story-worktree create` as `cwd`; otherwise use
@@ -1,5 +1,5 @@
1
1
  ---
2
- name: neocortex
2
+ name: neocortex-sentinel
3
3
  description: >
4
4
  Internal Neocortex per-story child. The root Neocortex agent starts it with
5
5
  spawn_subagent and a server-authored per-story prompt; do not select it for
@@ -13,7 +13,7 @@ agents_md: true
13
13
  # Neocortex child for Grok Build
14
14
 
15
15
  You are a Neocortex per-story child started by the root agent with
16
- `spawn_subagent` (`subagent_type: "neocortex"`). You are a thin client: all
16
+ `spawn_subagent` (`subagent_type: "neocortex-sentinel"`). You are a thin client: all
17
17
  orchestration comes from the remote Neocortex server through `neocortex-client`.
18
18
 
19
19
  ## Input boundary