@ornexus/neocortex 4.66.18 → 4.66.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +3 -2
- package/packages/client/dist/commands/invoke.js +58 -58
- package/packages/client/dist/git/epic-execution-checkout.d.ts +3 -0
- package/packages/client/dist/git/epic-execution-checkout.js +1 -0
- package/packages/client/dist/git/epic-state-recovery.d.ts +3 -1
- package/packages/client/dist/git/epic-state-recovery.js +2 -2
- package/packages/client/dist/git/published-story-reconciliation.d.ts +7 -6
- package/packages/client/dist/git/published-story-reconciliation.js +5 -5
- package/packages/client/dist/git/story-write-set-extension.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.d.ts +26 -6
- package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
- package/packages/client/dist/yoloop/target-normalization.d.ts +1 -0
- package/packages/client/dist/yoloop/target-normalization.js +1 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.d.ts +2 -6
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1
- package/packages/shared/dist/yoloop/execution-plan-v4-contract.js +332 -0
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -200,13 +200,9 @@ export declare class YoloopClientStateStore {
|
|
|
200
200
|
* check PID liveness for client-owned same-host locks; the server cannot.
|
|
201
201
|
*/
|
|
202
202
|
private prepareLockForSnapshot;
|
|
203
|
-
/**
|
|
204
|
-
* If the existing lock is held by a dead PID on the same host, delete
|
|
205
|
-
* it and return true (caller retries acquisition). Otherwise return
|
|
206
|
-
* false (honor the lock).
|
|
207
|
-
*/
|
|
203
|
+
/** Invoked while acquisition holds the checkout-local mutation lock. */
|
|
208
204
|
private maybeRecoverOrphanLock;
|
|
209
|
-
private
|
|
205
|
+
private removeRecoveredLock;
|
|
210
206
|
private isSameClientSessionLock;
|
|
211
207
|
/** Remove `yoloop-state.json.tmp.*` orphans from crashed writes. */
|
|
212
208
|
private cleanupOrphanTempFiles;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{promises as y}from"node:fs";import{existsSync as C}from"node:fs";import{createHash as P}from"node:crypto";import{join as R,dirname as ye}from"node:path";import{hostname as N}from"node:os";import{setSecureFilePermissions as Oe,setSecureDirPermissions as _e}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as B}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as z,epicOperationalCanonicalJson as E,epicOperationalHash as x,mutateEpicOperationalState as k,readEpicOperationalState as m}from"../git/epic-operational-state.js";import{yoloopDomainHash as Ie}from"../../../shared/dist/yoloop/canonical.js";const fe=".neocortex",J="yoloop-state.json",we="yoloop.lock",Se="yoloop-state.mutation.lock",W="yoloop-session-rollover.json",G="yoloop-successor-transition.json",X=360*60*1e3,Re=3e4,Ee=200,Z=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1","native-launch-retry-v1"]),Ce={warn:()=>{},info:()=>{},error:()=>{}};function Y(t){const e=t.slice(0,10);return{version:"1.1",lastResetAt:t,storiesRunToday:0,iterationsToday:0,iterationsTodayDate:e,tokensUsedToday:0,lastRunAt:null,coolDownUntil:null,totalRunsAllTime:0,totalStoriesAllTime:0,currentSession:null,continuationPolicy:"p205-finite-resume-v2",pendingContinuationAuthorities:[],continuationReceipts:[],continuationRecoveryReceipts:[]}}function rt(t){return{lock:null,state:Y(t),capabilities:Z}}class ot{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Ce){this.projectRoot=e,this.stateDir=R(e,fe),this.statePath=R(this.stateDir,J),this.lockPath=R(this.stateDir,we),this.mutationLockPath=R(this.stateDir,Se),this.rolloverManifestPath=R(this.stateDir,W),this.successorTransitionManifestPath=R(this.stateDir,G),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s){const c=await this.reconcileCommonLock(s,n);return{lock:c.lock,state:c.state,capabilities:[...new Set([...c.capabilities,"native-launch-retry-v1"])]}}await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[r,o]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(r,n),state:o,capabilities:Z}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const r of e.operations)await this.applyCommonOperation(r,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const r of e.operations)await this.applyOperation(r,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!he(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const r=o=>{const a=(o.pendingContinuationAuthorities??[]).find(l=>l.idempotencyKey===e.idempotencyKey);if(!a)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c={sessionId:String(a.sessionId??""),idempotencyKey:e.idempotencyKey,storyIds:Array.isArray(a.storyIds)?a.storyIds.map(String):[]};if(!he(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=o.continuationReceipts??[],d=i.find(l=>ze(l)&&l.idempotencyKey===e.idempotencyKey);if(d){if(E(d)===E(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...o,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:o,operational:a}=m(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return r(a.yoloop.state)==="unchanged"?"unchanged":(await k(this.projectRoot,{identityHash:c[0],expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=r(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const o=r(await this.readState(s));return o==="unchanged"?"unchanged":(await this.writeState(o),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const r=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(r)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(r).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,l=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(l){if(l.operationId===i&&l.idempotencyKey===d)return l;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const u=Ye(a.status,e);if(!u)throw new Error(A.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(He({current:a,action:e,target:u,operationId:i,idempotencyKey:d,occurredAt:r}),r)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:r,...o}=e.state;await this.writeState({...o,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await z(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=m(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!C(R(this.projectRoot,".git")))return null;throw e}}async reconcileCommonLock(e,n){const s=e.yoloop.lock;if(!s||s.ownerKind!=="client")return e.yoloop;const r=ie(s);if(!ae(e.yoloop,n,r))return{...e.yoloop,lock:{...s,ownerPidState:r==="live"?"live":"unknown"}};const{document:o,operational:a}=m(this.projectRoot);if(E(a.yoloop.lock)!==E(s))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const c=Object.values(a.identities).filter(d=>d.epicId===s.currentEpicId);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");const{value:i}=await k(this.projectRoot,{identityHash:c[0].identityHash,expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},d=>{if(d.activeJournal!==null||E(d.yoloop.lock)!==E(s)||!ae(d.yoloop,n,ie(s)))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const l={...d.yoloop,lock:null};return d.yoloop=l,l});return i}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await z(this.projectRoot,e);return}const{document:s,operational:r}=m(this.projectRoot),o=Object.keys(r.identities);if(o.length!==1)throw new Error("epic-operational-identity-mismatch");const a=o[0];await k(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:r.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,l=i;switch(e.type){case"acquire_lock":{if(d){if(d.sessionId===e.lock.sessionId&&d.leaseId===e.lock.leaseId&&d.hostname===N()&&d.pid===process.pid)return;throw new Error("YOLOOP_LOCK_HELD")}d={...e.lock,pid:process.pid,hostname:N(),ownerKind:"client",leaseId:e.lock.leaseId??oe(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??X,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseExpiresAt&&(d?.leaseExpiresAt??d?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:u,...p}=e.state;l={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;l={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=u.find(I=>I.idempotencyKey===p);if(O){if(E(O)!==E(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||u.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[...u,e.authority]};break}case"acknowledge_continuation_authority":{const u=i.pendingContinuationAuthorities??[],p=u.find(I=>I.idempotencyKey===e.idempotencyKey);if(!p)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const O=i.continuationReceipts??[];if(O.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:u.filter(I=>I!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const u=i.pendingContinuationAuthorities??[];if(u.length!==1||x("p208-legacy-authority-before-v1",u[0])!==e.beforeHash)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const p=i.continuationRecoveryReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,pendingContinuationAuthorities:[e.authority],continuationRecoveryReceipts:[...p,e.receipt]};break}case"switch_continuation_policy":{if(i.currentSession||(i.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");l={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const u=i.runControl;if(!u||u.revision!==e.expectedRevision||u.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");l={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":l={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":l=e.next,d=null;break;case"replan_continuation_session":{const u=i.pendingContinuationAuthorities??[];if(x("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||x("p222-yoloop-replan-pending-v1",u)!==e.expectedPendingHash||u.length>1||u.some(O=>O.delegated!==!1))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");const p=i.continuationReplanReceipts??[];if(p.length>=64)throw new Error("YOLOOP_CONTINUATION_RECEIPT_CAPACITY_EXCEEDED");l={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":l={...i,recovery_history:M([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const u=[...i.recovery_history??[]],p=u.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(u[p]={...u[p],outcome:e.outcome,finished_at:n}),l={...i,recovery_history:u};break}default:{const u=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(u)}`)}}c.yoloop={...c.yoloop,lock:d,state:l}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),r=s.pendingContinuationAuthorities??[],o=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!o)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=r.find(c=>c.idempotencyKey===o);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(r.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...r,e]})}async acknowledgeContinuationAuthority(e,n,s){const r=await this.readState(s),o=r.pendingContinuationAuthorities??[],a=o.findIndex(l=>l.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=o[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=o.filter((l,u)=>u!==a),d=r.continuationReceipts??[];await this.writeState({...r,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,r){const o=await this.readState(r),a=o.pendingContinuationAuthorities??[],c=o.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||_("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const l=_("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==l)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const u={...s};if(delete u.idempotencyKey,!i||_("p208-legacy-authority-recovery-receipt-v1",u)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...o,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const r=await this.readState(s);if(r.currentSession||(r.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(o){if(o.code!=="ENOENT")throw o}await this.writeState({...r,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:C(this.lockPath),rolloverManifestPresent:C(this.rolloverManifestPath),successorTransitionManifestPresent:C(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(r){throw r.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):r}if(P("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(C(this.lockPath)||C(this.rolloverManifestPath)||C(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:P("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const r=await y.open(s,"w",384);try{await r.writeFile(n),await r.sync()}finally{await r.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(r){throw await y.unlink(s).catch(()=>{}),r}}async replanContinuationSession(e,n){const{type:s,payloadHash:r,receipt:o,...a}=e;if(Ne(a)!==e.payloadHash||!Q(e.nextSession))throw new Error("YOLOOP_CONTINUATION_REPLAN_PAYLOAD_INVALID");const c={schemaVersion:"YoloopContinuationReplanReceipt/1.0",operationId:e.operationId,idempotencyKey:e.idempotencyKey,runId:e.expectedRunId,previousSessionHash:e.expectedSessionHash,nextSessionHash:_("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===_("p222-yoloop-replan-pending-v1",[])?0:1,payloadHash:e.payloadHash,outcome:"graph-replanned",publicSafe:!0};if(h(e.receipt)!==h(c))throw new Error("YOLOOP_CONTINUATION_REPLAN_RECEIPT_INVALID");const i=await this.readState(n);if(await this.readLock()||i.currentSession!==null)throw new Error("YOLOOP_CONTINUATION_REPLAN_ACTIVE");const d=i.runControl;if(!d||d.runId!==e.expectedRunId||!["success","exhausted"].includes(d.status)||d.revision!==e.expectedRevision||d.latestSnapshotHash!==e.expectedSnapshotHash||i.continuationPolicy!=="p205-finite-resume-v2")throw new Error("YOLOOP_CONTINUATION_REPLAN_RUN_CONFLICT");const l=i.continuationReplanReceipts??[],u=l.find(I=>I.idempotencyKey===e.idempotencyKey||I.operationId===e.operationId);if(u){if(h(u)===h(c)&&h(i.continuationSession)===h(e.nextSession)&&(i.pendingContinuationAuthorities?.length??0)===0)return;throw new Error("YOLOOP_CONTINUATION_REPLAN_REPLAY_CONFLICT")}const p=i.continuationSession,O=i.pendingContinuationAuthorities??[];if(!Q(p)||_("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||_("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(I=>I.delegated!==!1||I.sessionId!==p.sessionId||!I.certificate||I.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...l.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),r=s.recovery_history??[];if(r.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=M([...r,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const r=await this.readState(s),o=r.recovery_history??[],a=o.findIndex(l=>l.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=o[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=o.slice();i[a]={...c,outcome:n,finished_at:s};const d={...r,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:N(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??oe(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??X,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},r=JSON.stringify(s,null,2);try{const o=await y.open(this.lockPath,"wx");try{await o.writeFile(r,"utf8")}finally{await o.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(o){const a=o;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),o;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),o;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(r,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT")}if(e.expectedSessionId&&e.expectedSessionId!==s?.sessionId||e.expectedLeaseId&&e.expectedLeaseId!==s?.leaseId||e.expectedLeaseExpiresAt&&(s?.leaseExpiresAt??s?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(r){const o=r;if(o.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:o.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Ke(s,e)}catch(n){const s=n;return s.code!=="ENOENT"&&this.logger.warn({event:"yoloop_state_read_error",err:s.message},"yoloop state file unreadable; using defaults"),Y(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const r=await y.open(n,"w",384);try{await r.writeFile(s,"utf8"),await r.sync()}finally{await r.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(r){const o=r;this.logger.error({event:"yoloop_state_write_error",err:o.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw r}}async rolloverSession(e,n){D(e);const s=await this.readRolloverManifest();if(s){if(xe(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const r=await this.readState(n),o=await this.readLock();ne(e,r,o),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let r=h(s)===h(e.next);if(!r){const a=await this.readLock();ne(e,s,a),await this.writeState(e.next),r=!0}const o=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(o){if(o.sessionId!==e.expectedSessionId||o.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return D(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT")}}async writeRolloverManifest(e){const n=`${this.rolloverManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.rolloverManifestPath),await this.syncStateDirectory()}async commitSuccessorTransition(e,n){H(e);const s=await this.readSuccessorTransitionManifest();if(s){if(ge(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const r=await this.readState(n);if(U(e,r)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}ee(e,r),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!U(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const o=Pe(e,s);await this.writeState(o),s=await this.readState(n)}if(!U(e,s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT");await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_successor_transition_applied",runId:e.successor.runId,operationId:e.operationId},"yoloop successor transition applied")}async recoverSuccessorTransitionIfPresent(e){try{await y.access(this.successorTransitionManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readSuccessorTransitionManifest();n?.phase==="prepared"&&await this.completePreparedSuccessorTransition(n.operation,e)})}async readSuccessorTransitionManifest(){try{const e=JSON.parse(await y.readFile(this.successorTransitionManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSuccessorTransitionManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="commit_successor_transition")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT");return H(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const r=await this.readState(s);if(!r.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const o={...r,currentSession:{...r.currentSession,currentEpicIndex:e}};await this.writeState(o),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Ee;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(r){if(r.code!=="EEXIST")throw r;try{const o=await y.stat(this.mutationLockPath);if(Date.now()-o.mtimeMs>Re){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(o=>setTimeout(o,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){K(e);const s=await this.readState(n),r=s.runControl,o=r?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(o){if(o.operationId===e.operationId&&o.idempotencyKey===e.idempotencyKey&&o.payloadHash===e.payloadHash)return o;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(r&&r.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");F(r,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){te(e);const s=await this.readState(n),r=s.runControl,o={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=r?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(r?.predecessor)===h(o))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!r||r.runId!==e.previousRunId||!["exhausted","success"].includes(r.status)||r.revision!==e.expectedRevision||r.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(o))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return K(i),F(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{Oe(e)}catch{}}trySetDirPerms(e){try{_e(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e)return null;if(e.ownerKind!=="client")return e;const s=b(e,n),r={...e,leaseState:s};if(s==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"lease_expired"},"expired client-owned yoloop lock lease recovered before snapshot echo"),null;if(!r.pid||r.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"invalid_pid"},"invalid PID in client-owned yoloop lock; recovered"),null;if(r.hostname&&r.hostname!==N())return{...r,ownerPidState:"unknown"};try{return process.kill(r.pid,0),{...r,ownerPidState:"live"}}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:"dead_pid"},"stale client-owned yoloop lock recovered before snapshot echo"),null}}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;if(b(n,e)==="expired")return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"lease_expired"},"expired yoloop lock lease recovered"),!0;if(!n.pid||n.pid<=0)return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"invalid_pid"},"invalid PID in lock file; recovered"),!0;if(n.hostname&&n.hostname!==N())return this.logger.warn({event:"yoloop_lock_remote_host",ownerKind:n.ownerKind??"server",ownerPidState:"unknown"},"lock held by a remote host; honoring"),!1;try{return process.kill(n.pid,0),!1}catch{return await this.deleteLockBestEffort(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:"dead_pid"},"orphan yoloop lock recovered"),!0}}async deleteLockBestEffort(){try{await y.unlink(this.lockPath)}catch{}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===N()}async cleanupOrphanTempFiles(){try{const e=ye(this.statePath),n=await y.readdir(e),s=[`${J}.tmp.`,`${W}.tmp.`,`${G}.tmp.`],r=n.filter(o=>s.some(a=>o.startsWith(a)));for(const o of r)try{await y.unlink(R(e,o))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function _(t,e){return P("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Ne(t){return _("p222-yoloop-continuation-replan-v1",t)}function Q(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;const{sessionId:e,...n}=t;return typeof e=="string"&&/^[a-f0-9]{64}$/.test(e)&&e===_("p205-yoloop-session-v1",n)}function Te(t){return _("p9390812898200217364-yoloop-session-v1",t)}function Le(t){return _("p9390812898200217364-yoloop-rollover-v1",t)}function me(t){return _("p9390812898200217364-yoloop-successor-run-v1",t)}function Ae(t){return _("p9046281030721413419-yoloop-successor-transition-v1",t)}function ge(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function H(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;te(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,r=t.acknowledgement?.receipt.idempotencyKey,o=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==Ae(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||r!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof o!="string"||!e.test(o))||s!==void 0&&o===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function ee(t,e){if(H(t),!(h(e.runControl)===h(t.successor.next))){const s=e.runControl;if(!s||s.runId!==t.successor.previousRunId||!["exhausted","success"].includes(s.status)||s.revision!==t.successor.expectedRevision||s.latestSnapshotHash!==t.successor.expectedSnapshotHash||e.currentSession!==null)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_STATE_CONFLICT")}ve(t,e)}function ve(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],r=t.acknowledgement;if(r){const d=n.find(p=>p.idempotencyKey===r.idempotencyKey);if(!d||r.receipt.sessionId!==d.sessionId||h(r.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const l=n.filter(p=>p.idempotencyKey!==r.idempotencyKey),u=[...s.slice(-63),r.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(l)||h(t.state.continuationReceipts??[])!==h(u))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const o=t.reservation?.authority;if(!o)return;const a=String(o.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(o))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function Pe(t,e){ee(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function U(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n);const r={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(r)}function xe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function D(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,expectedSessionId:t.expectedSessionId,expectedSessionFingerprint:t.expectedSessionFingerprint,expectedLeaseId:t.expectedLeaseId,coolDownUntil:t.coolDownUntil,reason:t.reason,exhaustedRun:t.exhaustedRun,next:t.next};if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.expectedSessionFingerprint)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0||!Number.isFinite(Date.parse(t.coolDownUntil))||!["YOLOOP_PER_RUN_CAP_REACHED","YOLOOP_SESSION_TIMEOUT"].includes(t.reason)||t.payloadHash!==Le(n)||t.receipt.schemaVersion!=="YoloopSessionRolloverReceipt/1.0"||t.receipt.runId!==t.runId||t.receipt.operationId!==t.operationId||t.receipt.idempotencyKey!==t.idempotencyKey||t.receipt.payloadHash!==t.payloadHash||t.receipt.coolDownUntil!==t.coolDownUntil||t.receipt.revision!==(t.exhaustedRun?.revision??0)||t.receipt.snapshotHash!==(t.exhaustedRun?.latestSnapshotHash??null)||t.receipt.status!=="exhausted"||t.receipt.publicSafe!==!0)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(t.expectedSessionId===null!=(t.expectedLeaseId===null)||t.expectedSessionId!==null&&!e.test(t.expectedSessionId)||t.expectedLeaseId!==null&&!e.test(t.expectedLeaseId))throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}function te(t){const e=/^[A-Za-z0-9._:-]{1,128}$/,n={runId:t.runId,previousRunId:t.previousRunId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:t.next};if(!e.test(t.runId)||!e.test(t.previousRunId)||t.runId===t.previousRunId||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<1||t.payloadHash!==me(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function ne(t,e,n){D(t);const s=e.currentSession;if(!s||Te(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const r=e.runControl;if((r?.revision??0)!==t.expectedRevision||(r?.latestSnapshotHash??null)!==t.expectedSnapshotHash||r&&r.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const o=t.exhaustedRun;if(r)if(r.status==="exhausted"){if(h(o)!==h(r))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!o||o.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=o.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:r.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:r.revision,expectedSnapshotHash:r.latestSnapshotHash,payloadHash:c.payloadHash,next:o};K(i),F(r,i)}else{const c=o?.receipts[0],i=o?.receipts[1];if(o&&(o.runId!==t.runId||o.status!=="exhausted"||o.revision!==2||o.events.length!==2||o.progressSnapshots.length!==4||o.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||o.latestSnapshotHash!==i.snapshotHash||o.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...o?{runControl:o}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function se(t){const{receipts:e,...n}=t.next;return _("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const A=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),ke={created:["running","cancelling","exhausted"],running:["pausing","cancelling","success","partial","blocked","failure","exhausted"],pausing:["paused","cancelling","failure","exhausted"],paused:["resuming","cancelling","exhausted"],resuming:["running","cancelling","failure","exhausted"],cancelling:["cancelled","failure","exhausted"]};function Ye(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:A.has(t)||t==="cancelling"?null:"cancelling"}function He(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},r={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},o=_("p220-yoloop-progress-snapshot-id-v1",{runId:r.runId,operationId:r.operationId,sequence:r.sequence,phase:r.phase}),a={...r,snapshotId:o,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...r,snapshotId:o})},c={...r,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=_("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:_("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},l={schemaVersion:"YoloopRunEvent/1.0",runId:t.current.runId,operationId:t.operationId,kind:"intent",sequence:t.current.events.length+1,revision:e,occurredAt:t.occurredAt,fromStatus:t.current.status,toStatus:t.target,reasonCodes:n,budgetDimension:null,parentEventHash:t.current.events.at(-1)?.eventHash??null,publicSafe:!0},u=_("p220-yoloop-run-event-id-v1",{runId:l.runId,operationId:l.operationId,sequence:l.sequence}),p={...l,eventId:u,eventHash:_("p220-yoloop-run-event-v1",{...l,eventId:u})},O={...t.current,revision:e,status:t.target,events:[...t.current.events,p],progressSnapshots:[...t.current.progressSnapshots,a,d],latestSnapshotHash:d.snapshotHash,receipts:[...t.current.receipts]},I={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},L=se(I),v={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:L,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",...I,payloadHash:L,next:{...O,receipts:[...O.receipts,v]}}}function K(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==se(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function F(t,e){const n=e.next,s=t?.events??[],r=t?.progressSnapshots??[],o=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==r.length+2||n.receipts.length!==o.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,r.length))!==h(r)||h(n.receipts.slice(0,o.length))!==h(o))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(A.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const l=n.progressSnapshots.at(-2)?.boundary,u=t.status===n.status&&(l==="budget"||l==="retry");if(!(ke[t.status]??[]).includes(n.status)&&!u)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t.startedAt!==n.startedAt||t.deadlineAt!==n.deadlineAt)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(h(t.predecessor)!==h(n.predecessor))throw new Error("YOLOOP_RUN_TRANSITION_INVALID")}else if(n.status!=="created")throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const a=n.progressSnapshots.at(-2),c=n.progressSnapshots.at(-1),i=n.events.at(-1),d=n.receipts.at(-1);if(!a||!c||!i||!d||a.phase!=="before"||c.phase!=="after"||a.operationId!==e.operationId||c.operationId!==e.operationId||i.operationId!==e.operationId||a.runId!==e.runId||c.runId!==e.runId||i.runId!==e.runId||a.revision!==n.revision||c.revision!==n.revision||i.revision!==n.revision||a.parentSnapshotHash!==(t?.latestSnapshotHash??null)||c.parentSnapshotHash!==a.snapshotHash||n.latestSnapshotHash!==c.snapshotHash||d.schemaVersion!=="YoloopRunTransitionReceipt/1.0"||d.runId!==e.runId||d.operationId!==e.operationId||d.idempotencyKey!==e.idempotencyKey||d.payloadHash!==e.payloadHash||d.revision!==n.revision||d.snapshotHash!==n.latestSnapshotHash||d.status!==n.status||Date.parse(n.deadlineAt)<=Date.parse(n.startedAt))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");re(a),re(c),Ue(i,s.at(-1)?.eventHash??null)}function re(t){const{snapshotHash:e,...n}=t;if(e!==_("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Ue(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==_("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function oe(t,e){return`lease-${De(`${t}:${e}`)}`}function De(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function b(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),r=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(r)?"unknown":s<=r?"expired":"active"}function ie(t){if(t.hostname!==N()||!Number.isSafeInteger(t.pid)||t.pid<=0)return"unknown";try{return process.kill(t.pid,0),"live"}catch(e){return e.code==="ESRCH"?"stale":"unknown"}}function ae(t,e,n){const s=t.lock;if(s?.ownerKind!=="client"||!s.leaseId||!s.sessionId)return!1;if(b(s,e)==="expired")return!0;const r=t.state.runControl,o=r?.progressSnapshots.at(-1),a=r?.receipts.at(-1);return r&&o&&a&&r.runId===s.sessionId&&A.has(r.status)&&o.runId===r.runId&&o.revision===r.revision&&o.status===r.status&&o.phase==="after"&&o.snapshotHash===r.latestSnapshotHash&&a.runId===r.runId&&a.revision===r.revision&&a.status===r.status&&a.snapshotHash===o.snapshotHash&&a.operationId===o.operationId&&Date.parse(o.occurredAt)>=Date.parse(s.startedAt)&&Date.parse(o.occurredAt)<=Date.parse(e)?!0:n==="stale"&&(t.state.pendingContinuationAuthorities?.length??0)===0}function Ke(t,e){const n=Y(e);return{...t,version:t.version==="1.2"?"1.2":"1.1",lastResetAt:t.lastResetAt??n.lastResetAt,storiesRunToday:t.storiesRunToday??0,iterationsToday:t.iterationsToday??0,iterationsTodayDate:t.iterationsTodayDate??n.iterationsTodayDate,tokensUsedToday:t.tokensUsedToday??0,lastRunAt:t.lastRunAt??null,coolDownUntil:t.coolDownUntil??null,totalRunsAllTime:t.totalRunsAllTime??0,totalStoriesAllTime:t.totalStoriesAllTime??0,currentSession:t.currentSession??null,...t.runControl!==void 0?{runControl:t.runControl}:{},...t.continuationPolicy!==void 0?{continuationPolicy:t.continuationPolicy}:{},...t.continuationSession!==void 0?{continuationSession:t.continuationSession}:{},...t.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:t.pendingContinuationAuthorities}:{},...t.continuationReceipts!==void 0?{continuationReceipts:t.continuationReceipts}:{},...t.continuationRecoveryReceipts!==void 0?{continuationRecoveryReceipts:t.continuationRecoveryReceipts}:{},...t.continuationReplanReceipts!==void 0?{continuationReplanReceipts:t.continuationReplanReceipts}:{},recovery_history:Array.isArray(t.recovery_history)?M(t.recovery_history):[]}}function M(t){return t.length<=B?t:t.slice(t.length-B)}const V=Object.freeze(["backlog","pending","ready","in-progress","branch-ready","diagnose","research","write-spec","create-tasks","implemented","refactor-suggest-done","property-tests-emitted","tests-validated","qa-gate-passed","memory-updated","committed","synced","pr-created","pr-reviewed","done"]),Fe=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function be(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(Fe.has(n))return 0;const s=V.indexOf(e);return s<0?V.length:V.length-1-s}const $="yoloop-round-refused-before-setup",Me="neocortex.p230.round-refused-before-setup.v1",ce=64,Ve=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),$e="reasonCode,storyId",de=/^[a-z0-9][a-z0-9-]{2,79}$/,je=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,qe=/^[a-f0-9]{64}$/;function g(t){return typeof t=="string"&&je.test(t)&&!t.includes("..")}function T(t){return typeof t=="string"&&qe.test(t)}function le(t){if(!(!Array.isArray(t)||t.length===0||t.length>ce)&&t.every(g)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function ue(t){return Ie(Me,{schemaVersion:t.schemaVersion,kind:t.kind,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:t.storyIds,refusals:t.refusals.map(e=>({storyId:e.storyId,reasonCode:e.reasonCode}))})}function Be(t){if(!t||!g(t.epicId)||!T(t.sessionId)||!T(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ce)return;const e=t.refusals.map(r=>({storyId:r?.storyId,reasonCode:r?.reasonCode})).sort((r,o)=>String(r.storyId).localeCompare(String(o.storyId)));if(!e.every(r=>g(r.storyId)&&typeof r.reasonCode=="string"&&de.test(r.reasonCode)))return;const n=e.map(r=>r.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:$,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(r=>Object.freeze({storyId:r.storyId,reasonCode:r.reasonCode})))};return Object.freeze({...s,digest:ue(s)})}function ze(t){return S(t)&&t.kind===$}function he(t,e){if(!S(t)||Object.keys(t).some(p=>!Ve.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:r,sessionId:o,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==$||!g(r)||!T(o)||!T(a)||!T(d))return!1;const l=le(c);if(!l||!Array.isArray(i)||i.length!==l.length||!i.every((p,O)=>S(p)&&Object.keys(p).sort().join(",")===$e&&p.storyId===l[O]&&typeof p.reasonCode=="string"&&de.test(p.reasonCode))||d!==ue(t))return!1;if(!e)return!0;const u=le([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&o===e.sessionId&&u!==void 0&&u.join(",")===l.join(",")}const Je="story-round-no-setup-evidence";function it(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=S(n.certificate)?n.certificate:void 0,r=S(s?.expectedTransition)?s.expectedTransition:void 0,o=Array.isArray(r?.storyLifecycle)?r.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!o||o.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const l=new Set(i.map(f=>{const w=S(t.stories[f])?t.stories[f]:void 0;return typeof w?.epic_id=="string"?w.epic_id:f.split(".")[0]}));if(l.size!==1)return;const u=[...l][0],p=S(t.epics[u])?t.epics[u]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],I=S(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,L=Array.isArray(I?.receipts)?I.receipts:[],v=Array.isArray(I?.specAcceptances)?I.specAcceptances:[],pe=f=>O.some(w=>S(w)&&w.storyId===f)||L.some(w=>S(w)&&w.storyId===f&&(w.kind==="story-worktree-lease"||w.kind==="phase-one-receipt"))||v.some(w=>S(w)&&w.storyId===f);for(const f of i){if(pe(f))return;const w=o.find(q=>S(q)&&q.storyId===f),j=S(t.stories[f])?t.stories[f]:void 0;if(!w||!j||!Number.isSafeInteger(w.remaining)||be(j.status)!==w.remaining)return}return Be({epicId:u,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:Je}))})}function S(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{Z as YOLOOP_PERSISTENCE_CAPABILITIES,Je as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,$ as YOLOOP_ROUND_REFUSED_KIND,ot as YoloopClientStateStore,Be as buildClientYoloopRoundRefusedReceipt,Ne as buildYoloopContinuationReplanPayloadHash,se as buildYoloopRunTransitionPayloadHash,Le as buildYoloopSessionRolloverPayloadHash,me as buildYoloopSuccessorRunPayloadHash,Ae as buildYoloopSuccessorTransitionPayloadHash,M as capRecoveryHistory,be as clientYoloopStoryLifecycleRemaining,Y as createDefaultCounters,rt as createDefaultState,it as deriveYoloopRoundRefusedBeforeSetupReceipt,Te as fingerprintYoloopSession,ze as isClientYoloopRoundRefusedRecord,he as isValidClientYoloopRoundRefusedReceipt};
|
|
1
|
+
import{promises as y}from"node:fs";import{existsSync as C}from"node:fs";import{createHash as x}from"node:crypto";import{join as E,dirname as Ie}from"node:path";import{hostname as N}from"node:os";import{setSecureFilePermissions as _e,setSecureDirPermissions as fe}from"../config/secure-config.js";import{RECOVERY_HISTORY_CAP as J}from"./shared-yoloop-types.js";import{applyCrossEpicContinuationReconciliation as G,epicOperationalCanonicalJson as R,epicOperationalHash as k,mutateEpicOperationalState as Y,readEpicOperationalState as m}from"../git/epic-operational-state.js";import{yoloopDomainHash as Se}from"../../../shared/dist/yoloop/canonical.js";const we=".neocortex",W="yoloop-state.json",Re="yoloop.lock",Ee="yoloop-state.mutation.lock",X="yoloop-session-rollover.json",Z="yoloop-successor-transition.json",Q=360*60*1e3,Ce=3e4,Ne=200,ee=Object.freeze(["rollover-session-v1","successor-transition-v1","continuation-replan-v1","native-launch-retry-v1"]),Te={warn:()=>{},info:()=>{},error:()=>{}};function H(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 it(t){return{lock:null,state:H(t),capabilities:ee}}class at{projectRoot;stateDir;statePath;lockPath;mutationLockPath;rolloverManifestPath;successorTransitionManifestPath;logger;constructor(e,n=Te){this.projectRoot=e,this.stateDir=E(e,we),this.statePath=E(this.stateDir,W),this.lockPath=E(this.stateDir,Re),this.mutationLockPath=E(this.stateDir,Ee),this.rolloverManifestPath=E(this.stateDir,X),this.successorTransitionManifestPath=E(this.stateDir,Z),this.logger=n}async readAll(e){const n=e??new Date().toISOString(),s=this.readCommonAuthorityIfPresent();if(s){const c=await this.reconcileCommonLock(s,n);return{lock:c.lock,state:c.state,capabilities:[...new Set([...c.capabilities,"native-launch-retry-v1"])]}}await this.cleanupOrphanTempFiles(),await this.recoverSessionRolloverIfPresent(n),await this.recoverSuccessorTransitionIfPresent(n);const[r,o]=await Promise.all([this.readLock(),this.readState(n)]);return{lock:await this.prepareLockForSnapshot(r,n),state:o,capabilities:ee}}async applyUpdate(e,n){const s=n??new Date().toISOString();if(this.readCommonAuthorityIfPresent()){for(const r of e.operations)await this.applyCommonOperation(r,s);return}await this.ensureDir(),await this.recoverSessionRolloverIfPresent(s),await this.recoverSuccessorTransitionIfPresent(s);for(const r of e.operations)await this.applyOperation(r,s)}async recordRoundRefusedBeforeSetup(e,n){const s=n??new Date().toISOString();if(!ye(e))throw new Error("YOLOOP_ROUND_REFUSED_RECEIPT_INVALID");const r=o=>{const a=(o.pendingContinuationAuthorities??[]).find(u=>u.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(!ye(e,c))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=o.continuationReceipts??[],d=i.find(u=>Ge(u)&&u.idempotencyKey===e.idempotencyKey);if(d){if(R(d)===R(e))return"unchanged";throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}return{...o,continuationReceipts:[...i.slice(-63),e]}};if(this.readCommonAuthorityIfPresent()){const{document:o,operational:a}=m(this.projectRoot),c=Object.keys(a.identities);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");return r(a.yoloop.state)==="unchanged"?"unchanged":(await Y(this.projectRoot,{identityHash:c[0],expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},i=>{const d=r(i.yoloop.state);d!=="unchanged"&&(i.yoloop={...i.yoloop,state:d})}),"recorded")}return await this.ensureDir(),this.withMutationLock(async()=>{const o=r(await this.readState(s));return o==="unchanged"?"unchanged":(await this.writeState(o),"recorded")})}async requestRunTransition(e,n){const s=n??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(()=>this.transitionRun(e,s))}async requestLifecycleAction(e,n={},s){const r=s??new Date().toISOString();return await this.ensureDir(),this.withMutationLock(async()=>{const a=(await this.readState(r)).runControl;if(!a)throw new Error("YOLOOP_RUN_TRANSITION_INVALID");const c=Date.parse(r).toString(36),i=n.operationId??`op-${e}-${c}`,d=n.idempotencyKey??`idem-${e}-${c}`,u=a.receipts.find(p=>p.operationId===i||p.idempotencyKey===d);if(u){if(u.operationId===i&&u.idempotencyKey===d)return u;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}const l=Ue(a.status,e);if(!l)throw new Error(A.has(a.status)?"YOLOOP_RUN_TERMINAL":"YOLOOP_RUN_TRANSITION_INVALID");return this.transitionRun(De({current:a,action:e,target:l,operationId:i,idempotencyKey:d,occurredAt:r}),r)})}async applyOperation(e,n){switch(e.type){case"acquire_lock":await this.withMutationLock(()=>this.acquireLock(e.lock,n));return;case"release_lock":await this.withMutationLock(()=>this.releaseLock(e));return;case"write_state":await this.withMutationLock(async()=>{const s=await this.readState(n),{runControl:r,...o}=e.state;await this.writeState({...o,...s.runControl?{version:"1.2",runControl:s.runControl}:{}})});return;case"advance_epic":await this.advanceEpic(e.nextEpicIndex,e.nextEpicId,n);return;case"no_op":this.logger.info({event:"yoloop_noop"},"yoloop server sent no-op");return;case"reserve_continuation_authority":await this.reserveContinuationAuthority(e.authority,n);return;case"acknowledge_continuation_authority":await this.acknowledgeContinuationAuthority(e.idempotencyKey,e.receipt,n);return;case"repair_continuation_authority":await this.repairContinuationAuthority(e.beforeHash,e.authority,e.receipt,n);return;case"switch_continuation_policy":await this.switchContinuationPolicy(e.policy,e.session,n);return;case"transition_run":await this.requestRunTransition(e,n);return;case"start_successor_run":await this.withMutationLock(()=>this.startSuccessorRun(e,n));return;case"commit_successor_transition":await this.withMutationLock(()=>this.commitSuccessorTransition(e,n));return;case"rollover_session":await this.withMutationLock(()=>this.rolloverSession(e,n));return;case"replan_continuation_session":await this.withMutationLock(()=>this.replanContinuationSession(e,n));return;case"reconcile_cross_epic_continuation":await G(this.projectRoot,e);return;case"recovery_attempted":await this.appendRecoveryAttempt(e.attempt,n);return;case"recovery_resolved":await this.resolveRecoveryAttempt(e.attempt_id,e.outcome,n);return;default:{const s=e;throw this.logger.error({event:"yoloop_unknown_op",op:s},"unknown yoloop operation rejected"),new Error("YOLOOP_STATE_OPERATION_UNSUPPORTED")}}}readCommonAuthorityIfPresent(){try{const e=m(this.projectRoot).operational;if(e.activeJournal!==null)throw new Error("epic-operational-recovery-required");return e}catch(e){if(e instanceof Error&&["git-lifecycle-runtime-missing","epic-operational-store-missing"].includes(e.message)||e instanceof Error&&e.message==="git-lifecycle-common-dir-invalid"&&!C(E(this.projectRoot,".git")))return null;throw e}}async reconcileCommonLock(e,n){const s=e.yoloop.lock;if(!s||s.ownerKind!=="client")return e.yoloop;const r=g(s);if(!de(e.yoloop,n,r))return{...e.yoloop,lock:{...s,ownerPidState:r==="live"?"live":"unknown"}};const{document:o,operational:a}=m(this.projectRoot);if(R(a.yoloop.lock)!==R(s))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const c=Object.values(a.identities).filter(d=>d.epicId===s.currentEpicId);if(c.length!==1)throw new Error("epic-operational-identity-mismatch");const{value:i}=await Y(this.projectRoot,{identityHash:c[0].identityHash,expectedRevision:o.revision,expectedWriterEpoch:a.writerEpoch},d=>{if(d.activeJournal!==null||R(d.yoloop.lock)!==R(s)||!de(d.yoloop,n,g(s)))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");const u={...d.yoloop,lock:null};return d.yoloop=u,u});return i}async applyCommonOperation(e,n){if(e.type==="no_op")return;if(e.type==="reconcile_cross_epic_continuation"){await G(this.projectRoot,e);return}const{document:s,operational:r}=m(this.projectRoot),o=Object.keys(r.identities);if(o.length!==1)throw new Error("epic-operational-identity-mismatch");const a=o[0];await Y(this.projectRoot,{identityHash:a,expectedRevision:s.revision,expectedWriterEpoch:r.writerEpoch},c=>{const i=c.yoloop.state;let d=c.yoloop.lock,u=i;switch(e.type){case"acquire_lock":{if(d){if(d.sessionId===e.lock.sessionId&&d.leaseId===e.lock.leaseId&&d.hostname===N()&&d.pid===process.pid)return;throw new Error("YOLOOP_LOCK_HELD")}d={...e.lock,pid:process.pid,hostname:N(),ownerKind:"client",leaseId:e.lock.leaseId??ae(e.lock.sessionId,n),leaseState:"active",leaseAcquiredAt:e.lock.leaseAcquiredAt??n,leaseDurationMs:e.lock.leaseDurationMs??Q,leaseExpiresAt:e.lock.leaseExpiresAt??e.lock.ttlExpiresAt};break}case"release_lock":{if(e.expectedSessionId&&d?.sessionId!==e.expectedSessionId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseId&&d?.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedLeaseExpiresAt&&(d?.leaseExpiresAt??d?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(e.expectedRunId&&i.runControl?.runId!==e.expectedRunId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");d=null;break}case"write_state":{const{runControl:l,...p}=e.state;u={...p,...i.runControl?{version:"1.2",runControl:i.runControl}:{}};break}case"advance_epic":{if(!i.currentSession)return;u={...i,currentSession:{...i.currentSession,currentEpicIndex:e.nextEpicIndex}};break}case"reserve_continuation_authority":{const l=i.pendingContinuationAuthorities??[],p=String(e.authority.idempotencyKey??""),O=l.find(_=>_.idempotencyKey===p);if(O){if(R(O)!==R(e.authority))throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT");return}if(!p||l.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");u={...i,pendingContinuationAuthorities:[...l,e.authority]};break}case"acknowledge_continuation_authority":{const l=i.pendingContinuationAuthorities??[],p=l.find(_=>_.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");u={...i,pendingContinuationAuthorities:l.filter(_=>_!==p),continuationReceipts:[...O,e.receipt]};break}case"repair_continuation_authority":{const l=i.pendingContinuationAuthorities??[];if(l.length!==1||k("p208-legacy-authority-before-v1",l[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");u={...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");u={...i,continuationPolicy:e.policy,continuationSession:e.session};break}case"transition_run":case"start_successor_run":{const l=i.runControl;if(!l||l.revision!==e.expectedRevision||l.latestSnapshotHash!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");u={...i,version:"1.2",runControl:e.next};break}case"commit_successor_transition":u={...e.state,version:"1.2",runControl:e.successor.next};break;case"rollover_session":u=e.next,d=null;break;case"replan_continuation_session":{const l=i.pendingContinuationAuthorities??[];if(k("p222-yoloop-replan-session-v1",i.continuationSession??null)!==e.expectedSessionHash||k("p222-yoloop-replan-pending-v1",l)!==e.expectedPendingHash||l.length>1||l.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");u={...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...p,e.receipt]};break}case"recovery_attempted":u={...i,recovery_history:j([...i.recovery_history??[],e.attempt])};break;case"recovery_resolved":{const l=[...i.recovery_history??[]],p=l.findIndex(O=>O.recovery_step_id_tokenized===e.attempt_id);p>=0&&(l[p]={...l[p],outcome:e.outcome,finished_at:n}),u={...i,recovery_history:l};break}default:{const l=e;throw new Error(`YOLOOP_STATE_OPERATION_UNSUPPORTED:${String(l)}`)}}c.yoloop={...c.yoloop,lock:d,state:u}})}async reserveContinuationAuthority(e,n){const s=await this.readState(n),r=s.pendingContinuationAuthorities??[],o=typeof e.idempotencyKey=="string"?e.idempotencyKey:"";if(!o)throw new Error("YOLOOP_CONTINUATION_AUTHORITY_INVALID");const a=r.find(c=>c.idempotencyKey===o);if(a){if(h(a)===h(e))return;throw new Error("YOLOOP_CONTINUATION_AUTHORITY_CONFLICT")}if(r.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED");await this.writeState({...s,pendingContinuationAuthorities:[...r,e]})}async acknowledgeContinuationAuthority(e,n,s){const r=await this.readState(s),o=r.pendingContinuationAuthorities??[],a=o.findIndex(u=>u.idempotencyKey===e);if(a<0)throw new Error("YOLOOP_CONTINUATION_RECEIPT_ORPHAN");const c=o[a];if(n.idempotencyKey!==e||n.sessionId!==c.sessionId||JSON.stringify(n.storyIds)!==JSON.stringify(c.storyIds))throw new Error("YOLOOP_CONTINUATION_RECEIPT_MISMATCH");const i=o.filter((u,l)=>l!==a),d=r.continuationReceipts??[];await this.writeState({...r,pendingContinuationAuthorities:i,continuationReceipts:[...d.slice(-63),n]})}async repairContinuationAuthority(e,n,s,r){const o=await this.readState(r),a=o.pendingContinuationAuthorities??[],c=o.continuationRecoveryReceipts??[],i=typeof s.idempotencyKey=="string"?s.idempotencyKey:"",d=c.find(p=>p.idempotencyKey===i);if(d){if(h(d)===h(s))return;throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_CONFLICT")}if(a.length!==1||I("p208-legacy-authority-before-v1",a[0])!==e)throw new Error("YOLOOP_CONTINUATION_RECOVERY_BEFORE_MISMATCH");const u=I("p208-legacy-authority-after-v1",n);if(s.beforeHash!==e||s.afterHash!==u)throw new Error("YOLOOP_CONTINUATION_RECOVERY_HASH_MISMATCH");const l={...s};if(delete l.idempotencyKey,!i||I("p208-legacy-authority-recovery-receipt-v1",l)!==i)throw new Error("YOLOOP_CONTINUATION_RECOVERY_RECEIPT_INVALID");await this.writeState({...o,pendingContinuationAuthorities:[n],continuationRecoveryReceipts:[...c.slice(-63),s]})}async switchContinuationPolicy(e,n,s){const r=await this.readState(s);if(r.currentSession||(r.pendingContinuationAuthorities?.length??0)>0)throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");try{await y.copyFile(this.statePath,`${this.statePath}.policy-backup`)}catch(o){if(o.code!=="ENOENT")throw o}await this.writeState({...r,continuationPolicy:e,continuationSession:n})}usesCommonAuthority(){return this.readCommonAuthorityIfPresent()!==null}async readLegacyAdoptionSource(){let e=null;try{e=await y.readFile(this.statePath)}catch(n){if(n.code!=="ENOENT")throw n}return{sourceBytes:e,lockPresent:C(this.lockPath),rolloverManifestPresent:C(this.rolloverManifestPath),successorTransitionManifestPresent:C(this.successorTransitionManifestPath)}}async commitLegacyPolicyAdoption(e){return await this.ensureDir(),this.withMutationLock(async()=>{let n;try{n=await y.readFile(this.statePath)}catch(r){throw r.code==="ENOENT"?new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT"):r}if(x("sha256").update(n).digest("hex")!==e.sourceSha256)throw new Error("YOLOOP_LEGACY_ADOPTION_CAS_CONFLICT");if(C(this.lockPath)||C(this.rolloverManifestPath)||C(this.successorTransitionManifestPath))throw new Error("YOLOOP_POLICY_SWITCH_ACTIVE");const s=Buffer.from(e.nextBytes,"utf8");return await this.writeBytesAtomically(`${this.statePath}.policy-backup`,n),await this.writeBytesAtomically(this.statePath,s),{resultSha256:x("sha256").update(s).digest("hex")}})}async writeBytesAtomically(e,n){const s=`${e}.tmp.${process.pid}.${Date.now()}`;try{const r=await y.open(s,"w",384);try{await r.writeFile(n),await r.sync()}finally{await r.close()}this.trySetFilePerms(s),await y.rename(s,e),await this.syncStateDirectory()}catch(r){throw await y.unlink(s).catch(()=>{}),r}}async replanContinuationSession(e,n){const{type:s,payloadHash:r,receipt:o,...a}=e;if(Le(a)!==e.payloadHash||!te(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:I("p222-yoloop-replan-session-v1",e.nextSession),retiredAuthorityHash:e.expectedPendingHash,retiredAuthorityCount:e.expectedPendingHash===I("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 u=i.continuationReplanReceipts??[],l=u.find(_=>_.idempotencyKey===e.idempotencyKey||_.operationId===e.operationId);if(l){if(h(l)===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(!te(p)||I("p222-yoloop-replan-session-v1",p)!==e.expectedSessionHash||I("p222-yoloop-replan-pending-v1",O)!==e.expectedPendingHash||O.length>1||O.some(_=>_.delegated!==!1||_.sessionId!==p.sessionId||!_.certificate||_.certificate.sessionId!==p.sessionId))throw new Error("YOLOOP_CONTINUATION_REPLAN_AUTHORITY_CONFLICT");await this.writeState({...i,continuationSession:e.nextSession,pendingContinuationAuthorities:[],continuationReplanReceipts:[...u.slice(-63),c]})}async appendRecoveryAttempt(e,n){const s=await this.readState(n),r=s.recovery_history??[];if(r.some(i=>i.attempted_at===e.attempted_at&&i.story_id===e.story_id)){this.logger.warn({event:"recovery_attempted_duplicate",story_id:e.story_id},"duplicate recovery_attempted op; skipping");return}const a=j([...r,e]),c={...s,recovery_history:a};await this.writeState(c),this.logger.info({event:"recovery_attempted_persisted",story_id:e.story_id,history_size:a.length},"recovery attempt persisted")}async resolveRecoveryAttempt(e,n,s){const r=await this.readState(s),o=r.recovery_history??[],a=o.findIndex(u=>u.recovery_step_id_tokenized===e);if(a===-1){this.logger.warn({event:"recovery_resolve_orphan",attempt_id:e},"recovery_resolved op had no matching attempt; skipping");return}const c=o[a];if(c.outcome===n&&c.finished_at){this.logger.info({event:"recovery_resolved_duplicate",attempt_id:e,outcome:n},"duplicate recovery_resolved op; skipping");return}const i=o.slice();i[a]={...c,outcome:n,finished_at:s};const d={...r,recovery_history:i};await this.writeState(d),this.logger.info({event:"recovery_resolved_persisted",attempt_id:e,outcome:n},"recovery attempt resolved")}async acquireLock(e,n){const s={...e,pid:process.pid,hostname:N(),ownerKind:"client",startedAt:e.startedAt||n,leaseId:e.leaseId??ae(e.sessionId,n),leaseState:"active",leaseAcquiredAt:e.leaseAcquiredAt??n,leaseDurationMs:e.leaseDurationMs??Q,leaseExpiresAt:e.leaseExpiresAt??e.ttlExpiresAt},r=JSON.stringify(s,null,2);try{const o=await y.open(this.lockPath,"wx");try{await o.writeFile(r,"utf8")}finally{await o.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired",pid:s.pid,sessionId:s.sessionId},"yoloop lock acquired");return}catch(o){const a=o;if(a.code!=="EEXIST")throw this.logger.error({event:"yoloop_lock_acquire_error",err:a.message},"failed to acquire yoloop lock"),o;const c=await this.readLock();if(c&&this.isSameClientSessionLock(c,s)){this.logger.info({event:"yoloop_lock_acquire_duplicate",sessionId:s.sessionId},"duplicate acquire_lock for current yoloop session; treating as no-op");return}if(!await this.maybeRecoverOrphanLock(n))throw this.logger.warn({event:"yoloop_lock_held"},"yoloop lock held by another live process"),o;const d=await y.open(this.lockPath,"wx");try{await d.writeFile(r,"utf8")}finally{await d.close()}this.trySetFilePerms(this.lockPath),this.logger.info({event:"yoloop_lock_acquired_after_recovery",pid:s.pid},"yoloop lock acquired after orphan recovery")}}async releaseLock(e){const n=await this.readState(new Date().toISOString()),s=await this.readLock();if(n.runControl){if(!e.expectedRunId||!e.expectedSessionId||!e.expectedLeaseId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(e.expectedRunId!==n.runControl.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT")}if(e.expectedSessionId&&e.expectedSessionId!==s?.sessionId||e.expectedLeaseId&&e.expectedLeaseId!==s?.leaseId||e.expectedLeaseExpiresAt&&(s?.leaseExpiresAt??s?.ttlExpiresAt)!==e.expectedLeaseExpiresAt)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");try{await y.unlink(this.lockPath),this.logger.info({event:"yoloop_lock_released"},"yoloop lock released")}catch(r){const o=r;if(o.code==="ENOENT"){this.logger.info({event:"yoloop_lock_release_noop"},"yoloop lock release noop (file absent)");return}this.logger.warn({event:"yoloop_lock_release_error",err:o.message},"unexpected error releasing yoloop lock")}}async readLock(){try{const e=await y.readFile(this.lockPath,"utf8"),n=JSON.parse(e),s=n.currentEpicId??n.epicId??"";return{pid:n.pid??0,hostname:n.hostname??"",...n.ownerKind?{ownerKind:n.ownerKind}:{},...n.ownerPidState?{ownerPidState:n.ownerPidState}:{},...typeof n.leaseId=="string"?{leaseId:n.leaseId}:{},...n.leaseState?{leaseState:n.leaseState}:{},...typeof n.leaseAcquiredAt=="string"?{leaseAcquiredAt:n.leaseAcquiredAt}:{},...typeof n.leaseDurationMs=="number"?{leaseDurationMs:n.leaseDurationMs}:{},...typeof n.leaseExpiresAt=="string"?{leaseExpiresAt:n.leaseExpiresAt}:{},startedAt:n.startedAt??"",sessionId:n.sessionId??"",mode:n.mode??"epic-id",inputPath:n.inputPath??"",epicQueue:n.epicQueue??(s?[s]:[]),currentEpicIndex:n.currentEpicIndex??0,currentEpicId:s,ttlExpiresAt:n.ttlExpiresAt??"",epicId:n.epicId??s}}catch{return null}}async readState(e){try{const n=await y.readFile(this.statePath,"utf8"),s=JSON.parse(n);return Me(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"),H(e)}}async writeState(e){const n=`${this.statePath}.tmp.${process.pid}.${Date.now()}`,s=JSON.stringify(e,null,2);try{const r=await y.open(n,"w",384);try{await r.writeFile(s,"utf8"),await r.sync()}finally{await r.close()}this.trySetFilePerms(n),await y.rename(n,this.statePath),await this.syncStateDirectory()}catch(r){const o=r;this.logger.error({event:"yoloop_state_write_error",err:o.message},"failed to write yoloop state");try{await y.unlink(n)}catch{}throw r}}async rolloverSession(e,n){F(e);const s=await this.readRolloverManifest();if(s){if(Ye(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSessionRollover(s.operation,n);return}else if(s.phase==="prepared")throw new Error("YOLOOP_SESSION_ROLLOVER_CONFLICT")}const r=await this.readState(n),o=await this.readLock();re(e,r,o),await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSessionRollover(e,n)}async completePreparedSessionRollover(e,n){const s=await this.readState(n);let r=h(s)===h(e.next);if(!r){const a=await this.readLock();re(e,s,a),await this.writeState(e.next),r=!0}const o=await this.readLock();if(e.expectedSessionId===null||e.expectedLeaseId===null){if(e.expectedSessionId!==null||e.expectedLeaseId!==null||o)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(o){if(o.sessionId!==e.expectedSessionId||o.leaseId!==e.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await y.unlink(this.lockPath),await this.syncStateDirectory()}else if(!r)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");await this.writeRolloverManifest({schemaVersion:"YoloopSessionRolloverManifest/1.0",phase:"applied",operation:e}),this.logger.info({event:"yoloop_session_rollover_applied",runId:e.runId,operationId:e.operationId,coolDownUntil:e.coolDownUntil},"yoloop per-run-cap session rollover applied")}async recoverSessionRolloverIfPresent(e){try{await y.access(this.rolloverManifestPath)}catch(n){if(n.code==="ENOENT")return;throw n}await this.ensureDir(),await this.withMutationLock(async()=>{const n=await this.readRolloverManifest();n?.phase==="prepared"&&await this.completePreparedSessionRollover(n.operation,e)})}async readRolloverManifest(){try{const e=JSON.parse(await y.readFile(this.rolloverManifestPath,"utf8"));if(e.schemaVersion!=="YoloopSessionRolloverManifest/1.0"||e.phase!=="prepared"&&e.phase!=="applied"||!e.operation||e.operation.type!=="rollover_session")throw new Error("YOLOOP_SESSION_ROLLOVER_MANIFEST_CORRUPT");return F(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){U(e);const s=await this.readSuccessorTransitionManifest();if(s){if(Pe(s.operation,e)){if(s.operation.payloadHash!==e.payloadHash)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT");if(s.phase==="applied")return;await this.completePreparedSuccessorTransition(s.operation,n);return}if(s.phase==="prepared")throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}const r=await this.readState(n);if(D(e,r)){await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"applied",operation:e});return}ne(e,r),await this.writeSuccessorTransitionManifest({schemaVersion:"YoloopSuccessorTransitionManifest/1.0",phase:"prepared",operation:e}),await this.completePreparedSuccessorTransition(e,n)}async completePreparedSuccessorTransition(e,n){let s=await this.readState(n);if(!D(e,s)){h(s.runControl)===h(e.successor.next)||(await this.startSuccessorRun(e.successor,n),s=await this.readState(n));const o=ke(e,s);await this.writeState(o),s=await this.readState(n)}if(!D(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 U(e.operation),e}catch(e){if(e.code==="ENOENT")return null;throw e.message==="YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT"?e:new Error("YOLOOP_SUCCESSOR_TRANSITION_MANIFEST_CORRUPT")}}async writeSuccessorTransitionManifest(e){const n=`${this.successorTransitionManifestPath}.tmp.${process.pid}.${Date.now()}`,s=await y.open(n,"w",384);try{await s.writeFile(JSON.stringify(e,null,2),"utf8"),await s.sync()}finally{await s.close()}this.trySetFilePerms(n),await y.rename(n,this.successorTransitionManifestPath),await this.syncStateDirectory()}async advanceEpic(e,n,s){const r=await this.readState(s);if(!r.currentSession){this.logger.warn({event:"yoloop_advance_no_session",nextEpicId:n},"advance_epic with no active session; skipping");return}const o={...r,currentSession:{...r.currentSession,currentEpicIndex:e}};await this.writeState(o),this.logger.info({event:"yoloop_epic_advance",nextEpicId:n,nextIndex:e},"yoloop advanced to next epic")}async ensureDir(){try{await y.mkdir(this.stateDir,{recursive:!0}),this.trySetDirPerms(this.stateDir)}catch(e){const n=e;throw this.logger.error({event:"yoloop_mkdir_error",err:n.message,path:this.stateDir},"failed to ensure .neocortex/ directory"),e}}async syncStateDirectory(){try{const e=await y.open(this.stateDir,"r");try{await e.sync()}finally{await e.close()}}catch(e){const n=e.code;if(n!=="EINVAL"&&n!=="EISDIR"&&n!=="ENOTSUP"&&n!=="EPERM")throw e}}async withMutationLock(e){let n=null;for(let s=0;s<Ne;s+=1)try{n=await y.open(this.mutationLockPath,"wx",384),await n.writeFile(JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()})),await n.sync();break}catch(r){if(r.code!=="EEXIST")throw r;try{const o=await y.stat(this.mutationLockPath);if(Date.now()-o.mtimeMs>Ce){await y.unlink(this.mutationLockPath);continue}}catch{continue}await new Promise(o=>setTimeout(o,5))}if(!n)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");try{return await e()}finally{await n.close().catch(()=>{}),await y.unlink(this.mutationLockPath).catch(()=>{})}}async transitionRun(e,n){K(e);const s=await this.readState(n),r=s.runControl,o=r?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(o){if(o.operationId===e.operationId&&o.idempotencyKey===e.idempotencyKey&&o.payloadHash===e.payloadHash)return o;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(r&&r.runId!==e.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.revision??0)!==e.expectedRevision)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if((r?.latestSnapshotHash??null)!==e.expectedSnapshotHash)throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT");M(r,e);const i=e.next.receipts.at(-1);if(!i)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");return await this.writeState({...s,version:"1.2",runControl:e.next}),this.logger.info({event:"yoloop_run_transition_committed",runId:e.runId,operationId:e.operationId,revision:i.revision,status:i.status},"yoloop run transition committed"),i}async startSuccessorRun(e,n){se(e);const s=await this.readState(n),r=s.runControl,o={schemaVersion:"YoloopRunPredecessor/1.0",runId:e.previousRunId,revision:e.expectedRevision,snapshotHash:e.expectedSnapshotHash,successorOperationId:e.operationId,publicSafe:!0},a=r?.receipts.find(d=>d.operationId===e.operationId||d.idempotencyKey===e.idempotencyKey);if(a){if(a.operationId===e.operationId&&a.idempotencyKey===e.idempotencyKey&&e.next.receipts.at(-1)?.payloadHash===a.payloadHash&&h(r?.predecessor)===h(o))return a;throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}if(!r||r.runId!==e.previousRunId||!["exhausted","success"].includes(r.status)||r.revision!==e.expectedRevision||r.latestSnapshotHash!==e.expectedSnapshotHash||s.currentSession!==null)throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const c=e.next.receipts.at(-1);if(!c||h(e.next.predecessor)!==h(o))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT");const i={type:"transition_run",runId:e.runId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,expectedRevision:0,expectedSnapshotHash:null,payloadHash:c.payloadHash,next:e.next};return K(i),M(void 0,i),await this.writeState({...s,version:"1.2",runControl:e.next}),c}trySetFilePerms(e){try{_e(e)}catch{}}trySetDirPerms(e){try{fe(e)}catch{}}async prepareLockForSnapshot(e,n){if(!e||e.ownerKind!=="client")return e;const s=V(e,n);return s?this.withMutationLock(async()=>{const r=await this.readLock();return r?R(r)!==R(e)||V(r,n)!==s?r.ownerKind==="client"?ce(r,n):r:(await this.removeRecoveredLock(),this.logger.warn({event:"yoloop_client_lock_recovered",reason:s},"stale client-owned yoloop lock recovered before snapshot echo"),null):null}):ce(e,n)}async maybeRecoverOrphanLock(e){const n=await this.readLock();if(!n)return!0;const s=V(n,e);return s?(await this.removeRecoveredLock(),this.logger.warn({event:"yoloop_orphan_lock_recovered",reason:s},"orphan yoloop lock recovered"),!0):!1}async removeRecoveredLock(){try{await y.unlink(this.lockPath)}catch(e){if(e.code!=="ENOENT")throw e}}isSameClientSessionLock(e,n){return e.ownerKind==="client"&&e.sessionId===n.sessionId&&e.pid===process.pid&&e.hostname===N()}async cleanupOrphanTempFiles(){try{const e=Ie(this.statePath),n=await y.readdir(e),s=[`${W}.tmp.`,`${X}.tmp.`,`${Z}.tmp.`],r=n.filter(o=>s.some(a=>o.startsWith(a)));for(const o of r)try{await y.unlink(E(e,o))}catch{}}catch{}}}function h(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${t.map(h).join(",")}]`:`{${Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${h(n)}`).join(",")}}`}function I(t,e){return x("sha256").update(`${t}\0${h(e)}`).digest("hex")}function Le(t){return I("p222-yoloop-continuation-replan-v1",t)}function te(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===I("p205-yoloop-session-v1",n)}function me(t){return I("p9390812898200217364-yoloop-session-v1",t)}function Ae(t){return I("p9390812898200217364-yoloop-rollover-v1",t)}function ge(t){return I("p9390812898200217364-yoloop-successor-run-v1",t)}function ve(t){return I("p9046281030721413419-yoloop-successor-transition-v1",t)}function Pe(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function U(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;se(t.successor);const n={operationId:t.operationId,idempotencyKey:t.idempotencyKey,successor:t.successor,state:t.state,...t.acknowledgement?{acknowledgement:t.acknowledgement}:{},...t.reservation?{reservation:t.reservation}:{}},s=t.acknowledgement?.idempotencyKey,r=t.acknowledgement?.receipt.idempotencyKey,o=t.reservation?.authority.idempotencyKey;if(t.successor.type!=="start_successor_run"||!e.test(t.operationId)||!e.test(t.idempotencyKey)||t.operationId!==t.successor.operationId||t.idempotencyKey!==t.successor.idempotencyKey||!/^[a-f0-9]{64}$/.test(t.payloadHash)||t.payloadHash!==ve(n)||Buffer.byteLength(h(n),"utf8")>1048576||t.acknowledgement!==void 0&&(t.acknowledgement.type!=="acknowledge_continuation_authority"||typeof s!="string"||!e.test(s)||r!==s)||t.reservation!==void 0&&(t.reservation.type!=="reserve_continuation_authority"||typeof o!="string"||!e.test(o))||s!==void 0&&o===s)throw new Error("YOLOOP_SUCCESSOR_TRANSITION_CONFLICT")}function ne(t,e){if(U(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")}xe(t,e)}function xe(t,e){const n=e.pendingContinuationAuthorities??[],s=e.continuationReceipts??[],r=t.acknowledgement;if(r){const d=n.find(p=>p.idempotencyKey===r.idempotencyKey);if(!d||r.receipt.sessionId!==d.sessionId||h(r.receipt.storyIds)!==h(d.storyIds))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const u=n.filter(p=>p.idempotencyKey!==r.idempotencyKey),l=[...s.slice(-63),r.receipt];if(h(t.state.pendingContinuationAuthorities??[])!==h(u)||h(t.state.continuationReceipts??[])!==h(l))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT")}else if(h(t.state.pendingContinuationAuthorities??[])!==h(n)||h(t.state.continuationReceipts??[])!==h(s))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");const o=t.reservation?.authority;if(!o)return;const a=String(o.idempotencyKey??""),c=t.state.pendingContinuationAuthorities??[],i=c.find(d=>d.idempotencyKey===a);if(i&&h(i)!==h(o))throw new Error("YOLOOP_SUCCESSOR_TRANSITION_AUTHORITY_CONFLICT");if(!i&&c.length>=64)throw new Error("YOLOOP_PENDING_AUTHORITY_CAPACITY_EXCEEDED")}function ke(t,e){ne(t,e);const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];return n&&!s.some(r=>r.idempotencyKey===n.idempotencyKey)&&s.push(n),{...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}}}function D(t,e){const n=t.reservation?.authority,s=[...t.state.pendingContinuationAuthorities??[]];n&&!s.some(o=>o.idempotencyKey===n.idempotencyKey)&&s.push(n);const r={...t.state,version:"1.2",runControl:t.successor.next,...n||t.state.pendingContinuationAuthorities!==void 0?{pendingContinuationAuthorities:s}:{}};return h(e)===h(r)}function Ye(t,e){return t.operationId===e.operationId&&t.idempotencyKey===e.idempotencyKey}function F(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!==Ae(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 se(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!==ge(n))throw new Error("YOLOOP_RUN_SUCCESSOR_CONFLICT")}function re(t,e,n){F(t);const s=e.currentSession;if(!s||me(s)!==t.expectedSessionFingerprint)throw new Error("YOLOOP_SESSION_ROLLOVER_SESSION_CONFLICT");const r=e.runControl;if((r?.revision??0)!==t.expectedRevision||(r?.latestSnapshotHash??null)!==t.expectedSnapshotHash||r&&r.runId!==t.runId)throw new Error("YOLOOP_RUN_REVISION_CONFLICT");if(t.expectedSessionId===null||t.expectedLeaseId===null){if(n)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT")}else if(!n||n.sessionId!==t.expectedSessionId||n.leaseId!==t.expectedLeaseId)throw new Error("YOLOOP_SESSION_ROLLOVER_LOCK_CONFLICT");const o=t.exhaustedRun;if(r)if(r.status==="exhausted"){if(h(o)!==h(r))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}else{if(!o||o.status!=="exhausted")throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const c=o.receipts.at(-1);if(!c)throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT");const i={type:"transition_run",runId:r.runId,operationId:c.operationId,idempotencyKey:c.idempotencyKey,expectedRevision:r.revision,expectedSnapshotHash:r.latestSnapshotHash,payloadHash:c.payloadHash,next:o};K(i),M(r,i)}else{const c=o?.receipts[0],i=o?.receipts[1];if(o&&(o.runId!==t.runId||o.status!=="exhausted"||o.revision!==2||o.events.length!==2||o.progressSnapshots.length!==4||o.receipts.length!==2||c?.runId!==t.runId||c.revision!==1||c.status!=="created"||i?.runId!==t.runId||i.revision!==2||i.status!=="exhausted"||i.operationId!==`${t.operationId}:run`||i.idempotencyKey!==`${t.idempotencyKey}:run`||o.latestSnapshotHash!==i.snapshotHash||o.predecessor!==void 0))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}const a={...e,version:"1.2",coolDownUntil:t.coolDownUntil,currentSession:null,...o?{runControl:o}:{}};if(h(a)!==h(t.next))throw new Error("YOLOOP_SESSION_ROLLOVER_STATE_CONFLICT")}function oe(t){const{receipts:e,...n}=t.next;return I("p220-yoloop-run-transition-payload-v1",{runId:t.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.expectedRevision,expectedSnapshotHash:t.expectedSnapshotHash,next:n})}const A=new Set(["success","partial","blocked","failure","exhausted","cancelled"]),He={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 Ue(t,e){return e==="pause"?t==="running"?"pausing":null:e==="resume"?t==="paused"?"resuming":null:A.has(t)||t==="cancelling"?null:"cancelling"}function De(t){const e=t.current.revision+1,n=t.action==="cancel"?["YOLOOP_RUN_CANCEL_REQUESTED"]:[],s={schemaVersion:"YoloopOperationalBudgetSummary/1.0",limits:t.current.operationalBudget.limits,usage:t.current.usage,exhaustedDimension:null},r={schemaVersion:"ProgressSnapshot/1.0",runId:t.current.runId,sequence:t.current.progressSnapshots.length+1,revision:e,operationId:t.operationId,boundary:t.action,phase:"before",status:t.current.status,occurredAt:t.occurredAt,parentSnapshotHash:t.current.latestSnapshotHash,budget:s,reasonCodes:n,publicSafe:!0},o=I("p220-yoloop-progress-snapshot-id-v1",{runId:r.runId,operationId:r.operationId,sequence:r.sequence,phase:r.phase}),a={...r,snapshotId:o,snapshotHash:I("p220-yoloop-progress-snapshot-v1",{...r,snapshotId:o})},c={...r,sequence:a.sequence+1,phase:"after",status:t.target,parentSnapshotHash:a.snapshotHash},i=I("p220-yoloop-progress-snapshot-id-v1",{runId:c.runId,operationId:c.operationId,sequence:c.sequence,phase:c.phase}),d={...c,snapshotId:i,snapshotHash:I("p220-yoloop-progress-snapshot-v1",{...c,snapshotId:i})},u={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},l=I("p220-yoloop-run-event-id-v1",{runId:u.runId,operationId:u.operationId,sequence:u.sequence}),p={...u,eventId:l,eventHash:I("p220-yoloop-run-event-v1",{...u,eventId:l})},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]},_={runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,expectedRevision:t.current.revision,expectedSnapshotHash:t.current.latestSnapshotHash,next:O},L=oe(_),P={schemaVersion:"YoloopRunTransitionReceipt/1.0",runId:t.current.runId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,payloadHash:L,revision:e,snapshotHash:d.snapshotHash,status:t.target};return{type:"transition_run",..._,payloadHash:L,next:{...O,receipts:[...O.receipts,P]}}}function K(t){const e=/^[A-Za-z0-9._:-]{1,128}$/;if(!e.test(t.runId)||!e.test(t.operationId)||!e.test(t.idempotencyKey)||!/^[a-f0-9]{64}$/.test(t.payloadHash)||!Number.isSafeInteger(t.expectedRevision)||t.expectedRevision<0)throw new Error("YOLOOP_RUN_OPERATION_CONFLICT");if(t.payloadHash!==oe(t))throw new Error("YOLOOP_RUN_OPERATION_CONFLICT")}function M(t,e){const n=e.next,s=t?.events??[],r=t?.progressSnapshots??[],o=t?.receipts??[];if(n.schemaVersion!=="YoloopRunControl/1.0"||n.runId!==e.runId||n.revision!==e.expectedRevision+1||n.events.length!==s.length+1||n.progressSnapshots.length!==r.length+2||n.receipts.length!==o.length+1||h(n.events.slice(0,s.length))!==h(s)||h(n.progressSnapshots.slice(0,r.length))!==h(r)||h(n.receipts.slice(0,o.length))!==h(o))throw new Error("YOLOOP_RUN_TRANSITION_INVALID");if(t){if(A.has(t.status))throw new Error("YOLOOP_RUN_TERMINAL");const u=n.progressSnapshots.at(-2)?.boundary,l=t.status===n.status&&(u==="budget"||u==="retry");if(!(He[t.status]??[]).includes(n.status)&&!l)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");ie(a),ie(c),Fe(i,s.at(-1)?.eventHash??null)}function ie(t){const{snapshotHash:e,...n}=t;if(e!==I("p220-yoloop-progress-snapshot-v1",n))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function Fe(t,e){const{eventHash:n,...s}=t;if(t.parentEventHash!==e||n!==I("p220-yoloop-run-event-v1",s))throw new Error("YOLOOP_RUN_SNAPSHOT_CONFLICT")}function ae(t,e){return`lease-${Ke(`${t}:${e}`)}`}function Ke(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(36).padStart(7,"0")}function b(t,e){const n=t.leaseExpiresAt??t.ttlExpiresAt,s=Date.parse(n),r=Date.parse(e);return!Number.isFinite(s)||!Number.isFinite(r)?"unknown":s<=r?"expired":"active"}function g(t){if(t.hostname!==N()||!Number.isSafeInteger(t.pid)||t.pid<=0)return"unknown";try{return process.kill(t.pid,0),"live"}catch(e){return e.code==="ESRCH"?"stale":"unknown"}}function V(t,e){if(b(t,e)==="expired")return"lease_expired";if(!(t.hostname&&t.hostname!==N()))return!Number.isSafeInteger(t.pid)||t.pid<=0?"invalid_pid":g(t)==="stale"?"dead_pid":void 0}function ce(t,e){return{...t,leaseState:b(t,e),ownerPidState:g(t)==="live"?"live":"unknown"}}function de(t,e,n){const s=t.lock;if(s?.ownerKind!=="client"||!s.leaseId||!s.sessionId)return!1;if(b(s,e)==="expired")return!0;const r=t.state.runControl,o=r?.progressSnapshots.at(-1),a=r?.receipts.at(-1);return r&&o&&a&&r.runId===s.sessionId&&A.has(r.status)&&o.runId===r.runId&&o.revision===r.revision&&o.status===r.status&&o.phase==="after"&&o.snapshotHash===r.latestSnapshotHash&&a.runId===r.runId&&a.revision===r.revision&&a.status===r.status&&a.snapshotHash===o.snapshotHash&&a.operationId===o.operationId&&Date.parse(o.occurredAt)>=Date.parse(s.startedAt)&&Date.parse(o.occurredAt)<=Date.parse(e)?!0:n==="stale"&&(t.state.pendingContinuationAuthorities?.length??0)===0}function Me(t,e){const n=H(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)?j(t.recovery_history):[]}}function j(t){return t.length<=J?t:t.slice(t.length-J)}const $=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"]),be=new Set(["done","completed","merged","cancelled","canceled","abandoned","skipped-with-debt","documented"]);function Ve(t){const e=String(t??"").toLowerCase().replace(/_/g,"-"),n=e.trim().toLowerCase().replace(/_/g,"-");if(be.has(n))return 0;const s=$.indexOf(e);return s<0?$.length:$.length-1-s}const q="yoloop-round-refused-before-setup",je="neocortex.p230.round-refused-before-setup.v1",ue=64,$e=Object.freeze(["digest","epicId","idempotencyKey","kind","refusals","schemaVersion","sessionId","storyIds"]),qe="reasonCode,storyId",le=/^[a-z0-9][a-z0-9-]{2,79}$/,Be=/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/,ze=/^[a-f0-9]{64}$/;function v(t){return typeof t=="string"&&Be.test(t)&&!t.includes("..")}function T(t){return typeof t=="string"&&ze.test(t)}function he(t){if(!(!Array.isArray(t)||t.length===0||t.length>ue)&&t.every(v)){for(let e=1;e<t.length;e+=1)if(t[e-1].localeCompare(t[e])>=0)return;return t}}function pe(t){return Se(je,{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||!v(t.epicId)||!T(t.sessionId)||!T(t.idempotencyKey)||!Array.isArray(t.refusals)||t.refusals.length===0||t.refusals.length>ue)return;const e=t.refusals.map(r=>({storyId:r?.storyId,reasonCode:r?.reasonCode})).sort((r,o)=>String(r.storyId).localeCompare(String(o.storyId)));if(!e.every(r=>v(r.storyId)&&typeof r.reasonCode=="string"&&le.test(r.reasonCode)))return;const n=e.map(r=>r.storyId);if(new Set(n).size!==n.length)return;const s={schemaVersion:1,kind:q,epicId:t.epicId,sessionId:t.sessionId,idempotencyKey:t.idempotencyKey,storyIds:Object.freeze(n),refusals:Object.freeze(e.map(r=>Object.freeze({storyId:r.storyId,reasonCode:r.reasonCode})))};return Object.freeze({...s,digest:pe(s)})}function Ge(t){return w(t)&&t.kind===q}function ye(t,e){if(!w(t)||Object.keys(t).some(p=>!$e.includes(p)))return!1;const{schemaVersion:n,kind:s,epicId:r,sessionId:o,idempotencyKey:a,storyIds:c,refusals:i,digest:d}=t;if(n!==1||s!==q||!v(r)||!T(o)||!T(a)||!T(d))return!1;const u=he(c);if(!u||!Array.isArray(i)||i.length!==u.length||!i.every((p,O)=>w(p)&&Object.keys(p).sort().join(",")===qe&&p.storyId===u[O]&&typeof p.reasonCode=="string"&&le.test(p.reasonCode))||d!==pe(t))return!1;if(!e)return!0;const l=he([...e.storyIds??[]].sort((p,O)=>p.localeCompare(O)));return a===e.idempotencyKey&&o===e.sessionId&&l!==void 0&&l.join(",")===u.join(",")}const We="story-round-no-setup-evidence";function ct(t){const e=t.persisted.pendingContinuationAuthorities??[];if(e.length!==1)return;const n=e[0],s=w(n.certificate)?n.certificate:void 0,r=w(s?.expectedTransition)?s.expectedTransition:void 0,o=Array.isArray(r?.storyLifecycle)?r.storyLifecycle:void 0,a=typeof n.idempotencyKey=="string"?n.idempotencyKey:"",c=typeof n.sessionId=="string"?n.sessionId:"",i=Array.isArray(n.storyIds)&&n.storyIds.every(f=>typeof f=="string")?n.storyIds:[];if(!a||!c||i.length===0||!o||o.length!==i.length||(t.persisted.continuationReceipts??[]).some(f=>f.idempotencyKey===a))return;const u=new Set(i.map(f=>{const S=w(t.stories[f])?t.stories[f]:void 0;return typeof S?.epic_id=="string"?S.epic_id:f.split(".")[0]}));if(u.size!==1)return;const l=[...u][0],p=w(t.epics[l])?t.epics[l]:void 0,O=Array.isArray(p?.story_worktree_leases)?p.story_worktree_leases:[],_=w(p?.story_worktree_evidence)?p.story_worktree_evidence:void 0,L=Array.isArray(_?.receipts)?_.receipts:[],P=Array.isArray(_?.specAcceptances)?_.specAcceptances:[],Oe=f=>O.some(S=>w(S)&&S.storyId===f)||L.some(S=>w(S)&&S.storyId===f&&(S.kind==="story-worktree-lease"||S.kind==="phase-one-receipt"))||P.some(S=>w(S)&&S.storyId===f);for(const f of i){if(Oe(f))return;const S=o.find(z=>w(z)&&z.storyId===f),B=w(t.stories[f])?t.stories[f]:void 0;if(!S||!B||!Number.isSafeInteger(S.remaining)||Ve(B.status)!==S.remaining)return}return Je({epicId:l,sessionId:c,idempotencyKey:a,refusals:i.map(f=>({storyId:f,reasonCode:We}))})}function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}export{ee as YOLOOP_PERSISTENCE_CAPABILITIES,We as YOLOOP_ROUND_NO_SETUP_EVIDENCE_REASON,q as YOLOOP_ROUND_REFUSED_KIND,at as YoloopClientStateStore,Je as buildClientYoloopRoundRefusedReceipt,Le as buildYoloopContinuationReplanPayloadHash,oe as buildYoloopRunTransitionPayloadHash,Ae as buildYoloopSessionRolloverPayloadHash,ge as buildYoloopSuccessorRunPayloadHash,ve as buildYoloopSuccessorTransitionPayloadHash,j as capRecoveryHistory,Ve as clientYoloopStoryLifecycleRemaining,H as createDefaultCounters,it as createDefaultState,ct as deriveYoloopRoundRefusedBeforeSetupReceipt,me as fingerprintYoloopSession,Ge as isClientYoloopRoundRefusedRecord,ye as isValidClientYoloopRoundRefusedReceipt};
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Public structural contract for a v4 yoloop plan.
|
|
3
|
+
* The server supplies its exact step lists without publishing them in this module.
|
|
4
|
+
*/
|
|
5
|
+
/** Actor expected to execute the plan. */
|
|
6
|
+
export const YOLOOP_EXECUTION_PLAN_EXECUTORS = Object.freeze([
|
|
7
|
+
'root_agent',
|
|
8
|
+
'root_agent_with_child_tasks',
|
|
9
|
+
'manual_operator',
|
|
10
|
+
]);
|
|
11
|
+
/** Whether the server has authorized the plan as executable. */
|
|
12
|
+
export const YOLOOP_EXECUTION_PLAN_AUTHORIZATIONS = Object.freeze([
|
|
13
|
+
'server_authorized',
|
|
14
|
+
'not_authorized',
|
|
15
|
+
]);
|
|
16
|
+
/** Whether child task delegation is required, allowed, or forbidden. */
|
|
17
|
+
export const YOLOOP_CHILD_TASK_DELEGATION_POLICIES = Object.freeze([
|
|
18
|
+
'not_required',
|
|
19
|
+
'allowed',
|
|
20
|
+
'forbidden',
|
|
21
|
+
]);
|
|
22
|
+
export const YOLOOP_EXECUTION_PLAN_V4_MODE = 'two_phase_worktree_dag';
|
|
23
|
+
/** How each story worktree is materialized for the child. */
|
|
24
|
+
export const YOLOOP_WORKSPACE_MECHANISMS = Object.freeze([
|
|
25
|
+
'native_subagent_worktree',
|
|
26
|
+
'client_managed_worktree',
|
|
27
|
+
]);
|
|
28
|
+
export const YOLOOP_V4_PHASE_IDS = Object.freeze(['phase-1-prepare', 'phase-2-finalize']);
|
|
29
|
+
/** Phase 1 runs in parallel for every story and stops after implementation. */
|
|
30
|
+
/** P225.03: closed child prompt suffix per v4 phase. */
|
|
31
|
+
export const YOLOOP_V4_PHASE_PROMPT_SUFFIXES = Object.freeze({
|
|
32
|
+
'phase-1-prepare': 'story-worktree-phase-1',
|
|
33
|
+
'phase-2-finalize': 'story-worktree-phase-2',
|
|
34
|
+
});
|
|
35
|
+
/** Closed per-story, per-phase child prompt; never the outer `*yoloop` trigger. */
|
|
36
|
+
export function yoloopV4PhasePrompt(storyId, phase) {
|
|
37
|
+
return `*yolo @docs/stories/${storyId}.story.md ${YOLOOP_V4_PHASE_PROMPT_SUFFIXES[phase]}`;
|
|
38
|
+
}
|
|
39
|
+
/** Public scheduler status of one v4 node. */
|
|
40
|
+
export const YOLOOP_V4_NODE_PHASE_STATUSES = Object.freeze([
|
|
41
|
+
'phase-1',
|
|
42
|
+
'phase-1-complete',
|
|
43
|
+
'released',
|
|
44
|
+
'reopened',
|
|
45
|
+
'integrated',
|
|
46
|
+
]);
|
|
47
|
+
/** P230.03: grammar of the opaque `worktreeRef` (same as the client lease). */
|
|
48
|
+
export const YOLOOP_V4_WORKTREE_REF_PATTERN = /^wt\/[0-9a-f]{8}$/;
|
|
49
|
+
/** Public clients validate step identifier shape. The server binds its exact lists. */
|
|
50
|
+
export function isYoloopV4PublicStepId(value) {
|
|
51
|
+
return typeof value === 'string' && /^step-[a-z0-9-]{1,64}$/.test(value);
|
|
52
|
+
}
|
|
53
|
+
function isYoloopV4PublicStepList(value) {
|
|
54
|
+
return Array.isArray(value) && value.length > 0 && value.length <= 32
|
|
55
|
+
&& value.every(isYoloopV4PublicStepId) && new Set(value).size === value.length;
|
|
56
|
+
}
|
|
57
|
+
const publicV4StepPolicy = {
|
|
58
|
+
phaseOne: isYoloopV4PublicStepList,
|
|
59
|
+
phaseTwo: isYoloopV4PublicStepList,
|
|
60
|
+
barrier: isYoloopV4PublicStepId,
|
|
61
|
+
};
|
|
62
|
+
export const YOLOOP_V4_PLAN_REASON_CODES = Object.freeze([
|
|
63
|
+
'plan-v4-shape-invalid',
|
|
64
|
+
'plan-v4-version-invalid',
|
|
65
|
+
'plan-v4-story-ids-invalid',
|
|
66
|
+
'plan-v4-workspace-mechanism-invalid',
|
|
67
|
+
'plan-v4-phase-order-invalid',
|
|
68
|
+
'plan-v4-spec-barrier-invalid',
|
|
69
|
+
'plan-v4-integration-order-invalid',
|
|
70
|
+
'plan-v4-integration-owner-invalid',
|
|
71
|
+
'plan-v4-integration-concurrency-invalid',
|
|
72
|
+
'plan-v4-outer-yoloop-forbidden',
|
|
73
|
+
'plan-v4-child-workspace-invalid',
|
|
74
|
+
'plan-v4-isolation-policy-invalid',
|
|
75
|
+
'plan-v4-prompt-template-invalid',
|
|
76
|
+
'plan-v4-node-invalid',
|
|
77
|
+
'plan-v4-unknown-field',
|
|
78
|
+
'plan-v4-unsafe-value',
|
|
79
|
+
]);
|
|
80
|
+
const V4_STORY_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
|
|
81
|
+
const V4_SHA256 = /^[a-f0-9]{64}$/;
|
|
82
|
+
const V4_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,119}$/;
|
|
83
|
+
const V4_URL_LIKE = /[A-Za-z][A-Za-z0-9+.-]*:\/\//;
|
|
84
|
+
const V4_ABSOLUTE_PATH_LIKE = /^(?:\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/;
|
|
85
|
+
const V4_PLAN_KEYS = new Set([
|
|
86
|
+
'version', 'mode', 'executor', 'authorization', 'storyIds', 'promptTemplates', 'executionBranch',
|
|
87
|
+
'graphRevision', 'dependencyBasis', 'workspaceMechanism', 'phases', 'specBarrier', 'integrationOrder',
|
|
88
|
+
'isolationPolicy', 'skippedStories', 'nodes', 'childSpecContexts',
|
|
89
|
+
]);
|
|
90
|
+
const V4_NODE_KEYS = new Set([
|
|
91
|
+
'storyId', 'phaseStatus', 'executionBranch', 'baseSha', 'temporaryBranch', 'dependencies', 'promptTemplate',
|
|
92
|
+
'worktreeRef',
|
|
93
|
+
]);
|
|
94
|
+
const V4_GIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
|
|
95
|
+
const V4_PHASE_KEYS = new Set(['id', 'stepIds', 'storyIds', 'maxConcurrency']);
|
|
96
|
+
const V4_BARRIER_KEYS = new Set(['stepId', 'scope', 'storyIds']);
|
|
97
|
+
const V4_POLICY_KEYS = new Set([
|
|
98
|
+
'rootOwnsLoop', 'rootOwnedScheduling', 'childPromptKind', 'childTaskDelegation', 'allowOuterYoloopInChild',
|
|
99
|
+
'allowMetaTaskPromptInChild', 'childWorkspace', 'integrationOwner', 'maxIntegrationConcurrency', 'maxDepth',
|
|
100
|
+
'childDelegationMaxDepth',
|
|
101
|
+
]);
|
|
102
|
+
const V4_DEPENDENCY_BASIS_KEYS = new Set([
|
|
103
|
+
'scope', 'epicId', 'epicQueue', 'currentEpicIndex', 'source', 'storyIds', 'dependencyRefs', 'contractRefs',
|
|
104
|
+
'sharedSurfaceRefs',
|
|
105
|
+
]);
|
|
106
|
+
function v4HasOnlyKeys(value, allowed) {
|
|
107
|
+
return value === undefined || Object.keys(value).every((key) => allowed.has(key));
|
|
108
|
+
}
|
|
109
|
+
/** True when any nested string (or key) looks like a URL or an absolute path. */
|
|
110
|
+
function v4HasUnsafeString(value, depth = 0) {
|
|
111
|
+
if (depth > 6)
|
|
112
|
+
return true;
|
|
113
|
+
if (typeof value === 'string')
|
|
114
|
+
return V4_URL_LIKE.test(value) || V4_ABSOLUTE_PATH_LIKE.test(value);
|
|
115
|
+
if (Array.isArray(value))
|
|
116
|
+
return value.some((item) => v4HasUnsafeString(item, depth + 1));
|
|
117
|
+
if (value !== null && typeof value === 'object') {
|
|
118
|
+
return Object.entries(value).some(([key, item]) => v4HasUnsafeString(key, depth + 1) || v4HasUnsafeString(item, depth + 1));
|
|
119
|
+
}
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
function v4IsValidBranch(value) {
|
|
123
|
+
return typeof value === 'string' && V4_BRANCH.test(value) && !value.includes('..') && !value.endsWith('/')
|
|
124
|
+
&& !value.endsWith('.lock') && value.split('/').every((segment) => segment !== '' && !segment.startsWith('.'));
|
|
125
|
+
}
|
|
126
|
+
function v4Record(value) {
|
|
127
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
128
|
+
? value
|
|
129
|
+
: undefined;
|
|
130
|
+
}
|
|
131
|
+
function v4StoryIds(value) {
|
|
132
|
+
if (!Array.isArray(value) || value.some((id) => typeof id !== 'string' || !V4_STORY_ID.test(id)))
|
|
133
|
+
return undefined;
|
|
134
|
+
return new Set(value).size === value.length ? value : undefined;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* P228.02: a `frontier` barrier needs the plan nodes to prove closure; every
|
|
138
|
+
* dependency of a member that is a non-integrated plan story must be a member.
|
|
139
|
+
*/
|
|
140
|
+
function v4FrontierBarrierValid(barrierStories, storyIds, nodes) {
|
|
141
|
+
if (!barrierStories || barrierStories.length === 0 || !storyIds)
|
|
142
|
+
return false;
|
|
143
|
+
if (!barrierStories.every((id) => storyIds.includes(id)) || !Array.isArray(nodes))
|
|
144
|
+
return false;
|
|
145
|
+
const byId = new Map();
|
|
146
|
+
for (const node of nodes) {
|
|
147
|
+
const record = v4Record(node);
|
|
148
|
+
if (!record || typeof record.storyId !== 'string')
|
|
149
|
+
return false;
|
|
150
|
+
byId.set(record.storyId, record);
|
|
151
|
+
}
|
|
152
|
+
const members = new Set(barrierStories);
|
|
153
|
+
return barrierStories.every((storyId) => {
|
|
154
|
+
const dependencies = byId.get(storyId)?.dependencies;
|
|
155
|
+
if (!Array.isArray(dependencies))
|
|
156
|
+
return false;
|
|
157
|
+
return dependencies.every((id) => typeof id === 'string' && (!storyIds.includes(id) || members.has(id)
|
|
158
|
+
|| byId.get(id)?.phaseStatus === 'integrated'));
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function v4SameSet(left, right) {
|
|
162
|
+
if (left.length !== right.length)
|
|
163
|
+
return false;
|
|
164
|
+
const expected = new Set(right);
|
|
165
|
+
return left.every((value) => expected.has(value));
|
|
166
|
+
}
|
|
167
|
+
function v4SameList(left, right) {
|
|
168
|
+
return Array.isArray(left) && left.length === right.length && left.every((value, index) => value === right[index]);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Pure, total validator for v4 plans. Enforces a closed key set, no URL or
|
|
172
|
+
* absolute-path values, exact phases (every story in phase 1), the C04 spec
|
|
173
|
+
* barrier, an integration order covering every story exactly once and the
|
|
174
|
+
* root-only integration policy. Topological soundness of `integrationOrder`
|
|
175
|
+
* against the dependency graph is the emitter's responsibility (P225.02/.03).
|
|
176
|
+
*/
|
|
177
|
+
export function validateYoloopExecutionPlanV4Structure(plan, stepPolicy = publicV4StepPolicy) {
|
|
178
|
+
const reasons = new Set();
|
|
179
|
+
const record = v4Record(plan);
|
|
180
|
+
if (!record) {
|
|
181
|
+
return Object.freeze({ valid: false, reasonCodes: Object.freeze(['plan-v4-shape-invalid']) });
|
|
182
|
+
}
|
|
183
|
+
if (record.version !== 4 || record.mode !== YOLOOP_EXECUTION_PLAN_V4_MODE)
|
|
184
|
+
reasons.add('plan-v4-version-invalid');
|
|
185
|
+
if (v4HasUnsafeString(record))
|
|
186
|
+
reasons.add('plan-v4-unsafe-value');
|
|
187
|
+
const nestedPhases = Array.isArray(record.phases) ? record.phases.map(v4Record) : [];
|
|
188
|
+
if (!v4HasOnlyKeys(record, V4_PLAN_KEYS)
|
|
189
|
+
|| nestedPhases.some((phase) => !v4HasOnlyKeys(phase, V4_PHASE_KEYS))
|
|
190
|
+
|| !v4HasOnlyKeys(v4Record(record.specBarrier), V4_BARRIER_KEYS)
|
|
191
|
+
|| !v4HasOnlyKeys(v4Record(record.isolationPolicy), V4_POLICY_KEYS)
|
|
192
|
+
|| !v4HasOnlyKeys(v4Record(record.dependencyBasis), V4_DEPENDENCY_BASIS_KEYS)) {
|
|
193
|
+
reasons.add('plan-v4-unknown-field');
|
|
194
|
+
}
|
|
195
|
+
const storyIds = v4StoryIds(record.storyIds);
|
|
196
|
+
if (!storyIds || storyIds.length === 0)
|
|
197
|
+
reasons.add('plan-v4-story-ids-invalid');
|
|
198
|
+
if (!v4IsValidBranch(record.executionBranch)
|
|
199
|
+
|| typeof record.graphRevision !== 'string' || !V4_SHA256.test(record.graphRevision)
|
|
200
|
+
|| !v4Record(record.dependencyBasis)
|
|
201
|
+
|| !YOLOOP_EXECUTION_PLAN_EXECUTORS.includes(record.executor)
|
|
202
|
+
|| !YOLOOP_EXECUTION_PLAN_AUTHORIZATIONS.includes(record.authorization)) {
|
|
203
|
+
reasons.add('plan-v4-shape-invalid');
|
|
204
|
+
}
|
|
205
|
+
if (!YOLOOP_WORKSPACE_MECHANISMS.includes(record.workspaceMechanism)) {
|
|
206
|
+
reasons.add('plan-v4-workspace-mechanism-invalid');
|
|
207
|
+
}
|
|
208
|
+
const phases = Array.isArray(record.phases) ? record.phases.map(v4Record) : undefined;
|
|
209
|
+
const phaseOne = phases?.[0];
|
|
210
|
+
const phaseTwo = phases?.[1];
|
|
211
|
+
const phaseConcurrencyValid = [phaseOne, phaseTwo].every((phase) => Number.isSafeInteger(phase?.maxConcurrency) && phase?.maxConcurrency >= 1);
|
|
212
|
+
// Every story runs phase 1; phase 2 holds the currently released subset.
|
|
213
|
+
const phaseOneStories = v4StoryIds(phaseOne?.storyIds);
|
|
214
|
+
const phaseTwoStories = v4StoryIds(phaseTwo?.storyIds);
|
|
215
|
+
const phaseStoriesValid = phaseOneStories !== undefined && phaseTwoStories !== undefined
|
|
216
|
+
&& (storyIds === undefined
|
|
217
|
+
|| (v4SameSet(phaseOneStories, storyIds) && phaseTwoStories.every((id) => storyIds.includes(id))));
|
|
218
|
+
if (!phases || phases.length !== 2 || phaseOne?.id !== 'phase-1-prepare' || phaseTwo?.id !== 'phase-2-finalize'
|
|
219
|
+
|| !stepPolicy.phaseOne(phaseOne.stepIds) || !stepPolicy.phaseTwo(phaseTwo.stepIds)
|
|
220
|
+
|| !phaseConcurrencyValid || !phaseStoriesValid) {
|
|
221
|
+
reasons.add('plan-v4-phase-order-invalid');
|
|
222
|
+
}
|
|
223
|
+
const barrier = v4Record(record.specBarrier);
|
|
224
|
+
const barrierStories = v4StoryIds(barrier?.storyIds);
|
|
225
|
+
// P228.02 (CON-P228.02-PLAN-V4-SCOPE): `epic` keeps the exact-set rule;
|
|
226
|
+
// `frontier` is a non-empty subset closed under unintegrated dependencies.
|
|
227
|
+
const barrierScopeValid = barrier?.scope === 'epic'
|
|
228
|
+
? storyIds === undefined || (barrierStories !== undefined && v4SameSet(barrierStories, storyIds))
|
|
229
|
+
: barrier?.scope === 'frontier'
|
|
230
|
+
? v4FrontierBarrierValid(barrierStories, storyIds, record.nodes)
|
|
231
|
+
: false;
|
|
232
|
+
if (!barrier || !stepPolicy.barrier(barrier.stepId) || !barrierStories || !barrierScopeValid) {
|
|
233
|
+
reasons.add('plan-v4-spec-barrier-invalid');
|
|
234
|
+
}
|
|
235
|
+
const integrationOrder = v4StoryIds(record.integrationOrder);
|
|
236
|
+
if (!integrationOrder || (storyIds !== undefined && !v4SameSet(integrationOrder, storyIds))) {
|
|
237
|
+
reasons.add('plan-v4-integration-order-invalid');
|
|
238
|
+
}
|
|
239
|
+
const policy = v4Record(record.isolationPolicy);
|
|
240
|
+
if (!policy) {
|
|
241
|
+
reasons.add('plan-v4-isolation-policy-invalid');
|
|
242
|
+
}
|
|
243
|
+
else {
|
|
244
|
+
if (policy.integrationOwner !== 'root_agent')
|
|
245
|
+
reasons.add('plan-v4-integration-owner-invalid');
|
|
246
|
+
if (policy.maxIntegrationConcurrency !== 1)
|
|
247
|
+
reasons.add('plan-v4-integration-concurrency-invalid');
|
|
248
|
+
if (policy.allowOuterYoloopInChild !== false || policy.allowMetaTaskPromptInChild !== false) {
|
|
249
|
+
reasons.add('plan-v4-outer-yoloop-forbidden');
|
|
250
|
+
}
|
|
251
|
+
if (policy.childWorkspace !== 'story_worktree')
|
|
252
|
+
reasons.add('plan-v4-child-workspace-invalid');
|
|
253
|
+
if (policy.rootOwnsLoop !== true || policy.rootOwnedScheduling !== 'two_phase_worktree_dag_allowed'
|
|
254
|
+
|| policy.childPromptKind !== 'per_story_worktree_phase_only'
|
|
255
|
+
|| !YOLOOP_CHILD_TASK_DELEGATION_POLICIES.includes(policy.childTaskDelegation)
|
|
256
|
+
|| (policy.maxDepth !== undefined && policy.maxDepth !== 1)
|
|
257
|
+
|| (policy.childDelegationMaxDepth !== undefined && policy.childDelegationMaxDepth !== 3)) {
|
|
258
|
+
reasons.add('plan-v4-isolation-policy-invalid');
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (record.promptTemplates !== undefined && (!Array.isArray(record.promptTemplates)
|
|
262
|
+
|| record.promptTemplates.some((template) => typeof template !== 'string'
|
|
263
|
+
|| !template.startsWith('*yolo @') || /\*yoloop\b/i.test(template)))) {
|
|
264
|
+
reasons.add('plan-v4-prompt-template-invalid');
|
|
265
|
+
}
|
|
266
|
+
if (record.nodes !== undefined && (!v4NodesValid(record.nodes, storyIds, record.executionBranch)
|
|
267
|
+
|| !v4PromptsMatchNodes(record.promptTemplates, record.nodes))) {
|
|
268
|
+
reasons.add('plan-v4-node-invalid');
|
|
269
|
+
}
|
|
270
|
+
if (record.childSpecContexts !== undefined && (!Array.isArray(record.childSpecContexts)
|
|
271
|
+
|| record.childSpecContexts.some((context) => {
|
|
272
|
+
const item = v4Record(context);
|
|
273
|
+
return !item || item.schemaVersion !== 1 || typeof item.storyId !== 'string'
|
|
274
|
+
|| (storyIds !== undefined && !storyIds.includes(item.storyId));
|
|
275
|
+
})
|
|
276
|
+
|| new Set(record.childSpecContexts.map((context) => v4Record(context)?.storyId)).size
|
|
277
|
+
!== record.childSpecContexts.length)) {
|
|
278
|
+
reasons.add('plan-v4-node-invalid');
|
|
279
|
+
}
|
|
280
|
+
const reasonCodes = Object.freeze([...reasons].sort());
|
|
281
|
+
return Object.freeze({ valid: reasonCodes.length === 0, reasonCodes });
|
|
282
|
+
}
|
|
283
|
+
/** Nodes: closed keys, one per story, same execution branch, distinct temporary branches, closed prompts. */
|
|
284
|
+
function v4NodesValid(value, storyIds, executionBranch) {
|
|
285
|
+
if (!Array.isArray(value))
|
|
286
|
+
return false;
|
|
287
|
+
const nodes = value.map(v4Record);
|
|
288
|
+
if (nodes.some((node) => !node || !v4HasOnlyKeys(node, V4_NODE_KEYS)))
|
|
289
|
+
return false;
|
|
290
|
+
const nodeIds = v4StoryIds(nodes.map((node) => node.storyId));
|
|
291
|
+
if (!nodeIds || (storyIds !== undefined && !v4SameSet(nodeIds, storyIds)))
|
|
292
|
+
return false;
|
|
293
|
+
const temporaryBranches = new Set();
|
|
294
|
+
for (const node of nodes) {
|
|
295
|
+
const storyId = node.storyId;
|
|
296
|
+
if (!YOLOOP_V4_NODE_PHASE_STATUSES.includes(node.phaseStatus))
|
|
297
|
+
return false;
|
|
298
|
+
if (node.executionBranch !== executionBranch || !v4IsValidBranch(node.executionBranch))
|
|
299
|
+
return false;
|
|
300
|
+
if (typeof node.baseSha !== 'string' || !V4_GIT_SHA.test(node.baseSha))
|
|
301
|
+
return false;
|
|
302
|
+
if (!v4IsValidBranch(node.temporaryBranch) || node.temporaryBranch === executionBranch
|
|
303
|
+
|| temporaryBranches.has(node.temporaryBranch))
|
|
304
|
+
return false;
|
|
305
|
+
temporaryBranches.add(node.temporaryBranch);
|
|
306
|
+
const dependencies = v4StoryIds(node.dependencies);
|
|
307
|
+
if (!dependencies || dependencies.includes(storyId))
|
|
308
|
+
return false;
|
|
309
|
+
// P230.03: an opaque reference only; any other shape (a path) fails closed.
|
|
310
|
+
if (node.worktreeRef !== undefined
|
|
311
|
+
&& (typeof node.worktreeRef !== 'string' || !YOLOOP_V4_WORKTREE_REF_PATTERN.test(node.worktreeRef)))
|
|
312
|
+
return false;
|
|
313
|
+
// The prompt phase must match the node status; non-dispatchable nodes carry none.
|
|
314
|
+
const expectedPhase = node.phaseStatus === 'phase-1'
|
|
315
|
+
? 'phase-1-prepare'
|
|
316
|
+
: node.phaseStatus === 'released' || node.phaseStatus === 'reopened' ? 'phase-2-finalize' : undefined;
|
|
317
|
+
if (node.promptTemplate !== undefined
|
|
318
|
+
&& (expectedPhase === undefined || node.promptTemplate !== yoloopV4PhasePrompt(storyId, expectedPhase)))
|
|
319
|
+
return false;
|
|
320
|
+
}
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
/** With nodes present, top-level prompts are exactly the node prompts in node order. */
|
|
324
|
+
function v4PromptsMatchNodes(promptTemplates, nodes) {
|
|
325
|
+
if (!Array.isArray(nodes))
|
|
326
|
+
return true;
|
|
327
|
+
const expected = nodes.flatMap((node) => {
|
|
328
|
+
const prompt = v4Record(node)?.promptTemplate;
|
|
329
|
+
return typeof prompt === 'string' ? [prompt] : [];
|
|
330
|
+
});
|
|
331
|
+
return v4SameList(promptTemplates ?? [], expected);
|
|
332
|
+
}
|