@ornexus/neocortex 4.66.26 → 4.66.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1194 -1194
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/commands/invoke.d.ts +13 -1
  7. package/packages/client/dist/commands/invoke.js +61 -61
  8. package/packages/client/dist/continuity/sqlite-store.d.ts +9 -2
  9. package/packages/client/dist/continuity/sqlite-store.js +32 -25
  10. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +10 -0
  11. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -4
  12. package/packages/client/dist/git/git-lifecycle-store.d.ts +16 -0
  13. package/packages/client/dist/git/git-lifecycle-store.js +9 -9
  14. package/packages/client/dist/git/published-story-reconciliation.d.ts +7 -3
  15. package/packages/client/dist/git/published-story-reconciliation.js +5 -5
  16. package/packages/client/dist/git/secure-filesystem-boundary.d.ts +1 -1
  17. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -5
  18. package/packages/client/dist/git/story-worktree-integration.d.ts +2 -0
  19. package/packages/client/dist/git/story-worktree-integration.js +3 -3
  20. package/packages/client/dist/git/story-worktree-manager.d.ts +1 -0
  21. package/packages/client/dist/git/story-worktree-manager.js +3 -3
  22. package/packages/client/dist/license/license-client.js +1 -1
  23. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +17 -0
  24. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +3 -2
  25. package/packages/client/dist/runner/headless/phase-two-checkpoint-evidence.d.ts +23 -0
  26. package/packages/client/dist/runner/headless/phase-two-checkpoint-evidence.js +1 -0
  27. package/packages/client/dist/runner/headless/run-yolo.js +1 -1
  28. package/packages/client/dist/runner/headless/run-yoloop.d.ts +30 -2
  29. package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
  30. package/postinstall.js +6 -0
  31. package/targets-stubs/antigravity/gemini.md +1 -1
  32. package/targets-stubs/antigravity/neocortex.md +1 -1
  33. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  34. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  35. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  36. package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
  37. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  38. package/targets-stubs/claude-code/neocortex.md +2 -2
  39. package/targets-stubs/codex/AGENTS.md +1 -1
  40. package/targets-stubs/codex/neocortex.toml +1 -1
  41. package/targets-stubs/cursor/agent.md +2 -2
  42. package/targets-stubs/deepseek-harness/SKILL.md +1 -1
  43. package/targets-stubs/gemini-cli/agent.md +2 -2
  44. package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
  45. package/targets-stubs/grok/SKILL.md +1 -1
  46. package/targets-stubs/kimi/neocortex.md +1 -1
  47. package/targets-stubs/openclaw/SKILL.md +1 -1
  48. package/targets-stubs/opencode/neocortex-root.md +2 -2
  49. package/targets-stubs/opencode/neocortex.md +2 -2
  50. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -989,15 +989,22 @@ export declare class ContinuitySqliteStore {
989
989
  readonly jobId: string;
990
990
  readonly storyId: string;
991
991
  readonly targetRef: string;
992
- }, phaseTwoBinding?: string): {
992
+ }, phaseTwoBinding?: string, phaseTwoCheckpointFingerprint?: string): {
993
993
  readonly receiptId: string;
994
994
  readonly createdAt: string;
995
995
  readonly reasonCode: string;
996
996
  readonly ownerRunnerId: string;
997
997
  readonly leaseId: string;
998
998
  } | null;
999
- /** A new root job may resume the same phase-two release without redoing its worker. */
999
+ /** Legacy binding-only lookup retained for compatibility and diagnostics. */
1000
1000
  findPhaseTwoExecutionCompletion(binding: string, storyId: string, targetRef: string): 'completed' | 'missing' | 'conflict';
1001
+ /**
1002
+ * A phase-two worker is reusable only for the exact post-execution worktree
1003
+ * fingerprint stored in its applied receipt. This keeps worker completion
1004
+ * distinct from checkpoint completion and permits one new idempotent worker
1005
+ * after the physical evidence changes.
1006
+ */
1007
+ findPhaseTwoWorkerCompletion(binding: string, storyId: string, targetRef: string, checkpointFingerprint: string): 'completed' | 'missing' | 'conflict';
1001
1008
  claimHeadlessExecutionAttempt(input: ContinuityHeadlessExecutionAttemptClaimInput): ContinuitySqliteWriteResult;
1002
1009
  acquireNextHeadlessExecutionAttempt(input: ContinuityHeadlessExecutionAcquireNextInput): ContinuityHeadlessExecutionAcquireNextResult;
1003
1010
  heartbeatHeadlessExecutionAttempt(input: ContinuityHeadlessExecutionAttemptHeartbeatInput): ContinuitySqliteWriteResult;
@@ -1,15 +1,15 @@
1
- import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";import{chmodSync as X,closeSync as xe,existsSync as ae,mkdirSync as re,openSync as Re,readSync as Ne}from"node:fs";import{dirname as se,join as oe}from"node:path";import{INITIAL_CONTINUITY_SQLITE_MIGRATION as Oe}from"./migrations/001-initial-schema.js";import{PROCESSING_OUTPUT_SUMMARY_SQLITE_MIGRATION as Te}from"./migrations/002-processing-output-summary-indexes.js";import{HEADLESS_EXECUTION_ATTEMPTS_SQLITE_MIGRATION as Le}from"./migrations/003-headless-execution-attempts.js";import{OUTBOX_DELIVERY_STATE_SQLITE_MIGRATION as ve}from"./migrations/004-outbox-delivery-state.js";import{BOUNDED_HEADLESS_QUEUE_SQLITE_MIGRATION as je}from"./migrations/005-bounded-headless-queue.js";import{NATIVE_AGENT_DISPATCHES_SQLITE_MIGRATION as Me}from"./migrations/006-native-agent-dispatches.js";import{NATIVE_LAUNCH_RETRY_SQLITE_MIGRATION as ke}from"./migrations/007-native-launch-retry.js";import{isNativeLaunchRefusal as De,nativeLaunchRetryKey as we}from"../../../shared/dist/yoloop/native-launch-retry.js";import{NATIVE_AGENT_TERMINAL_STATES as ne,isNativeAgentDispatchReceiptV1 as Z,isNativeAgentStateTransitionAllowed as Ue,isNativeDispatchBindingV1 as qe,isNativeHostAttestationV1 as He}from"./native-agent-types.js";import{CONTINUITY_QUEUE_REASON_CODES as v,CONTINUITY_RECEIPT_COMPACTION_EVENT_TYPE as B,CONTINUITY_RECEIPT_RETENTION_REASON_CODES as $,DEFAULT_CONTINUITY_QUEUE_POLICY as Pe,computeContinuityQueueRetryAt as We,computeContinuityOutboxFailureDecision as Fe,normalizeContinuityQueuePolicy as Y,normalizeContinuityQueuePriority as Be,normalizeContinuityQueueScope as $e,normalizeContinuityRetentionPolicy as Ye}from"./outbox.js";const de=".neocortex/continuity",Ke="continuity.sqlite",Ft=7,Ve=5e3,O="processing_output_summary",Qe=2e3,ie=20,Je=100,ce="Install the optional Enterprise continuity SQLite adapter with `npm install --workspace packages/client better-sqlite3 --include=optional` or reinstall Neocortex with optional dependencies enabled.",Ge=Object.freeze(["discover_more","create_epic","run_yoloop","run_yolo","run_verifier","run_review_gate","compact_context","wait_external","backoff","waiting_human","complete","abort","scheduled","running","overlap_skipped","missed_run_catchup","completed","aborted","cancelled","blocked","draft","planned"]),le=20,ze=new Set(Ge),Xe=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;function ue(a){return typeof a=="string"&&ze.has(a)}function _e(a){if(typeof a!="string")return;const e=a.trim();if(!(e.length===0||e.length>40)&&Xe.test(e))return e}function Ze(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(!E(t)||!ue(t.stage))continue;const r=_e(t.at);r&&e.push({stage:t.stage,at:r})}return e.slice(-le)}function et(a){if(!(typeof a!="number"||!Number.isFinite(a)||a<0))return Math.floor(a)}class c extends Error{code;reasonCode;guidance;mutationBlocked;cause;constructor(e,t,r={}){super(t),this.name="ContinuitySqliteStoreError",this.code=e,this.reasonCode=e,this.guidance=r.guidance,this.cause=r.cause,this.mutationBlocked=r.mutationBlocked??e==="sqlite-integrity-failed"}}function j(a){const e=Object.freeze({schemaVersion:1,storyId:a.story_id,graphRevision:a.graph_revision,dispatchKey:a.dispatch_key,profile:a.profile,parentHandle:a.parent_handle,handle:a.handle,topology:a.topology,state:a.state,requestedAt:a.requested_at,observedAt:a.observed_at,terminalAt:a.terminal_at,freshness:a.freshness,observationSource:a.observation_source,reasonCode:a.reason_code,revision:a.revision,publicSafe:!0});if(!Z(e))throw new c("sqlite-integrity-failed","Native-agent receipt failed its closed public contract.",{mutationBlocked:!0});return e}const tt=[Oe,Te,Le,ve,je,Me,ke],at=Object.freeze(["continuity_migrations","jobs","job_leases","job_events","job_receipts","goal_campaigns","goal_ledger_items","goal_verifiers","goal_review_gates","loop_jobs","artifacts","state_snapshots","headless_execution_attempts","runner_config","outbox","native_agent_dispatches","native_agent_observations"]),me=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,pe=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_ -]?(?:logs?|outputs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt[_ -]?(?:body|text)|workflow body|step body|\bargv\b|(?:bash|sh|zsh|powershell|pwsh)\s+-c\b|(?:\.{0,2}\/|[A-Za-z]:\\|\/)[^\s]*(?:\.exe|\.bat|\.cmd|\.ps1|\.sh|\/bin\/[^\s]+)|\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY)|P192[_-]?SYNTHETIC[_-]?(?:PORTAL|RUNNER|SYNC))/i,rt=new Set(["unsafe_key","raw_log","prompt_body","private_url","local_absolute_path","secret","protected_field","unbounded_text","unbounded_number","unknown_required_operation","missing"]),st=/(corrupt|malformed|not a database|file is not a database|database disk image is malformed)/i,ot=/(foreign key constraint failed|SQLITE_CONSTRAINT_FOREIGNKEY)/i,ee="p185:v1:",nt=new Set(["schemaVersion","contractVersion","eventType","executionId","jobId","operationId","idempotencyKey","goalId","loopId","campaignId","itemId","ledgerItemIds","verifierId","verifierIds","gateId","reviewGateIds","runnerId","leaseId","status","reasonCode","reasonCodes","runtimeId","modelId","runtimeSource","headlessRuntime","headlessModel","headlessRuntimeReasonCode","originRuntime","originModel","targetRef","attemptId","attemptStatus","terminalClass","releaseBlocked","directiveHash","timeoutMs","leaseExpiresAt","heartbeatAt","notBeforeAt","maxAttempts","counts","hashes","relativePaths","artifactRefs","evidenceRefs","validationRefs","registryRefs","storyIds","epicIds","debtIds","iteration","currentStage","stageHistory","durationMs","retryCount","attemptCount","queuePriority","queueScope","queueCap","queueDepth","queueAvailable","queueBackpressure","nextTickAt","nextAttemptAt","nextRetryAt","deadLetterReasonCode","deliveryCursor","lastAttemptAt","sentAt","ackedAt","lastErrorReason","lastErrorSummary","deadLetterSummary","deadLetteredAt","processingOutputSource","publicSummary","redactionEvidence","selectorKind","targetId","targetJobId","relatedJobIds","serverAccessToLocalhost","serverHeldStream","initialCursor","targetResolutionState","targetKind","relatedJobCount","snapshotStatus","snapshotGeneratedAt","renderedSummaryCount","cursorState","currentCursor","nextCursor","cursorAdvanced","eventId","latestEventId","watchStatus","stopReason","syncVersion","transportKind","envelopeId","workspaceId","workspaceLabel","projectId","projectLabel","snapshotId","syncCursor","previousSyncCursor","nextSyncCursor","commandId","receiptId","acknowledgedAt","observedAt","generatedAt","syncStatus","commandStatus","receiptStatus","actorType","actorId","tenantId","commandKind","auditStatus","redactionCount","autonomousGovernance","governanceVersion","governanceEvidence","governanceSource","publicSafe"]),dt=new Set(["foreground_invoke","scheduled_tick","runner_tick","manual_tick","headless_execution","jobs_command","invoke_watch","portal_render"]);function it(a){return import(a)}function ct(a){return`sha256:${k("sha256").update(a).digest("hex")}`}function E(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function lt(a){return a instanceof Error?a.message:String(a)}function ut(a){return E(a)&&typeof a.code=="string"?a.code:void 0}function p(a,e){if(a instanceof c)return a;const t=lt(a),r=ut(a);return r==="SQLITE_CORRUPT"||r==="SQLITE_NOTADB"||st.test(t)?new c("sqlite-integrity-failed","Continuity SQLite integrity check failed; durable mutation is blocked until the store is repaired or rebuilt.",{cause:a,mutationBlocked:!0}):r==="SQLITE_CONSTRAINT_FOREIGNKEY"||ot.test(t)?new c("sqlite-foreign-key-failed","Continuity SQLite foreign-key validation failed; mutation was rejected.",{cause:a}):new c(e,t,{cause:a})}function A(a,e){if(typeof a=="string"){if(/\.(?:redactionEvidence|redactionSummary)\[\d+\]\.field$/.test(e)&&/^[A-Za-z0-9_.:[\]-]{1,120}$/.test(a)||/\.(?:redactionEvidence|redactionSummary)\[\d+\]\.reason$/.test(e)&&rt.has(a))return;if(pe.test(a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe value at ${e}.`);return}if(!(a===null||typeof a=="number"||typeof a=="boolean")){if(Array.isArray(a)){a.forEach((t,r)=>A(t,`${e}[${r}]`));return}if(E(a)){for(const[t,r]of Object.entries(a)){const s=t==="terminationToken"&&e.endsWith(".releaseBlocked")&&r==="[YOLOOP_RELEASE_BLOCKED]";if(me.test(t)&&!s)throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe key at ${e}.${t}.`);A(r,`${e}.${t}`)}return}throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsupported value at ${e}.`)}}function I(a,e){if(a!==void 0&&pe.test(a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite text rejected unsafe value at ${e}.`)}function K(a,e,t=240){if(a.trim().length===0)throw new c("sqlite-public-safety-rejected",`Continuity SQLite processing summary text is required at ${e}.`);if(I(a,e),a.length>t)throw new c("sqlite-public-safety-rejected",`Continuity SQLite processing summary text exceeded the public bound at ${e}.`)}function V(a){const e={};if(!a)return e;for(const[t,r]of Object.entries(a))if(nt.has(t)&&!me.test(t))try{A(r,`metadata.${t}`),e[t]=r}catch{}return e}function _t(a){const e={...V(a.metadata),schemaVersion:1,contractVersion:"continuity-v1",eventType:O,executionId:a.executionId,jobId:a.jobId,operationId:a.executionId,publicSummary:a.publicSummary};return a.idempotencyKey&&(e.idempotencyKey=a.idempotencyKey),a.goalId&&(e.goalId=a.goalId),a.loopId&&(e.loopId=a.loopId),a.reasonCode&&(e.reasonCode=a.reasonCode),a.source&&dt.has(a.source)&&(e.processingOutputSource=a.source),V(e)}function he(a){const e=Math.floor(a??ie);return Number.isFinite(e)?Math.max(1,Math.min(Je,e)):ie}function mt(a){if(a.eventId&&a.eventId.trim().length>0)return a.eventId;const e=a.executionId.replace(/[^a-z0-9_.:-]+/gi,"-").replace(/^-+|-+$/g,"");return e.length>0?`event-processing-summary-${e.slice(0,160)}`:`event-processing-summary-${k("sha256").update(a.executionId).digest("hex").slice(0,32)}`}function pt(a){return`${ee}${z.from(JSON.stringify([a.created_at,a.event_id]),"utf8").toString("base64url")}`}function ht(a){if(a?.startsWith(ee))try{const e=a.slice(ee.length),t=JSON.parse(z.from(e,"base64url").toString("utf8"));if(!Array.isArray(t)||t.length!==2)return;const[r,s]=t;return typeof r!="string"||typeof s!="string"?void 0:{createdAt:r,eventId:s}}catch{return}}function w(a,e){if(!e)return;const t=e.trim().replace(/^@/,"");if(a==="job"&&/^job-J\d{3,}$/i.test(t))return`job-J${t.match(/\d+$/)?.[0]??""}`;if(a==="goal"&&/^goal-G\d{3,}$/i.test(t))return`goal-G${t.match(/\d+$/)?.[0]??""}`;if(a==="loop"&&/^loop-L\d{3,}$/i.test(t))return`loop-L${t.match(/\d+$/)?.[0]??""}`}function ye(a){return a?P(a.map(e=>w("job",e)).filter(e=>!!e)):[]}function fe(a){const e=a.target;if(!e){const r=w("job",a.jobId);return r?{sql:" AND job_id = ?",params:[r]}:{sql:"",params:[]}}const t=e.selectorKind;if(t==="job"){const r=w("job",e.jobId??e.targetId??a.jobId);return r?{sql:" AND job_id = ?",params:[r]}:{sql:" AND 1 = 0",params:[]}}if(t==="goal"){const r=w("goal",e.goalId??e.targetId);if(!r)return{sql:" AND 1 = 0",params:[]};const s=ye(e.relatedJobIds);return{sql:` AND (job_id = ? OR json_extract(metadata_json, '$.goalId') = ?${s.length>0?` OR job_id IN (${s.map(()=>"?").join(", ")})`:""})`,params:[r,r,...s]}}if(t==="loop"){const r=w("loop",e.loopId??e.targetId);if(!r)return{sql:" AND 1 = 0",params:[]};const s=ye(e.relatedJobIds);return{sql:` AND (job_id = ? OR json_extract(metadata_json, '$.loopId') = ?${s.length>0?` OR job_id IN (${s.map(()=>"?").join(", ")})`:""})`,params:[r,r,...s]}}return{sql:" AND 1 = 0",params:[]}}function Ie(a){const e={event_id:a.event_id,job_id:a.job_id,execution_id:a.operation_id,public_summary:a.summary,reason_code:a.reason_code,created_at:a.created_at,metadata_json:a.metadata_json};return{...e,cursor:pt(e)}}function S(a){return a?(A(a,"metadata"),JSON.stringify(a)):null}function yt(a,e,t){const r=d=>`sha256:${k("sha256").update(d.map(n=>[n.id,n.status,n.reasonCode].join(":")).sort().join(`
2
- `)).digest("hex")}`,s=r(e),o=r(t);return{receipts:s,outputs:o,aggregate:`sha256:${k("sha256").update(`${a}:${s}:${o}`).digest("hex")}`}}function U(a){if(!a)return{};try{const e=JSON.parse(a);return E(e)?{...e}:{}}catch{return{}}}function be(a){if(!a)return[];try{const e=JSON.parse(a);return Array.isArray(e)?e:[]}catch{return[]}}function ft(a){return be(a).filter(e=>typeof e=="string")}function l(a,e,t,r=!1){if(a===void 0){if(r)throw new c("sqlite-public-safety-rejected",`Continuity SQLite text is required at ${e}.`);return}if(I(a,e),a.trim().length===0||a.length>t)throw new c("sqlite-public-safety-rejected",`Continuity SQLite text exceeded the public bound at ${e}.`)}function T(a,e){if(a!==void 0&&(!Number.isFinite(a)||a<0||Math.floor(a)!==a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite numeric value rejected at ${e}.`)}function M(a){l(a.outboxId,"outbox.outboxId",160,!0),l(a.jobId,"outbox.jobId",160),l(a.operationId,"outbox.operationId",160),l(a.idempotencyKey,"outbox.idempotencyKey",160),l(a.type,"outbox.type",80),l(a.status,"outbox.status",40),l(a.deliveryCursor,"outbox.deliveryCursor",200),l(a.timestamp,"outbox.timestamp",80),l(a.reasonCode,"outbox.reasonCode",100),l(a.summary,"outbox.summary",240)}function Ee(a){return a==="pending"||a==="sent"||a==="acked"||a==="failed"||a==="dead_letter"}function It(a){return typeof a=="string"&&Ee(a)?a:"failed"}function f(a){return typeof a=="string"&&a.length>0?a:void 0}function bt(a){if(typeof a!="string"||a.trim().length===0)return{};try{const e=JSON.parse(a);return E(e)?(A(e,"outbox.payload"),e):{}}catch{return{}}}function Et(a){return{outboxId:String(a.outbox_id??""),...f(a.job_id)?{jobId:f(a.job_id)}:{},operationId:String(a.operation_id??""),...f(a.idempotency_key)?{idempotencyKey:f(a.idempotency_key)}:{},type:String(a.type??""),status:It(a.status),payload:bt(a.payload_json),retryCount:typeof a.retry_count=="number"?a.retry_count:0,attemptCount:typeof a.attempt_count=="number"?a.attempt_count:0,...f(a.delivery_cursor)?{deliveryCursor:f(a.delivery_cursor)}:{},...f(a.next_attempt_at)?{nextAttemptAt:f(a.next_attempt_at)}:{},...f(a.last_attempt_at)?{lastAttemptAt:f(a.last_attempt_at)}:{},...f(a.sent_at)?{sentAt:f(a.sent_at)}:{},...f(a.acked_at)?{ackedAt:f(a.acked_at)}:{},...f(a.last_error_code)?{lastErrorCode:f(a.last_error_code)}:{},...f(a.last_error_reason)?{lastErrorReason:f(a.last_error_reason)}:{},...f(a.last_error_summary)?{lastErrorSummary:f(a.last_error_summary)}:{},...f(a.dead_letter_summary)?{deadLetterSummary:f(a.dead_letter_summary)}:{},...f(a.dead_lettered_at)?{deadLetteredAt:f(a.dead_lettered_at)}:{},createdAt:String(a.created_at??""),updatedAt:String(a.updated_at??""),publicSafe:!0}}function g(a){return{...a,publicSafe:!0}}function L(a,e){return a===void 0?null:(A(a,e),JSON.stringify(a))}function q(a){if(!a)return;const e=P(a.map(t=>t.replace(/\\/g,"/"))).filter(t=>t.length>0).slice(0,50);for(const[t,r]of e.entries()){l(r,`relativePaths[${t}]`,240,!0);const s=r.split("/").filter(Boolean);if(r.startsWith("/")||r.startsWith("~")||r.includes("://")||/^[A-Za-z]:\//.test(r)||s.includes(".."))throw new c("sqlite-public-safety-rejected",`Continuity SQLite rejected non-relative path at relativePaths[${t}].`)}return e}function Q(a){const e={...V(a.metadata),schemaVersion:1,contractVersion:"continuity-v1",attemptId:a.attemptId,executionId:a.executionId,jobId:a.jobId};return a.directiveHash&&(e.directiveHash=a.directiveHash),a.runtimeId&&(e.runtimeId=a.runtimeId),a.modelId&&(e.modelId=a.modelId),a.runtimeSource&&(e.runtimeSource=a.runtimeSource),a.status&&(e.attemptStatus=a.status),a.reasonCode&&(e.reasonCode=a.reasonCode),a.durationMs!==void 0&&(e.durationMs=a.durationMs),a.retryCount!==void 0&&(e.retryCount=a.retryCount),a.attemptCount!==void 0&&(e.attemptCount=a.attemptCount),a.maxAttempts!==void 0&&(e.maxAttempts=a.maxAttempts),a.queuePriority!==void 0&&(e.queuePriority=a.queuePriority),a.queueScope&&(e.queueScope=a.queueScope),a.nextRetryAt&&(e.nextRetryAt=a.nextRetryAt),a.deadLetterReasonCode&&(e.deadLetterReasonCode=a.deadLetterReasonCode),a.counts&&(e.counts=a.counts),a.hashes&&(e.hashes=a.hashes),a.redactionSummary&&(e.redactionEvidence=a.redactionSummary),a.relativePaths&&(e.relativePaths=q(a.relativePaths)),V(e)}function R(a){l(a.attemptId,"headless_execution.attemptId",160,!0),l(a.executionId,"headless_execution.executionId",160,!0),l(a.jobId,"headless_execution.jobId",160,!0),l(a.directiveHash,"headless_execution.directiveHash",160),l(a.targetRef,"headless_execution.targetRef",240),l(a.storyId,"headless_execution.storyId",120),l(a.epicId,"headless_execution.epicId",120),l(a.runtimeId,"headless_execution.runtimeId",80),l(a.modelId,"headless_execution.modelId",120),l(a.runtimeSource,"headless_execution.runtimeSource",40),l(a.reasonCode,"headless_execution.reasonCode",100),l(a.publicSummary,"headless_execution.publicSummary",240),l(a.leaseId,"headless_execution.leaseId",160),l(a.runnerId,"headless_execution.runnerId",160),l(a.timestamp,"headless_execution.timestamp",80)}function H(a){if(Array.isArray(a)){const e=a[0];return E(e)?Object.values(e)[0]:e}return E(a)?Object.values(a)[0]:a}function Ct(a){return at.includes(a)}function P(a){return Array.from(new Set(a))}function gt(a){const e=E(a)&&"default"in a?a.default:a;if(typeof e!="function")throw new c("sqlite-adapter-unavailable","Optional better-sqlite3 adapter did not export a database constructor.",{guidance:ce});const t=e;return{adapterName:"better-sqlite3",open(r,s){return new t(r,s)}}}async function St(a=it){try{const e=await a("better-sqlite3");return{ok:!0,adapter:gt(e)}}catch(e){return e instanceof c?{ok:!1,error:e}:{ok:!1,error:new c("sqlite-adapter-unavailable","Optional Enterprise continuity SQLite adapter better-sqlite3 is unavailable.",{cause:e,guidance:ce})}}}function Ce(a){return oe(a,de,Ke)}function At(a){const e=oe(a,de);re(e,{recursive:!0,mode:448});try{X(e,448)}catch{}return e}async function Bt(a){const e=a.adapter??await Se(a.adapterLoader),t=a.filePath??Ce(a.projectRoot);if(a.strictReadOnly)ge(t);else if(a.filePath){re(se(t),{recursive:!0,mode:448});try{X(se(t),448)}catch{}}else At(a.projectRoot);let r;try{r=e.open(t,a.strictReadOnly?{fileMustExist:!0,readonly:!0}:void 0)}catch(o){throw p(o,"sqlite-integrity-failed")}const s=new Rt({db:r,filePath:t,adapterName:e.adapterName,busyTimeoutMs:a.busyTimeoutMs??Ve,integrityCheck:a.integrityCheck??!0,now:a.now??(()=>new Date().toISOString())});try{if(a.strictReadOnly)return s.runIntegrityCheck(),s.getSchemaVersion(),s;if(s.initialize(),ae(t))try{X(t,384)}catch{}return s}catch(o){try{r.close()}catch{}throw o}}function ge(a){if(!ae(a))throw new c("sqlite-projection-missing","Continuity database is unavailable for physical read-only inspection.",{mutationBlocked:!0});let e;try{const t=Re(a,"r");try{if(e=z.alloc(20),Ne(t,e,0,e.length,0)<e.length)throw new Error("short-header")}finally{xe(t)}}catch(t){throw new c("sqlite-integrity-failed","Continuity database header could not be inspected read-only.",{cause:t,mutationBlocked:!0})}if(e.subarray(0,16).toString("ascii")!=="SQLite format 3\0")throw new c("sqlite-integrity-failed","Continuity database header is not a recognized SQLite database.",{mutationBlocked:!0});if(e[18]===2||e[19]===2)throw new c("sqlite-projection-wal-unsafe","Continuity database requires an unsafe WAL read profile.",{mutationBlocked:!0})}async function xt(a){const e=Ce(a.projectRoot);ge(e);const t=a.adapter??await Se(a.adapterLoader);let r,s=!1;try{r=t.open(e,{fileMustExist:!0,readonly:!0}),s=!0;const d=H(r.pragma("integrity_check",{simple:!0}));if(String(d).toLowerCase()!=="ok")throw new Error("integrity")}catch(d){throw new c(s?"sqlite-integrity-failed":"sqlite-projection-adapter-incompatible","Continuity database failed physical read-only inspection.",{cause:d,mutationBlocked:!0})}const o=d=>{const n=d.trim().replace(/^\(+/u,"").toLowerCase();if(!/^(select|with\s)/u.test(n)||/\b(insert|update|delete|replace|create|alter|drop|pragma|attach|detach|vacuum|reindex)\b/u.test(n))throw new c("sqlite-mutation-blocked","Statement is not in the physical read-only query profile.",{mutationBlocked:!0})};return Object.freeze({filePath:e,adapterName:t.adapterName,all(d,...n){return o(d),r.prepare(d).all(...n)},get(d,...n){return o(d),r.prepare(d).get(...n)},close(){r.close()}})}async function $t(a){if(!Number.isSafeInteger(a.authorityRevision)||a.authorityRevision<0||!/^[a-f0-9]{64}$/.test(a.sourceDigest))throw new c("sqlite-integrity-failed","Epic operational SQLite binding input is invalid.",{mutationBlocked:!0});let e;try{e=await xt(a);let t;try{t=e.all("SELECT sha256, metadata_json FROM state_snapshots WHERE kind = ? ORDER BY captured_at DESC LIMIT 2","epic-operational-state")}catch{return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:"unavailable",authorityRevision:a.authorityRevision,sourceDigest:null,adapterName:e.adapterName,reasonCodes:["sqlite-projection-schema-unsupported"],publicSafe:!0})}const r=t.filter(s=>{if(!E(s)||s.sha256!==a.sourceDigest||typeof s.metadata_json!="string")return!1;try{const o=JSON.parse(s.metadata_json);return E(o)&&o.authorityRevision===a.authorityRevision}catch{return!1}});return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:r.length===1?"bound":"unbound",authorityRevision:a.authorityRevision,sourceDigest:r.length===1?a.sourceDigest:null,adapterName:e.adapterName,reasonCodes:r.length===1?["epic-operational-sqlite-binding-verified"]:["epic-operational-projection-unbound"],publicSafe:!0})}catch(t){const r=t instanceof c?t.reasonCode:"sqlite-integrity-failed";return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:"unavailable",authorityRevision:a.authorityRevision,sourceDigest:null,adapterName:null,reasonCodes:[r],publicSafe:!0})}finally{e?.close()}}async function Se(a){const e=a?await a():await St();if(!e.ok)throw e.error;return e.adapter}class Rt{filePath;adapterName;db;busyTimeoutMs;integrityCheck;now;mutationBlocked=!1;constructor(e){this.db=e.db,this.filePath=e.filePath,this.adapterName=e.adapterName,this.busyTimeoutMs=e.busyTimeoutMs,this.integrityCheck=e.integrityCheck,this.now=e.now}initialize(){try{this.configureConnection(),this.integrityCheck&&this.runIntegrityCheck(),this.ensureMigrationTable(),this.applyMigrations(),this.integrityCheck&&this.runIntegrityCheck()}catch(e){throw p(e,"sqlite-migration-failed")}}close(){this.db.close()}pragmaValue(e){return H(this.db.pragma(e,{simple:!0}))}runIntegrityCheck(){try{if(String(H(this.db.pragma("integrity_check",{simple:!0}))??"").toLowerCase()!=="ok")throw this.mutationBlocked=!0,new c("sqlite-integrity-failed","Continuity SQLite integrity check failed; durable mutation is blocked until the store is repaired or rebuilt.",{mutationBlocked:!0})}catch(e){throw this.mutationBlocked=!0,p(e,"sqlite-integrity-failed")}}getSchemaVersion(){const e=this.db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM continuity_migrations").get();return E(e)&&typeof e.version=="number"?e.version:0}countRows(e){if(!Ct(e))throw new c("sqlite-public-safety-rejected","Unknown continuity table name.");const t=this.db.prepare(`SELECT COUNT(*) AS count FROM ${e}`).get();return E(t)&&typeof t.count=="number"?t.count:0}reserveNativeAgentDispatch(e){if(this.assertCanMutate(),!qe(e.binding)||!He(e.hostAttestation))throw new c("sqlite-public-safety-rejected","Native-agent reservation rejected invalid binding or host evidence.");const t={schemaVersion:1,storyId:e.binding.storyId,graphRevision:e.binding.graphRevision.replace(/^sha256:/,"").toLowerCase(),dispatchKey:e.binding.dispatchKey.toLowerCase(),profile:"neocortex",parentHandle:null,handle:null,topology:e.topology??"native-agent",state:"requested",requestedAt:e.requestedAt,observedAt:null,terminalAt:null,freshness:"unknown",observationSource:"local-reservation",reasonCode:e.reasonCode??"native-agent-dispatch-reserved",revision:0,publicSafe:!0};if(!Z(t))throw new c("sqlite-public-safety-rejected","Native-agent reservation rejected unsafe public fields.");try{return this.runInTransaction(()=>{const r=this.db.prepare(`
1
+ import{Buffer as z}from"node:buffer";import{createHash as M}from"node:crypto";import{chmodSync as X,closeSync as Ne,existsSync as re,mkdirSync as se,openSync as Oe,readSync as Te}from"node:fs";import{dirname as oe,join as ne}from"node:path";import{INITIAL_CONTINUITY_SQLITE_MIGRATION as Le}from"./migrations/001-initial-schema.js";import{PROCESSING_OUTPUT_SUMMARY_SQLITE_MIGRATION as ve}from"./migrations/002-processing-output-summary-indexes.js";import{HEADLESS_EXECUTION_ATTEMPTS_SQLITE_MIGRATION as je}from"./migrations/003-headless-execution-attempts.js";import{OUTBOX_DELIVERY_STATE_SQLITE_MIGRATION as De}from"./migrations/004-outbox-delivery-state.js";import{BOUNDED_HEADLESS_QUEUE_SQLITE_MIGRATION as Me}from"./migrations/005-bounded-headless-queue.js";import{NATIVE_AGENT_DISPATCHES_SQLITE_MIGRATION as ke}from"./migrations/006-native-agent-dispatches.js";import{NATIVE_LAUNCH_RETRY_SQLITE_MIGRATION as we}from"./migrations/007-native-launch-retry.js";import{isNativeLaunchRefusal as Ue,nativeLaunchRetryKey as qe}from"../../../shared/dist/yoloop/native-launch-retry.js";import{NATIVE_AGENT_TERMINAL_STATES as de,isNativeAgentDispatchReceiptV1 as Z,isNativeAgentStateTransitionAllowed as He,isNativeDispatchBindingV1 as Pe,isNativeHostAttestationV1 as We}from"./native-agent-types.js";import{CONTINUITY_QUEUE_REASON_CODES as v,CONTINUITY_RECEIPT_COMPACTION_EVENT_TYPE as B,CONTINUITY_RECEIPT_RETENTION_REASON_CODES as $,DEFAULT_CONTINUITY_QUEUE_POLICY as Fe,computeContinuityQueueRetryAt as Be,computeContinuityOutboxFailureDecision as $e,normalizeContinuityQueuePolicy as Y,normalizeContinuityQueuePriority as Ye,normalizeContinuityQueueScope as Ke,normalizeContinuityRetentionPolicy as Ve}from"./outbox.js";const ie=".neocortex/continuity",Qe="continuity.sqlite",$t=7,Je=5e3,O="processing_output_summary",Ge=2e3,ce=20,ze=100,ee="Install the optional Enterprise continuity SQLite adapter with `npm install --workspace packages/client better-sqlite3 --include=optional` or reinstall Neocortex with optional dependencies enabled.",Xe=Object.freeze(["discover_more","create_epic","run_yoloop","run_yolo","run_verifier","run_review_gate","compact_context","wait_external","backoff","waiting_human","complete","abort","scheduled","running","overlap_skipped","missed_run_catchup","completed","aborted","cancelled","blocked","draft","planned"]),le=20,Ze=new Set(Xe),et=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;function ue(a){return typeof a=="string"&&Ze.has(a)}function _e(a){if(typeof a!="string")return;const e=a.trim();if(!(e.length===0||e.length>40)&&et.test(e))return e}function tt(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(!E(t)||!ue(t.stage))continue;const r=_e(t.at);r&&e.push({stage:t.stage,at:r})}return e.slice(-le)}function at(a){if(!(typeof a!="number"||!Number.isFinite(a)||a<0))return Math.floor(a)}class c extends Error{code;reasonCode;guidance;mutationBlocked;cause;constructor(e,t,r={}){super(t),this.name="ContinuitySqliteStoreError",this.code=e,this.reasonCode=e,this.guidance=r.guidance,this.cause=r.cause,this.mutationBlocked=r.mutationBlocked??e==="sqlite-integrity-failed"}}function j(a){const e=Object.freeze({schemaVersion:1,storyId:a.story_id,graphRevision:a.graph_revision,dispatchKey:a.dispatch_key,profile:a.profile,parentHandle:a.parent_handle,handle:a.handle,topology:a.topology,state:a.state,requestedAt:a.requested_at,observedAt:a.observed_at,terminalAt:a.terminal_at,freshness:a.freshness,observationSource:a.observation_source,reasonCode:a.reason_code,revision:a.revision,publicSafe:!0});if(!Z(e))throw new c("sqlite-integrity-failed","Native-agent receipt failed its closed public contract.",{mutationBlocked:!0});return e}const rt=[Le,ve,je,De,Me,ke,we],st=Object.freeze(["continuity_migrations","jobs","job_leases","job_events","job_receipts","goal_campaigns","goal_ledger_items","goal_verifiers","goal_review_gates","loop_jobs","artifacts","state_snapshots","headless_execution_attempts","runner_config","outbox","native_agent_dispatches","native_agent_observations"]),me=/(raw[_-]?(?:logs?|payloads?)|std(?:out|err)|stack(?:[_-]?trace)?|transcript|objective(?:[_-]?(?:text|body|prompt))|prompt(?:[_-]?(?:body|text))?|private[_-]?(?:urls?|prompts?)|secret|token|password|protected(?:[_-]?(?:field|body|bodies|internals))?|workflow(?:[_-]?body)?|step(?:[_-]?body)?|customer(?:[_-]?(?:pii|data))?|\bpii\b|authorization|api[_-]?key|license[_-]?key|argv|args|executable(?:[_-]?path)?|binary(?:[_-]?path)?|shell|cwd|command[_-]?path|vendor(?:[_-]?(?:payload|corpus|response|output)))/i,pe=/(https?:\/\/\S+|(?:^|\s)(?:\/(?:home|Users|media|mnt|tmp|var|etc|private)\/\S+|[A-Za-z]:\\\S+)|ghp_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]+|-----BEGIN [A-Z ]*PRIVATE KEY-----|authorization\s*:|password\s*=|token\s*=|api[_-]?key\s*=|license[_-]?key\s*=|raw[_ -]?(?:logs?|outputs?)\s*[:=]|transcript|stack\s*trace|stderr:|stdout:|system prompt|prompt[_ -]?(?:body|text)|workflow body|step body|\bargv\b|(?:bash|sh|zsh|powershell|pwsh)\s+-c\b|(?:\.{0,2}\/|[A-Za-z]:\\|\/)[^\s]*(?:\.exe|\.bat|\.cmd|\.ps1|\.sh|\/bin\/[^\s]+)|\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b|PROTECTED_|PRIVATE_INTERNALS|CUSTOMER_PII|\bPII\b|VENDOR_CORPUS|P180[_-]?SYNTHETIC[_-]?CONTINUITY|P185[_-]?SYNTHETIC[_-]?CONTINUITY|P187[_-]?SYNTHETIC[_-]?(?:CONTINUITY|RUNNER|WATCH)|P190[_-]?SYNTHETIC[_-]?(?:HEADLESS|CONTINUITY)|P192[_-]?SYNTHETIC[_-]?(?:PORTAL|RUNNER|SYNC))/i,ot=new Set(["unsafe_key","raw_log","prompt_body","private_url","local_absolute_path","secret","protected_field","unbounded_text","unbounded_number","unknown_required_operation","missing"]),nt=/(corrupt|malformed|not a database|file is not a database|database disk image is malformed)/i,dt=/(foreign key constraint failed|SQLITE_CONSTRAINT_FOREIGNKEY)/i,te="p185:v1:",it=new Set(["schemaVersion","contractVersion","eventType","executionId","jobId","operationId","idempotencyKey","goalId","loopId","campaignId","itemId","ledgerItemIds","verifierId","verifierIds","gateId","reviewGateIds","runnerId","leaseId","status","reasonCode","reasonCodes","runtimeId","modelId","runtimeSource","headlessRuntime","headlessModel","headlessRuntimeReasonCode","originRuntime","originModel","targetRef","attemptId","attemptStatus","terminalClass","releaseBlocked","directiveHash","timeoutMs","leaseExpiresAt","heartbeatAt","notBeforeAt","maxAttempts","counts","hashes","relativePaths","artifactRefs","evidenceRefs","validationRefs","registryRefs","storyIds","epicIds","debtIds","iteration","currentStage","stageHistory","durationMs","retryCount","attemptCount","queuePriority","queueScope","queueCap","queueDepth","queueAvailable","queueBackpressure","nextTickAt","nextAttemptAt","nextRetryAt","deadLetterReasonCode","deliveryCursor","lastAttemptAt","sentAt","ackedAt","lastErrorReason","lastErrorSummary","deadLetterSummary","deadLetteredAt","processingOutputSource","publicSummary","redactionEvidence","selectorKind","targetId","targetJobId","relatedJobIds","serverAccessToLocalhost","serverHeldStream","initialCursor","targetResolutionState","targetKind","relatedJobCount","snapshotStatus","snapshotGeneratedAt","renderedSummaryCount","cursorState","currentCursor","nextCursor","cursorAdvanced","eventId","latestEventId","watchStatus","stopReason","syncVersion","transportKind","envelopeId","workspaceId","workspaceLabel","projectId","projectLabel","snapshotId","syncCursor","previousSyncCursor","nextSyncCursor","commandId","receiptId","acknowledgedAt","observedAt","generatedAt","syncStatus","commandStatus","receiptStatus","actorType","actorId","tenantId","commandKind","auditStatus","redactionCount","autonomousGovernance","governanceVersion","governanceEvidence","governanceSource","publicSafe"]),ct=new Set(["foreground_invoke","scheduled_tick","runner_tick","manual_tick","headless_execution","jobs_command","invoke_watch","portal_render"]);function lt(a){return import(a)}function ut(a){return`sha256:${M("sha256").update(a).digest("hex")}`}function E(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function he(a){return a instanceof Error?a.message:String(a)}function ye(a){return E(a)&&typeof a.code=="string"?a.code:void 0}function p(a,e){if(a instanceof c)return a;const t=he(a),r=ye(a);return r==="SQLITE_CORRUPT"||r==="SQLITE_NOTADB"||nt.test(t)?new c("sqlite-integrity-failed","Continuity SQLite integrity check failed; durable mutation is blocked until the store is repaired or rebuilt.",{cause:a,mutationBlocked:!0}):r==="SQLITE_CONSTRAINT_FOREIGNKEY"||dt.test(t)?new c("sqlite-foreign-key-failed","Continuity SQLite foreign-key validation failed; mutation was rejected.",{cause:a}):new c(e,t,{cause:a})}const _t=/better_sqlite3\.node|could not locate the bindings file|node_module_version|module did not self-register/i;function mt(a,e){const t=he(a),r=ye(a);return e==="better-sqlite3"&&(r==="ERR_DLOPEN_FAILED"||_t.test(t))?new c("sqlite-adapter-unavailable","Optional Enterprise continuity SQLite adapter better-sqlite3 could not load its native binding.",{cause:a,guidance:ee}):p(a,"sqlite-integrity-failed")}function A(a,e){if(typeof a=="string"){if(/\.(?:redactionEvidence|redactionSummary)\[\d+\]\.field$/.test(e)&&/^[A-Za-z0-9_.:[\]-]{1,120}$/.test(a)||/\.(?:redactionEvidence|redactionSummary)\[\d+\]\.reason$/.test(e)&&ot.has(a))return;if(pe.test(a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe value at ${e}.`);return}if(!(a===null||typeof a=="number"||typeof a=="boolean")){if(Array.isArray(a)){a.forEach((t,r)=>A(t,`${e}[${r}]`));return}if(E(a)){for(const[t,r]of Object.entries(a)){const s=t==="terminationToken"&&e.endsWith(".releaseBlocked")&&r==="[YOLOOP_RELEASE_BLOCKED]";if(me.test(t)&&!s)throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe key at ${e}.${t}.`);A(r,`${e}.${t}`)}return}throw new c("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsupported value at ${e}.`)}}function I(a,e){if(a!==void 0&&pe.test(a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite text rejected unsafe value at ${e}.`)}function K(a,e,t=240){if(a.trim().length===0)throw new c("sqlite-public-safety-rejected",`Continuity SQLite processing summary text is required at ${e}.`);if(I(a,e),a.length>t)throw new c("sqlite-public-safety-rejected",`Continuity SQLite processing summary text exceeded the public bound at ${e}.`)}function V(a){const e={};if(!a)return e;for(const[t,r]of Object.entries(a))if(it.has(t)&&!me.test(t))try{A(r,`metadata.${t}`),e[t]=r}catch{}return e}function pt(a){const e={...V(a.metadata),schemaVersion:1,contractVersion:"continuity-v1",eventType:O,executionId:a.executionId,jobId:a.jobId,operationId:a.executionId,publicSummary:a.publicSummary};return a.idempotencyKey&&(e.idempotencyKey=a.idempotencyKey),a.goalId&&(e.goalId=a.goalId),a.loopId&&(e.loopId=a.loopId),a.reasonCode&&(e.reasonCode=a.reasonCode),a.source&&ct.has(a.source)&&(e.processingOutputSource=a.source),V(e)}function fe(a){const e=Math.floor(a??ce);return Number.isFinite(e)?Math.max(1,Math.min(ze,e)):ce}function ht(a){if(a.eventId&&a.eventId.trim().length>0)return a.eventId;const e=a.executionId.replace(/[^a-z0-9_.:-]+/gi,"-").replace(/^-+|-+$/g,"");return e.length>0?`event-processing-summary-${e.slice(0,160)}`:`event-processing-summary-${M("sha256").update(a.executionId).digest("hex").slice(0,32)}`}function yt(a){return`${te}${z.from(JSON.stringify([a.created_at,a.event_id]),"utf8").toString("base64url")}`}function ft(a){if(a?.startsWith(te))try{const e=a.slice(te.length),t=JSON.parse(z.from(e,"base64url").toString("utf8"));if(!Array.isArray(t)||t.length!==2)return;const[r,s]=t;return typeof r!="string"||typeof s!="string"?void 0:{createdAt:r,eventId:s}}catch{return}}function w(a,e){if(!e)return;const t=e.trim().replace(/^@/,"");if(a==="job"&&/^job-J\d{3,}$/i.test(t))return`job-J${t.match(/\d+$/)?.[0]??""}`;if(a==="goal"&&/^goal-G\d{3,}$/i.test(t))return`goal-G${t.match(/\d+$/)?.[0]??""}`;if(a==="loop"&&/^loop-L\d{3,}$/i.test(t))return`loop-L${t.match(/\d+$/)?.[0]??""}`}function Ie(a){return a?P(a.map(e=>w("job",e)).filter(e=>!!e)):[]}function be(a){const e=a.target;if(!e){const r=w("job",a.jobId);return r?{sql:" AND job_id = ?",params:[r]}:{sql:"",params:[]}}const t=e.selectorKind;if(t==="job"){const r=w("job",e.jobId??e.targetId??a.jobId);return r?{sql:" AND job_id = ?",params:[r]}:{sql:" AND 1 = 0",params:[]}}if(t==="goal"){const r=w("goal",e.goalId??e.targetId);if(!r)return{sql:" AND 1 = 0",params:[]};const s=Ie(e.relatedJobIds);return{sql:` AND (job_id = ? OR json_extract(metadata_json, '$.goalId') = ?${s.length>0?` OR job_id IN (${s.map(()=>"?").join(", ")})`:""})`,params:[r,r,...s]}}if(t==="loop"){const r=w("loop",e.loopId??e.targetId);if(!r)return{sql:" AND 1 = 0",params:[]};const s=Ie(e.relatedJobIds);return{sql:` AND (job_id = ? OR json_extract(metadata_json, '$.loopId') = ?${s.length>0?` OR job_id IN (${s.map(()=>"?").join(", ")})`:""})`,params:[r,r,...s]}}return{sql:" AND 1 = 0",params:[]}}function Ee(a){const e={event_id:a.event_id,job_id:a.job_id,execution_id:a.operation_id,public_summary:a.summary,reason_code:a.reason_code,created_at:a.created_at,metadata_json:a.metadata_json};return{...e,cursor:yt(e)}}function S(a){return a?(A(a,"metadata"),JSON.stringify(a)):null}function It(a,e,t){const r=d=>`sha256:${M("sha256").update(d.map(n=>[n.id,n.status,n.reasonCode].join(":")).sort().join(`
2
+ `)).digest("hex")}`,s=r(e),o=r(t);return{receipts:s,outputs:o,aggregate:`sha256:${M("sha256").update(`${a}:${s}:${o}`).digest("hex")}`}}function U(a){if(!a)return{};try{const e=JSON.parse(a);return E(e)?{...e}:{}}catch{return{}}}function Ce(a){if(!a)return[];try{const e=JSON.parse(a);return Array.isArray(e)?e:[]}catch{return[]}}function bt(a){return Ce(a).filter(e=>typeof e=="string")}function l(a,e,t,r=!1){if(a===void 0){if(r)throw new c("sqlite-public-safety-rejected",`Continuity SQLite text is required at ${e}.`);return}if(I(a,e),a.trim().length===0||a.length>t)throw new c("sqlite-public-safety-rejected",`Continuity SQLite text exceeded the public bound at ${e}.`)}function T(a,e){if(a!==void 0&&(!Number.isFinite(a)||a<0||Math.floor(a)!==a))throw new c("sqlite-public-safety-rejected",`Continuity SQLite numeric value rejected at ${e}.`)}function D(a){l(a.outboxId,"outbox.outboxId",160,!0),l(a.jobId,"outbox.jobId",160),l(a.operationId,"outbox.operationId",160),l(a.idempotencyKey,"outbox.idempotencyKey",160),l(a.type,"outbox.type",80),l(a.status,"outbox.status",40),l(a.deliveryCursor,"outbox.deliveryCursor",200),l(a.timestamp,"outbox.timestamp",80),l(a.reasonCode,"outbox.reasonCode",100),l(a.summary,"outbox.summary",240)}function ge(a){return a==="pending"||a==="sent"||a==="acked"||a==="failed"||a==="dead_letter"}function Et(a){return typeof a=="string"&&ge(a)?a:"failed"}function f(a){return typeof a=="string"&&a.length>0?a:void 0}function Ct(a){if(typeof a!="string"||a.trim().length===0)return{};try{const e=JSON.parse(a);return E(e)?(A(e,"outbox.payload"),e):{}}catch{return{}}}function gt(a){return{outboxId:String(a.outbox_id??""),...f(a.job_id)?{jobId:f(a.job_id)}:{},operationId:String(a.operation_id??""),...f(a.idempotency_key)?{idempotencyKey:f(a.idempotency_key)}:{},type:String(a.type??""),status:Et(a.status),payload:Ct(a.payload_json),retryCount:typeof a.retry_count=="number"?a.retry_count:0,attemptCount:typeof a.attempt_count=="number"?a.attempt_count:0,...f(a.delivery_cursor)?{deliveryCursor:f(a.delivery_cursor)}:{},...f(a.next_attempt_at)?{nextAttemptAt:f(a.next_attempt_at)}:{},...f(a.last_attempt_at)?{lastAttemptAt:f(a.last_attempt_at)}:{},...f(a.sent_at)?{sentAt:f(a.sent_at)}:{},...f(a.acked_at)?{ackedAt:f(a.acked_at)}:{},...f(a.last_error_code)?{lastErrorCode:f(a.last_error_code)}:{},...f(a.last_error_reason)?{lastErrorReason:f(a.last_error_reason)}:{},...f(a.last_error_summary)?{lastErrorSummary:f(a.last_error_summary)}:{},...f(a.dead_letter_summary)?{deadLetterSummary:f(a.dead_letter_summary)}:{},...f(a.dead_lettered_at)?{deadLetteredAt:f(a.dead_lettered_at)}:{},createdAt:String(a.created_at??""),updatedAt:String(a.updated_at??""),publicSafe:!0}}function g(a){return{...a,publicSafe:!0}}function L(a,e){return a===void 0?null:(A(a,e),JSON.stringify(a))}function q(a){if(!a)return;const e=P(a.map(t=>t.replace(/\\/g,"/"))).filter(t=>t.length>0).slice(0,50);for(const[t,r]of e.entries()){l(r,`relativePaths[${t}]`,240,!0);const s=r.split("/").filter(Boolean);if(r.startsWith("/")||r.startsWith("~")||r.includes("://")||/^[A-Za-z]:\//.test(r)||s.includes(".."))throw new c("sqlite-public-safety-rejected",`Continuity SQLite rejected non-relative path at relativePaths[${t}].`)}return e}function Q(a){const e={...V(a.metadata),schemaVersion:1,contractVersion:"continuity-v1",attemptId:a.attemptId,executionId:a.executionId,jobId:a.jobId};return a.directiveHash&&(e.directiveHash=a.directiveHash),a.runtimeId&&(e.runtimeId=a.runtimeId),a.modelId&&(e.modelId=a.modelId),a.runtimeSource&&(e.runtimeSource=a.runtimeSource),a.status&&(e.attemptStatus=a.status),a.reasonCode&&(e.reasonCode=a.reasonCode),a.durationMs!==void 0&&(e.durationMs=a.durationMs),a.retryCount!==void 0&&(e.retryCount=a.retryCount),a.attemptCount!==void 0&&(e.attemptCount=a.attemptCount),a.maxAttempts!==void 0&&(e.maxAttempts=a.maxAttempts),a.queuePriority!==void 0&&(e.queuePriority=a.queuePriority),a.queueScope&&(e.queueScope=a.queueScope),a.nextRetryAt&&(e.nextRetryAt=a.nextRetryAt),a.deadLetterReasonCode&&(e.deadLetterReasonCode=a.deadLetterReasonCode),a.counts&&(e.counts=a.counts),a.hashes&&(e.hashes=a.hashes),a.redactionSummary&&(e.redactionEvidence=a.redactionSummary),a.relativePaths&&(e.relativePaths=q(a.relativePaths)),V(e)}function R(a){l(a.attemptId,"headless_execution.attemptId",160,!0),l(a.executionId,"headless_execution.executionId",160,!0),l(a.jobId,"headless_execution.jobId",160,!0),l(a.directiveHash,"headless_execution.directiveHash",160),l(a.targetRef,"headless_execution.targetRef",240),l(a.storyId,"headless_execution.storyId",120),l(a.epicId,"headless_execution.epicId",120),l(a.runtimeId,"headless_execution.runtimeId",80),l(a.modelId,"headless_execution.modelId",120),l(a.runtimeSource,"headless_execution.runtimeSource",40),l(a.reasonCode,"headless_execution.reasonCode",100),l(a.publicSummary,"headless_execution.publicSummary",240),l(a.leaseId,"headless_execution.leaseId",160),l(a.runnerId,"headless_execution.runnerId",160),l(a.timestamp,"headless_execution.timestamp",80)}function H(a){if(Array.isArray(a)){const e=a[0];return E(e)?Object.values(e)[0]:e}return E(a)?Object.values(a)[0]:a}function St(a){return st.includes(a)}function P(a){return Array.from(new Set(a))}function At(a){const e=E(a)&&"default"in a?a.default:a;if(typeof e!="function")throw new c("sqlite-adapter-unavailable","Optional better-sqlite3 adapter did not export a database constructor.",{guidance:ee});const t=e;return{adapterName:"better-sqlite3",open(r,s){return new t(r,s)}}}async function xt(a=lt){try{const e=await a("better-sqlite3");return{ok:!0,adapter:At(e)}}catch(e){return e instanceof c?{ok:!1,error:e}:{ok:!1,error:new c("sqlite-adapter-unavailable","Optional Enterprise continuity SQLite adapter better-sqlite3 is unavailable.",{cause:e,guidance:ee})}}}function Se(a){return ne(a,ie,Qe)}function Rt(a){const e=ne(a,ie);se(e,{recursive:!0,mode:448});try{X(e,448)}catch{}return e}async function Yt(a){const e=a.adapter??await xe(a.adapterLoader),t=a.filePath??Se(a.projectRoot);if(a.strictReadOnly)Ae(t);else if(a.filePath){se(oe(t),{recursive:!0,mode:448});try{X(oe(t),448)}catch{}}else Rt(a.projectRoot);let r;try{r=e.open(t,a.strictReadOnly?{fileMustExist:!0,readonly:!0}:void 0)}catch(o){throw mt(o,e.adapterName)}const s=new Ot({db:r,filePath:t,adapterName:e.adapterName,busyTimeoutMs:a.busyTimeoutMs??Je,integrityCheck:a.integrityCheck??!0,now:a.now??(()=>new Date().toISOString())});try{if(a.strictReadOnly)return s.runIntegrityCheck(),s.getSchemaVersion(),s;if(s.initialize(),re(t))try{X(t,384)}catch{}return s}catch(o){try{r.close()}catch{}throw o}}function Ae(a){if(!re(a))throw new c("sqlite-projection-missing","Continuity database is unavailable for physical read-only inspection.",{mutationBlocked:!0});let e;try{const t=Oe(a,"r");try{if(e=z.alloc(20),Te(t,e,0,e.length,0)<e.length)throw new Error("short-header")}finally{Ne(t)}}catch(t){throw new c("sqlite-integrity-failed","Continuity database header could not be inspected read-only.",{cause:t,mutationBlocked:!0})}if(e.subarray(0,16).toString("ascii")!=="SQLite format 3\0")throw new c("sqlite-integrity-failed","Continuity database header is not a recognized SQLite database.",{mutationBlocked:!0});if(e[18]===2||e[19]===2)throw new c("sqlite-projection-wal-unsafe","Continuity database requires an unsafe WAL read profile.",{mutationBlocked:!0})}async function Nt(a){const e=Se(a.projectRoot);Ae(e);const t=a.adapter??await xe(a.adapterLoader);let r,s=!1;try{r=t.open(e,{fileMustExist:!0,readonly:!0}),s=!0;const d=H(r.pragma("integrity_check",{simple:!0}));if(String(d).toLowerCase()!=="ok")throw new Error("integrity")}catch(d){throw new c(s?"sqlite-integrity-failed":"sqlite-projection-adapter-incompatible","Continuity database failed physical read-only inspection.",{cause:d,mutationBlocked:!0})}const o=d=>{const n=d.trim().replace(/^\(+/u,"").toLowerCase();if(!/^(select|with\s)/u.test(n)||/\b(insert|update|delete|replace|create|alter|drop|pragma|attach|detach|vacuum|reindex)\b/u.test(n))throw new c("sqlite-mutation-blocked","Statement is not in the physical read-only query profile.",{mutationBlocked:!0})};return Object.freeze({filePath:e,adapterName:t.adapterName,all(d,...n){return o(d),r.prepare(d).all(...n)},get(d,...n){return o(d),r.prepare(d).get(...n)},close(){r.close()}})}async function Kt(a){if(!Number.isSafeInteger(a.authorityRevision)||a.authorityRevision<0||!/^[a-f0-9]{64}$/.test(a.sourceDigest))throw new c("sqlite-integrity-failed","Epic operational SQLite binding input is invalid.",{mutationBlocked:!0});let e;try{e=await Nt(a);let t;try{t=e.all("SELECT sha256, metadata_json FROM state_snapshots WHERE kind = ? ORDER BY captured_at DESC LIMIT 2","epic-operational-state")}catch{return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:"unavailable",authorityRevision:a.authorityRevision,sourceDigest:null,adapterName:e.adapterName,reasonCodes:["sqlite-projection-schema-unsupported"],publicSafe:!0})}const r=t.filter(s=>{if(!E(s)||s.sha256!==a.sourceDigest||typeof s.metadata_json!="string")return!1;try{const o=JSON.parse(s.metadata_json);return E(o)&&o.authorityRevision===a.authorityRevision}catch{return!1}});return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:r.length===1?"bound":"unbound",authorityRevision:a.authorityRevision,sourceDigest:r.length===1?a.sourceDigest:null,adapterName:e.adapterName,reasonCodes:r.length===1?["epic-operational-sqlite-binding-verified"]:["epic-operational-projection-unbound"],publicSafe:!0})}catch(t){const r=t instanceof c?t.reasonCode:"sqlite-integrity-failed";return Object.freeze({schemaVersion:"EpicOperationalSqliteBindingInspection/1.0",status:"unavailable",authorityRevision:a.authorityRevision,sourceDigest:null,adapterName:null,reasonCodes:[r],publicSafe:!0})}finally{e?.close()}}async function xe(a){const e=a?await a():await xt();if(!e.ok)throw e.error;return e.adapter}class Ot{filePath;adapterName;db;busyTimeoutMs;integrityCheck;now;mutationBlocked=!1;constructor(e){this.db=e.db,this.filePath=e.filePath,this.adapterName=e.adapterName,this.busyTimeoutMs=e.busyTimeoutMs,this.integrityCheck=e.integrityCheck,this.now=e.now}initialize(){try{this.configureConnection(),this.integrityCheck&&this.runIntegrityCheck(),this.ensureMigrationTable(),this.applyMigrations(),this.integrityCheck&&this.runIntegrityCheck()}catch(e){throw p(e,"sqlite-migration-failed")}}close(){this.db.close()}pragmaValue(e){return H(this.db.pragma(e,{simple:!0}))}runIntegrityCheck(){try{if(String(H(this.db.pragma("integrity_check",{simple:!0}))??"").toLowerCase()!=="ok")throw this.mutationBlocked=!0,new c("sqlite-integrity-failed","Continuity SQLite integrity check failed; durable mutation is blocked until the store is repaired or rebuilt.",{mutationBlocked:!0})}catch(e){throw this.mutationBlocked=!0,p(e,"sqlite-integrity-failed")}}getSchemaVersion(){const e=this.db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM continuity_migrations").get();return E(e)&&typeof e.version=="number"?e.version:0}countRows(e){if(!St(e))throw new c("sqlite-public-safety-rejected","Unknown continuity table name.");const t=this.db.prepare(`SELECT COUNT(*) AS count FROM ${e}`).get();return E(t)&&typeof t.count=="number"?t.count:0}reserveNativeAgentDispatch(e){if(this.assertCanMutate(),!Pe(e.binding)||!We(e.hostAttestation))throw new c("sqlite-public-safety-rejected","Native-agent reservation rejected invalid binding or host evidence.");const t={schemaVersion:1,storyId:e.binding.storyId,graphRevision:e.binding.graphRevision.replace(/^sha256:/,"").toLowerCase(),dispatchKey:e.binding.dispatchKey.toLowerCase(),profile:"neocortex",parentHandle:null,handle:null,topology:e.topology??"native-agent",state:"requested",requestedAt:e.requestedAt,observedAt:null,terminalAt:null,freshness:"unknown",observationSource:"local-reservation",reasonCode:e.reasonCode??"native-agent-dispatch-reserved",revision:0,publicSafe:!0};if(!Z(t))throw new c("sqlite-public-safety-rejected","Native-agent reservation rejected unsafe public fields.");try{return this.runInTransaction(()=>{const r=this.db.prepare(`
3
3
  SELECT * FROM native_agent_dispatches
4
4
  WHERE dispatch_key = ? OR (story_id = ? AND graph_revision = ?)
5
- `).all(t.dispatchKey,t.storyId,t.graphRevision),s=r.find(n=>n.dispatch_key===t.dispatchKey);if(s){if(s.story_id!==t.storyId||s.graph_revision!==t.graphRevision)throw new Error("native-agent-reservation-binding-conflict");return Object.freeze({receipt:j(s),reserved:!1,replay:!0})}if(r.length>0){const n=r.length===1?j(r[0]):null;if(!n||!De(n)||t.topology!=="native-agent"||e.hostAttestation.hostKind==="unknown"||e.hostAttestation.origin==="explicit-override"||t.dispatchKey!==we(n.dispatchKey))throw new Error("native-agent-reservation-binding-conflict")}const o=this.db.prepare(`
5
+ `).all(t.dispatchKey,t.storyId,t.graphRevision),s=r.find(n=>n.dispatch_key===t.dispatchKey);if(s){if(s.story_id!==t.storyId||s.graph_revision!==t.graphRevision)throw new Error("native-agent-reservation-binding-conflict");return Object.freeze({receipt:j(s),reserved:!1,replay:!0})}if(r.length>0){const n=r.length===1?j(r[0]):null;if(!n||!Ue(n)||t.topology!=="native-agent"||e.hostAttestation.hostKind==="unknown"||e.hostAttestation.origin==="explicit-override"||t.dispatchKey!==qe(n.dispatchKey))throw new Error("native-agent-reservation-binding-conflict")}const o=this.db.prepare(`
6
6
  INSERT INTO native_agent_dispatches (
7
7
  dispatch_key, story_id, graph_revision, profile,
8
8
  host_kind, host_version, host_origin, host_confidence,
9
9
  parent_handle, handle, topology, state, requested_at, observed_at,
10
10
  terminal_at, freshness, observation_source, reason_code, revision
11
11
  ) VALUES (?, ?, ?, 'neocortex', ?, ?, ?, ?, NULL, NULL, ?, 'requested', ?, NULL, NULL, 'unknown', 'local-reservation', ?, 0)
12
- `).run(t.dispatchKey,t.storyId,t.graphRevision,e.hostAttestation.hostKind,e.hostAttestation.hostVersion,e.hostAttestation.origin,e.hostAttestation.confidence,t.topology,t.requestedAt,t.reasonCode),d=this.findNativeAgentDispatchRow(t.dispatchKey,t.storyId,t.graphRevision);if(!d)throw new Error("native-agent-reservation-readback-missing");if(d.dispatch_key!==t.dispatchKey||d.story_id!==t.storyId||d.graph_revision!==t.graphRevision)throw new c("sqlite-mutation-failed","Native-agent reservation conflicts with an existing story graph binding.");return Object.freeze({receipt:j(d),reserved:o.changes===1,replay:o.changes===0})})}catch(r){throw p(r,"sqlite-mutation-failed")}}observeNativeAgentDispatch(e){this.assertCanMutate();try{return this.runInTransaction(()=>{const t=this.db.prepare("SELECT * FROM native_agent_dispatches WHERE dispatch_key = ?").get(e.dispatchKey);if(!t)throw new c("sqlite-mutation-failed","Native-agent dispatch reservation is missing.");const r=j(t),s=ne.has(e.state)?e.terminalAt??e.observedAt:null,o=e.handle??r.handle,d=e.parentHandle===void 0?r.parentHandle:e.parentHandle,n={...r,handle:o,parentHandle:d,topology:e.topology,state:e.state,observedAt:e.observedAt,terminalAt:s,freshness:e.freshness,observationSource:e.observationSource,reasonCode:e.reasonCode,revision:r.revision+1};if(!Z(n))throw new c("sqlite-public-safety-rejected","Native-agent observation rejected unsafe or inconsistent fields.");if(r.handle&&e.handle&&r.handle!==e.handle)throw new c("sqlite-mutation-failed","Native-agent observation handle conflicts with the reserved dispatch.");if(!Ue(r.state,e.state))throw new c("sqlite-mutation-failed","Native-agent observation attempted a terminal or non-monotonic regression.");if(r.state===n.state&&r.handle===n.handle&&r.parentHandle===n.parentHandle&&r.topology===n.topology&&r.observedAt===n.observedAt&&r.terminalAt===n.terminalAt&&r.freshness===n.freshness&&r.observationSource===n.observationSource&&r.reasonCode===n.reasonCode)return Object.freeze({receipt:r,applied:!1,replay:!0});if(e.expectedRevision!==r.revision)throw new c("sqlite-mutation-failed","Native-agent observation CAS revision conflict.");if(r.observedAt&&Date.parse(e.observedAt)<Date.parse(r.observedAt))throw new c("sqlite-mutation-failed","Native-agent observation timestamp regressed.");if(this.db.prepare(`
12
+ `).run(t.dispatchKey,t.storyId,t.graphRevision,e.hostAttestation.hostKind,e.hostAttestation.hostVersion,e.hostAttestation.origin,e.hostAttestation.confidence,t.topology,t.requestedAt,t.reasonCode),d=this.findNativeAgentDispatchRow(t.dispatchKey,t.storyId,t.graphRevision);if(!d)throw new Error("native-agent-reservation-readback-missing");if(d.dispatch_key!==t.dispatchKey||d.story_id!==t.storyId||d.graph_revision!==t.graphRevision)throw new c("sqlite-mutation-failed","Native-agent reservation conflicts with an existing story graph binding.");return Object.freeze({receipt:j(d),reserved:o.changes===1,replay:o.changes===0})})}catch(r){throw p(r,"sqlite-mutation-failed")}}observeNativeAgentDispatch(e){this.assertCanMutate();try{return this.runInTransaction(()=>{const t=this.db.prepare("SELECT * FROM native_agent_dispatches WHERE dispatch_key = ?").get(e.dispatchKey);if(!t)throw new c("sqlite-mutation-failed","Native-agent dispatch reservation is missing.");const r=j(t),s=de.has(e.state)?e.terminalAt??e.observedAt:null,o=e.handle??r.handle,d=e.parentHandle===void 0?r.parentHandle:e.parentHandle,n={...r,handle:o,parentHandle:d,topology:e.topology,state:e.state,observedAt:e.observedAt,terminalAt:s,freshness:e.freshness,observationSource:e.observationSource,reasonCode:e.reasonCode,revision:r.revision+1};if(!Z(n))throw new c("sqlite-public-safety-rejected","Native-agent observation rejected unsafe or inconsistent fields.");if(r.handle&&e.handle&&r.handle!==e.handle)throw new c("sqlite-mutation-failed","Native-agent observation handle conflicts with the reserved dispatch.");if(!He(r.state,e.state))throw new c("sqlite-mutation-failed","Native-agent observation attempted a terminal or non-monotonic regression.");if(r.state===n.state&&r.handle===n.handle&&r.parentHandle===n.parentHandle&&r.topology===n.topology&&r.observedAt===n.observedAt&&r.terminalAt===n.terminalAt&&r.freshness===n.freshness&&r.observationSource===n.observationSource&&r.reasonCode===n.reasonCode)return Object.freeze({receipt:r,applied:!1,replay:!0});if(e.expectedRevision!==r.revision)throw new c("sqlite-mutation-failed","Native-agent observation CAS revision conflict.");if(r.observedAt&&Date.parse(e.observedAt)<Date.parse(r.observedAt))throw new c("sqlite-mutation-failed","Native-agent observation timestamp regressed.");if(this.db.prepare(`
13
13
  UPDATE native_agent_dispatches
14
14
  SET parent_handle = ?, handle = ?, topology = ?, state = ?, observed_at = ?,
15
15
  terminal_at = ?, freshness = ?, observation_source = ?, reason_code = ?, revision = revision + 1
@@ -19,7 +19,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
19
19
  dispatch_key, sequence, state, handle, parent_handle, topology,
20
20
  observed_at, terminal_at, freshness, observation_source, reason_code
21
21
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
22
- `).run(n.dispatchKey,n.revision,n.state,n.handle,n.parentHandle,n.topology,n.observedAt,n.terminalAt,n.freshness,n.observationSource,n.reasonCode),Object.freeze({receipt:n,applied:!0,replay:!1})})}catch(t){throw p(t,"sqlite-mutation-failed")}}getNativeAgentDispatchStatus(e,t={}){const r=this.db.prepare("SELECT * FROM native_agent_dispatches WHERE dispatch_key = ?").get(e);if(!r)return null;const s=j(r),o=Math.max(1e3,t.staleAfterMs??3e4),d=Date.parse(t.nowIso??this.now()),n=s.observedAt?Date.parse(s.observedAt):NaN;return!ne.has(s.state)&&Number.isFinite(d)&&(!Number.isFinite(n)||d-n>o)?Object.freeze({...s,state:"unknown",freshness:s.observedAt?"stale":"unknown",reasonCode:s.observedAt?"native-agent-observation-stale":"native-agent-awaiting-host-evidence"}):s}listRecentNativeAgentDispatches(e=20){const t=Math.max(1,Math.min(50,Math.floor(e))),r=this.db.prepare(`
22
+ `).run(n.dispatchKey,n.revision,n.state,n.handle,n.parentHandle,n.topology,n.observedAt,n.terminalAt,n.freshness,n.observationSource,n.reasonCode),Object.freeze({receipt:n,applied:!0,replay:!1})})}catch(t){throw p(t,"sqlite-mutation-failed")}}getNativeAgentDispatchStatus(e,t={}){const r=this.db.prepare("SELECT * FROM native_agent_dispatches WHERE dispatch_key = ?").get(e);if(!r)return null;const s=j(r),o=Math.max(1e3,t.staleAfterMs??3e4),d=Date.parse(t.nowIso??this.now()),n=s.observedAt?Date.parse(s.observedAt):NaN;return!de.has(s.state)&&Number.isFinite(d)&&(!Number.isFinite(n)||d-n>o)?Object.freeze({...s,state:"unknown",freshness:s.observedAt?"stale":"unknown",reasonCode:s.observedAt?"native-agent-observation-stale":"native-agent-awaiting-host-evidence"}):s}listRecentNativeAgentDispatches(e=20){const t=Math.max(1,Math.min(50,Math.floor(e))),r=this.db.prepare(`
23
23
  SELECT * FROM native_agent_dispatches
24
24
  ORDER BY COALESCE(observed_at, requested_at) DESC, dispatch_key DESC
25
25
  LIMIT ?
@@ -60,7 +60,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
60
60
  event_id, job_id, operation_id, idempotency_key, event_sequence,
61
61
  type, summary, reason_code, created_at, metadata_json
62
62
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
63
- `).run(e.eventId,e.jobId,e.operationId,e.idempotencyKey??null,e.sequence??null,e.type,e.summary,e.reasonCode??null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}recordProcessingOutputSummary(e){K(e.executionId,"processing_output_summary.executionId",160),K(e.jobId,"processing_output_summary.jobId",160),K(e.publicSummary,"processing_output_summary.publicSummary",Qe),K(e.createdAt,"processing_output_summary.createdAt",80),I(e.eventId,"processing_output_summary.eventId"),I(e.idempotencyKey,"processing_output_summary.idempotencyKey"),I(e.goalId,"processing_output_summary.goalId"),I(e.loopId,"processing_output_summary.loopId"),I(e.reasonCode,"processing_output_summary.reasonCode"),I(e.source,"processing_output_summary.source");const t=this.appendEvent({eventId:mt(e),jobId:e.jobId,operationId:e.executionId,idempotencyKey:e.idempotencyKey??e.executionId,type:O,summary:e.publicSummary,reasonCode:e.reasonCode,createdAt:e.createdAt,metadata:_t(e)});return t.inserted&&this.recordJobStageProgress({jobId:e.jobId,currentStage:e.metadata?.currentStage,iteration:e.metadata?.iteration,at:e.createdAt}),t}enqueueHeadlessExecutionAttempt(e){if(this.assertCanMutate(),R({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,directiveHash:e.directiveHash,targetRef:e.targetRef,storyId:e.storyId,epicId:e.epicId,runtimeId:e.runtimeId,modelId:e.modelId,runtimeSource:e.runtimeSource,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.enqueuedAt}),l(e.notBeforeAt,"headless_execution.notBeforeAt",80),l(e.operationId,"headless_execution.operationId",160),l(e.idempotencyKey,"headless_execution.idempotencyKey",160),T(e.retryCount,"headless_execution.retryCount"),T(e.maxAttempts,"headless_execution.maxAttempts"),e.maxAttempts!==void 0&&e.maxAttempts<1)throw new c("sqlite-public-safety-rejected","Continuity SQLite maxAttempts must be greater than zero.");e.metadata&&A(e.metadata,"headless_execution.metadata");const t=Y({maxItems:e.queueCap,maxAttempts:e.maxAttempts}),r=Be(e.queuePriority),s=$e(e.queueScope),o=q(e.relativePaths),d=Q({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,directiveHash:e.directiveHash,runtimeId:e.runtimeId,modelId:e.modelId,runtimeSource:e.runtimeSource,status:e.status??"queued",reasonCode:e.reasonCode,retryCount:e.retryCount??0,attemptCount:0,maxAttempts:t.maxAttempts,queuePriority:r,queueScope:s,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:o,metadata:e.metadata});return this.runInTransaction(()=>{const n=this.db.prepare(`
63
+ `).run(e.eventId,e.jobId,e.operationId,e.idempotencyKey??null,e.sequence??null,e.type,e.summary,e.reasonCode??null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}recordProcessingOutputSummary(e){K(e.executionId,"processing_output_summary.executionId",160),K(e.jobId,"processing_output_summary.jobId",160),K(e.publicSummary,"processing_output_summary.publicSummary",Ge),K(e.createdAt,"processing_output_summary.createdAt",80),I(e.eventId,"processing_output_summary.eventId"),I(e.idempotencyKey,"processing_output_summary.idempotencyKey"),I(e.goalId,"processing_output_summary.goalId"),I(e.loopId,"processing_output_summary.loopId"),I(e.reasonCode,"processing_output_summary.reasonCode"),I(e.source,"processing_output_summary.source");const t=this.appendEvent({eventId:ht(e),jobId:e.jobId,operationId:e.executionId,idempotencyKey:e.idempotencyKey??e.executionId,type:O,summary:e.publicSummary,reasonCode:e.reasonCode,createdAt:e.createdAt,metadata:pt(e)});return t.inserted&&this.recordJobStageProgress({jobId:e.jobId,currentStage:e.metadata?.currentStage,iteration:e.metadata?.iteration,at:e.createdAt}),t}enqueueHeadlessExecutionAttempt(e){if(this.assertCanMutate(),R({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,directiveHash:e.directiveHash,targetRef:e.targetRef,storyId:e.storyId,epicId:e.epicId,runtimeId:e.runtimeId,modelId:e.modelId,runtimeSource:e.runtimeSource,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.enqueuedAt}),l(e.notBeforeAt,"headless_execution.notBeforeAt",80),l(e.operationId,"headless_execution.operationId",160),l(e.idempotencyKey,"headless_execution.idempotencyKey",160),T(e.retryCount,"headless_execution.retryCount"),T(e.maxAttempts,"headless_execution.maxAttempts"),e.maxAttempts!==void 0&&e.maxAttempts<1)throw new c("sqlite-public-safety-rejected","Continuity SQLite maxAttempts must be greater than zero.");e.metadata&&A(e.metadata,"headless_execution.metadata");const t=Y({maxItems:e.queueCap,maxAttempts:e.maxAttempts}),r=Ye(e.queuePriority),s=Ke(e.queueScope),o=q(e.relativePaths),d=Q({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,directiveHash:e.directiveHash,runtimeId:e.runtimeId,modelId:e.modelId,runtimeSource:e.runtimeSource,status:e.status??"queued",reasonCode:e.reasonCode,retryCount:e.retryCount??0,attemptCount:0,maxAttempts:t.maxAttempts,queuePriority:r,queueScope:s,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:o,metadata:e.metadata});return this.runInTransaction(()=>{const n=this.db.prepare(`
64
64
  SELECT value_json
65
65
  FROM runner_config
66
66
  WHERE key = 'headless_queue_policy'
@@ -121,7 +121,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
121
121
  WHERE directive_hash = ?
122
122
  AND status = 'completed'${r}
123
123
  LIMIT 1
124
- `).get(...s)?.found===1}getAppliedHeadlessExecutionReceipt(e,t){for(const[s,o]of Object.entries(e))l(o,`headless_resume.${s}`,s==="targetRef"?240:160,!0);const r=this.db.prepare(`
124
+ `).get(...s)?.found===1}getAppliedHeadlessExecutionReceipt(e,t,r){for(const[o,d]of Object.entries(e))l(d,`headless_resume.${o}`,o==="targetRef"?240:160,!0);const s=this.db.prepare(`
125
125
  SELECT r.receipt_id AS receiptId, r.created_at AS createdAt,
126
126
  r.reason_code AS reasonCode, a.runner_id AS ownerRunnerId,
127
127
  a.lease_id AS leaseId
@@ -142,14 +142,21 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
142
142
  AND json_extract(r.metadata_json, '$.attemptId') = a.attempt_id
143
143
  AND json_extract(r.metadata_json, '$.hashes.directive') = a.directive_hash
144
144
  AND (? IS NULL OR json_extract(r.metadata_json, '$.hashes.phaseTwoBinding') = ?)
145
+ AND (? IS NULL OR json_extract(r.metadata_json, '$.hashes.phaseTwoCheckpointFingerprint') = ?)
145
146
  LIMIT 1
146
- `).get(e.attemptId,e.executionId,e.jobId,e.storyId,e.targetRef,t??null,t??null);return r&&typeof r.receiptId=="string"&&typeof r.createdAt=="string"&&typeof r.reasonCode=="string"&&typeof r.ownerRunnerId=="string"&&typeof r.leaseId=="string"?{receiptId:r.receiptId,createdAt:r.createdAt,reasonCode:r.reasonCode,ownerRunnerId:r.ownerRunnerId,leaseId:r.leaseId}:null}findPhaseTwoExecutionCompletion(e,t,r){if(!/^[a-f0-9]{64}$/.test(e))return"conflict";const s=this.db.prepare(`
147
+ `).get(e.attemptId,e.executionId,e.jobId,e.storyId,e.targetRef,t??null,t??null,r??null,r??null);return s&&typeof s.receiptId=="string"&&typeof s.createdAt=="string"&&typeof s.reasonCode=="string"&&typeof s.ownerRunnerId=="string"&&typeof s.leaseId=="string"?{receiptId:s.receiptId,createdAt:s.createdAt,reasonCode:s.reasonCode,ownerRunnerId:s.ownerRunnerId,leaseId:s.leaseId}:null}findPhaseTwoExecutionCompletion(e,t,r){if(!/^[a-f0-9]{64}$/.test(e))return"conflict";const s=this.db.prepare(`
147
148
  SELECT attempt_id AS attemptId, execution_id AS executionId, job_id AS jobId
148
149
  FROM headless_execution_attempts
149
150
  WHERE directive_kind = 'run_yolo' AND target_kind = 'story' AND status = 'completed'
150
151
  AND story_id = ? AND target_ref = ? AND json_extract(hashes_json, '$.phaseTwoBinding') = ?
151
- LIMIT 2
152
- `).all(t,r,e);return s.length===0?"missing":s.length!==1?"conflict":this.getAppliedHeadlessExecutionReceipt({...s[0],storyId:t,targetRef:r},e)?"completed":"conflict"}claimHeadlessExecutionAttempt(e){this.assertCanMutate(),R({attemptId:e.attemptId,executionId:e.attemptId,jobId:e.attemptId,leaseId:e.leaseId,runnerId:e.runnerId,reasonCode:e.reasonCode,timestamp:e.claimedAt}),l(e.leaseExpiresAt,"headless_execution.leaseExpiresAt",80,!0);try{const t=this.db.prepare(`
152
+ `).all(t,r,e);return s.length===0?"missing":s.every(o=>this.getAppliedHeadlessExecutionReceipt({...o,storyId:t,targetRef:r},e))?"completed":"conflict"}findPhaseTwoWorkerCompletion(e,t,r,s){if(!/^[a-f0-9]{64}$/.test(e)||!/^[a-f0-9]{64}$/.test(s))return"conflict";const o=this.db.prepare(`
153
+ SELECT attempt_id AS attemptId, execution_id AS executionId, job_id AS jobId
154
+ FROM headless_execution_attempts
155
+ WHERE directive_kind = 'run_yolo' AND target_kind = 'story' AND status = 'completed'
156
+ AND story_id = ? AND target_ref = ?
157
+ AND json_extract(hashes_json, '$.phaseTwoBinding') = ?
158
+ AND json_extract(hashes_json, '$.phaseTwoCheckpointFingerprint') = ?
159
+ `).all(t,r,e,s);return o.length===0?"missing":o.every(d=>this.getAppliedHeadlessExecutionReceipt({...d,storyId:t,targetRef:r},e,s))?"completed":"conflict"}claimHeadlessExecutionAttempt(e){this.assertCanMutate(),R({attemptId:e.attemptId,executionId:e.attemptId,jobId:e.attemptId,leaseId:e.leaseId,runnerId:e.runnerId,reasonCode:e.reasonCode,timestamp:e.claimedAt}),l(e.leaseExpiresAt,"headless_execution.leaseExpiresAt",80,!0);try{const t=this.db.prepare(`
153
160
  UPDATE headless_execution_attempts
154
161
  SET status = 'running',
155
162
  lease_id = ?,
@@ -264,19 +271,19 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
264
271
  WHERE operation_id = ? OR idempotency_key = ?
265
272
  ORDER BY created_at DESC, receipt_id ASC
266
273
  LIMIT 2
267
- `).all(n,u),h=_.filter(i=>{let y,C;try{y=i.applied_operation_ids_json?JSON.parse(i.applied_operation_ids_json):void 0,C=U(i.metadata_json)}catch{return!1}return i.job_id===o.job_id&&i.operation_id===n&&i.idempotency_key===u&&i.status==="applied"&&i.reason_code===o.reason_code&&i.created_at===o.completed_at&&Array.isArray(y)&&y.length===1&&y[0]===o.execution_id&&C.attemptId===o.attempt_id&&C.executionId===o.execution_id&&C.jobId===o.job_id&&C.directiveHash===o.directive_hash&&C.status==="completed"&&C.reasonCode===o.reason_code});if(_.length>0)return h.length===1&&_.length===1?{verified:!0,repaired:!1,attempt:o,reasonCode:"headless-resume-receipt-verified",publicSafe:!0}:{verified:!1,repaired:!1,reasonCode:"headless-resume-receipt-unverified",publicSafe:!0};const b=`receipt-headless-resume-${k("sha256").update(`${o.attempt_id}:${o.execution_id}:${o.directive_hash}`).digest("hex").slice(0,32)}`;return this.recordHeadlessExecutionReceipt({receiptId:b,attemptId:o.attempt_id,executionId:o.execution_id,jobId:o.job_id,status:"applied",reasonCode:o.reason_code,createdAt:o.completed_at,operationId:n,idempotencyKey:u,counts:U(o.counts_json),hashes:U(o.hashes_json),redactionSummary:be(o.redaction_summary_json),relativePaths:ft(o.relative_paths_json),metadata:d}).inserted?{verified:!0,repaired:!0,attempt:o,reasonCode:"headless-resume-receipt-reconciled",publicSafe:!0}:{verified:!1,repaired:!1,reasonCode:"headless-resume-receipt-unverified",publicSafe:!0}};return this.runInTransaction(t)}recordHeadlessExecutionSummary(e){R({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,runtimeId:e.runtimeId,modelId:e.modelId,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.createdAt}),T(e.durationMs,"headless_execution.durationMs"),e.metadata&&A(e.metadata,"headless_execution.metadata");const t=q(e.relativePaths),r=Q({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,runtimeId:e.runtimeId,modelId:e.modelId,status:e.status??"completed",reasonCode:e.reasonCode,durationMs:e.durationMs,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:t,metadata:e.metadata});return this.recordProcessingOutputSummary({eventId:e.eventId,executionId:e.executionId,jobId:e.jobId,idempotencyKey:e.executionId,publicSummary:e.publicSummary,reasonCode:e.reasonCode,createdAt:e.createdAt,source:"headless_execution",metadata:r})}appendReceipt(e){this.assertCanMutate();const t=S(e.metadata);try{const r=this.db.prepare(`
274
+ `).all(n,u),h=_.filter(i=>{let y,C;try{y=i.applied_operation_ids_json?JSON.parse(i.applied_operation_ids_json):void 0,C=U(i.metadata_json)}catch{return!1}return i.job_id===o.job_id&&i.operation_id===n&&i.idempotency_key===u&&i.status==="applied"&&i.reason_code===o.reason_code&&i.created_at===o.completed_at&&Array.isArray(y)&&y.length===1&&y[0]===o.execution_id&&C.attemptId===o.attempt_id&&C.executionId===o.execution_id&&C.jobId===o.job_id&&C.directiveHash===o.directive_hash&&C.status==="completed"&&C.reasonCode===o.reason_code});if(_.length>0)return h.length===1&&_.length===1?{verified:!0,repaired:!1,attempt:o,reasonCode:"headless-resume-receipt-verified",publicSafe:!0}:{verified:!1,repaired:!1,reasonCode:"headless-resume-receipt-unverified",publicSafe:!0};const b=`receipt-headless-resume-${M("sha256").update(`${o.attempt_id}:${o.execution_id}:${o.directive_hash}`).digest("hex").slice(0,32)}`;return this.recordHeadlessExecutionReceipt({receiptId:b,attemptId:o.attempt_id,executionId:o.execution_id,jobId:o.job_id,status:"applied",reasonCode:o.reason_code,createdAt:o.completed_at,operationId:n,idempotencyKey:u,counts:U(o.counts_json),hashes:U(o.hashes_json),redactionSummary:Ce(o.redaction_summary_json),relativePaths:bt(o.relative_paths_json),metadata:d}).inserted?{verified:!0,repaired:!0,attempt:o,reasonCode:"headless-resume-receipt-reconciled",publicSafe:!0}:{verified:!1,repaired:!1,reasonCode:"headless-resume-receipt-unverified",publicSafe:!0}};return this.runInTransaction(t)}recordHeadlessExecutionSummary(e){R({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,runtimeId:e.runtimeId,modelId:e.modelId,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.createdAt}),T(e.durationMs,"headless_execution.durationMs"),e.metadata&&A(e.metadata,"headless_execution.metadata");const t=q(e.relativePaths),r=Q({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,runtimeId:e.runtimeId,modelId:e.modelId,status:e.status??"completed",reasonCode:e.reasonCode,durationMs:e.durationMs,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:t,metadata:e.metadata});return this.recordProcessingOutputSummary({eventId:e.eventId,executionId:e.executionId,jobId:e.jobId,idempotencyKey:e.executionId,publicSummary:e.publicSummary,reasonCode:e.reasonCode,createdAt:e.createdAt,source:"headless_execution",metadata:r})}appendReceipt(e){this.assertCanMutate();const t=S(e.metadata);try{const r=this.db.prepare(`
268
275
  INSERT OR IGNORE INTO job_receipts (
269
276
  receipt_id, job_id, operation_id, idempotency_key, status, reason_code,
270
277
  applied_operation_ids_json, ignored_operation_ids_json, created_at, metadata_json
271
278
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
272
- `).run(e.receiptId,e.jobId,e.operationId??null,e.idempotencyKey??null,e.status,e.reasonCode??null,e.appliedOperationIds?JSON.stringify(e.appliedOperationIds):null,e.ignoredOperationIds?JSON.stringify(e.ignoredOperationIds):null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}compactPublicReceiptsAndOutputs(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new c("sqlite-public-safety-rejected","Continuity receipt compaction requires a valid public timestamp.");const r=Ye(e.policy),s=new Date(t-r.receipts.maxAgeMs).toISOString(),o=new Date(t-r.processingOutputs.maxAgeMs).toISOString();try{return this.runInTransaction(()=>{const d=this.selectReceiptRetentionCandidates({cutoff:s,maxItems:r.receipts.maxItems,maxBytes:r.receipts.maxBytes,limit:r.maxDeleteRowsPerRun}),n=this.selectOutputRetentionCandidates({cutoff:o,maxItems:r.processingOutputs.maxItems,maxBytes:r.processingOutputs.maxBytes,limit:r.maxDeleteRowsPerRun}),u=[...d,...n].sort((i,y)=>i.createdAt.localeCompare(y.createdAt)||i.id.localeCompare(y.id)).slice(0,r.maxDeleteRowsPerRun);if(u.length===0)return{status:"noop",summaries:[],counts:{receiptsRemoved:0,outputsRemoved:0,bytesRemoved:0,summariesCreated:0},reasonCode:$.NOOP,publicSafe:!0};const _=u.filter(i=>i.kind==="receipt"),h=u.filter(i=>i.kind==="output");for(const i of P(_.map(y=>y.jobId)))this.preserveReceiptDerivedIteration(i,e.nowIso);this.deleteRetentionCandidates("job_receipts","receipt_id",_.map(i=>i.id)),this.deleteRetentionCandidates("job_events","event_id",h.map(i=>i.id));const b=new Map;for(const i of u)b.set(i.jobId,[...b.get(i.jobId)??[],i]);const m=[];for(const[i,y]of[...b.entries()].sort(([C],[x])=>C.localeCompare(x))){const C=y.filter(D=>D.kind==="receipt"),x=y.filter(D=>D.kind==="output"),J=this.retainedReceiptOutputCounts(i),G=yt(i,C,x),N={receiptsRemoved:C.length,receiptsRetained:J.receipts,outputsRemoved:x.length,outputsRetained:J.outputs,bytesRemoved:y.reduce((D,Ae)=>D+Ae.approxBytes,0),bytesRetained:J.bytes,redactions:0},W=`Compacted public receipt and processing evidence: receipts removed ${N.receiptsRemoved}, retained ${N.receiptsRetained}; summaries removed ${N.outputsRemoved}, retained ${N.outputsRetained}; bytes removed ${N.bytesRemoved}, retained ${N.bytesRetained}.`;l(W,"receipt_compaction.publicSummary",500,!0);const F=`receipt-compaction-${k("sha256").update(`${i}:${e.nowIso}:${G.aggregate}`).digest("hex").slice(0,32)}`,te={schemaVersion:1,contractVersion:"continuity-v1",policyVersion:1,type:B,summaryId:F,jobId:i,scope:"local_sqlite",status:"compacted",createdAt:e.nowIso,reasonCodes:[$.COMPACTED],counts:N,hashes:G,publicSummary:W,publicSafe:!0};this.appendEvent({eventId:F,jobId:i,operationId:`op-${F}`,idempotencyKey:`idem-${F}`,type:B,summary:W,reasonCode:$.COMPACTED,createdAt:e.nowIso,metadata:{schemaVersion:1,contractVersion:"continuity-v1",eventType:B,jobId:i,reasonCodes:te.reasonCodes,counts:N,hashes:G,publicSummary:W}}),this.pruneReceiptCompactionSummaries(i,r.maxCompactionSummariesPerJob),m.push(te)}return{status:"compacted",summaries:m,counts:{receiptsRemoved:_.length,outputsRemoved:h.length,bytesRemoved:u.reduce((i,y)=>i+y.approxBytes,0),summariesCreated:m.length},reasonCode:$.COMPACTED,publicSafe:!0}})}catch(d){throw p(d,"sqlite-mutation-failed")}}updateJobStatus(e){this.assertCanMutate();try{const t=this.db.prepare(`
279
+ `).run(e.receiptId,e.jobId,e.operationId??null,e.idempotencyKey??null,e.status,e.reasonCode??null,e.appliedOperationIds?JSON.stringify(e.appliedOperationIds):null,e.ignoredOperationIds?JSON.stringify(e.ignoredOperationIds):null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}compactPublicReceiptsAndOutputs(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new c("sqlite-public-safety-rejected","Continuity receipt compaction requires a valid public timestamp.");const r=Ve(e.policy),s=new Date(t-r.receipts.maxAgeMs).toISOString(),o=new Date(t-r.processingOutputs.maxAgeMs).toISOString();try{return this.runInTransaction(()=>{const d=this.selectReceiptRetentionCandidates({cutoff:s,maxItems:r.receipts.maxItems,maxBytes:r.receipts.maxBytes,limit:r.maxDeleteRowsPerRun}),n=this.selectOutputRetentionCandidates({cutoff:o,maxItems:r.processingOutputs.maxItems,maxBytes:r.processingOutputs.maxBytes,limit:r.maxDeleteRowsPerRun}),u=[...d,...n].sort((i,y)=>i.createdAt.localeCompare(y.createdAt)||i.id.localeCompare(y.id)).slice(0,r.maxDeleteRowsPerRun);if(u.length===0)return{status:"noop",summaries:[],counts:{receiptsRemoved:0,outputsRemoved:0,bytesRemoved:0,summariesCreated:0},reasonCode:$.NOOP,publicSafe:!0};const _=u.filter(i=>i.kind==="receipt"),h=u.filter(i=>i.kind==="output");for(const i of P(_.map(y=>y.jobId)))this.preserveReceiptDerivedIteration(i,e.nowIso);this.deleteRetentionCandidates("job_receipts","receipt_id",_.map(i=>i.id)),this.deleteRetentionCandidates("job_events","event_id",h.map(i=>i.id));const b=new Map;for(const i of u)b.set(i.jobId,[...b.get(i.jobId)??[],i]);const m=[];for(const[i,y]of[...b.entries()].sort(([C],[x])=>C.localeCompare(x))){const C=y.filter(k=>k.kind==="receipt"),x=y.filter(k=>k.kind==="output"),J=this.retainedReceiptOutputCounts(i),G=It(i,C,x),N={receiptsRemoved:C.length,receiptsRetained:J.receipts,outputsRemoved:x.length,outputsRetained:J.outputs,bytesRemoved:y.reduce((k,Re)=>k+Re.approxBytes,0),bytesRetained:J.bytes,redactions:0},W=`Compacted public receipt and processing evidence: receipts removed ${N.receiptsRemoved}, retained ${N.receiptsRetained}; summaries removed ${N.outputsRemoved}, retained ${N.outputsRetained}; bytes removed ${N.bytesRemoved}, retained ${N.bytesRetained}.`;l(W,"receipt_compaction.publicSummary",500,!0);const F=`receipt-compaction-${M("sha256").update(`${i}:${e.nowIso}:${G.aggregate}`).digest("hex").slice(0,32)}`,ae={schemaVersion:1,contractVersion:"continuity-v1",policyVersion:1,type:B,summaryId:F,jobId:i,scope:"local_sqlite",status:"compacted",createdAt:e.nowIso,reasonCodes:[$.COMPACTED],counts:N,hashes:G,publicSummary:W,publicSafe:!0};this.appendEvent({eventId:F,jobId:i,operationId:`op-${F}`,idempotencyKey:`idem-${F}`,type:B,summary:W,reasonCode:$.COMPACTED,createdAt:e.nowIso,metadata:{schemaVersion:1,contractVersion:"continuity-v1",eventType:B,jobId:i,reasonCodes:ae.reasonCodes,counts:N,hashes:G,publicSummary:W}}),this.pruneReceiptCompactionSummaries(i,r.maxCompactionSummariesPerJob),m.push(ae)}return{status:"compacted",summaries:m,counts:{receiptsRemoved:_.length,outputsRemoved:h.length,bytesRemoved:u.reduce((i,y)=>i+y.approxBytes,0),summariesCreated:m.length},reasonCode:$.COMPACTED,publicSafe:!0}})}catch(d){throw p(d,"sqlite-mutation-failed")}}updateJobStatus(e){this.assertCanMutate();try{const t=this.db.prepare(`
273
280
  UPDATE jobs
274
281
  SET status = ?,
275
282
  reason_code = COALESCE(?, reason_code),
276
283
  updated_at = ?,
277
284
  next_run_at = COALESCE(?, next_run_at)
278
285
  WHERE job_id = ?
279
- `).run(e.status,e.reasonCode??null,e.updatedAt,e.nextRunAt??null,e.jobId);if(t.changes===0)throw new c("sqlite-foreign-key-failed",`Continuity SQLite job ${e.jobId} was not found for status update.`);return this.toWriteResult(t)}catch(t){throw p(t,"sqlite-mutation-failed")}}recordJobStageProgress(e){this.assertCanMutate(),l(e.jobId,"job_stage.jobId",160,!0);const t=ue(e.currentStage)?e.currentStage:void 0,r=et(e.iteration);if(!t&&r===void 0)return{inserted:!1,replay:!1,changes:0};const s=_e(e.at);try{const o=this.db.prepare("SELECT metadata_json FROM jobs WHERE job_id = ?").get(e.jobId);if(!o)return{inserted:!1,replay:!1,changes:0};const d=U(typeof o.metadata_json=="string"?o.metadata_json:null);if(t&&(d.currentStage=t),r!==void 0&&(d.iteration=r),t&&s&&e.appendHistory!==!1){const u=Ze(d.stageHistory);u.push({stage:t,at:s}),d.stageHistory=u.slice(-le)}const n=this.db.prepare("UPDATE jobs SET metadata_json = ? WHERE job_id = ?").run(S(d),e.jobId);return this.toWriteResult(n)}catch(o){throw p(o,"sqlite-mutation-failed")}}updateJobAndExistingGoalCampaignStatus(e){return this.runInTransaction(()=>{const t=this.db.prepare(`
286
+ `).run(e.status,e.reasonCode??null,e.updatedAt,e.nextRunAt??null,e.jobId);if(t.changes===0)throw new c("sqlite-foreign-key-failed",`Continuity SQLite job ${e.jobId} was not found for status update.`);return this.toWriteResult(t)}catch(t){throw p(t,"sqlite-mutation-failed")}}recordJobStageProgress(e){this.assertCanMutate(),l(e.jobId,"job_stage.jobId",160,!0);const t=ue(e.currentStage)?e.currentStage:void 0,r=at(e.iteration);if(!t&&r===void 0)return{inserted:!1,replay:!1,changes:0};const s=_e(e.at);try{const o=this.db.prepare("SELECT metadata_json FROM jobs WHERE job_id = ?").get(e.jobId);if(!o)return{inserted:!1,replay:!1,changes:0};const d=U(typeof o.metadata_json=="string"?o.metadata_json:null);if(t&&(d.currentStage=t),r!==void 0&&(d.iteration=r),t&&s&&e.appendHistory!==!1){const u=tt(d.stageHistory);u.push({stage:t,at:s}),d.stageHistory=u.slice(-le)}const n=this.db.prepare("UPDATE jobs SET metadata_json = ? WHERE job_id = ?").run(S(d),e.jobId);return this.toWriteResult(n)}catch(o){throw p(o,"sqlite-mutation-failed")}}updateJobAndExistingGoalCampaignStatus(e){return this.runInTransaction(()=>{const t=this.db.prepare(`
280
287
  UPDATE jobs
281
288
  SET status = ?,
282
289
  reason_code = COALESCE(?, reason_code),
@@ -308,7 +315,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
308
315
  artifact_id, job_id, kind, relative_path, sha256, summary,
309
316
  operation_id, idempotency_key, created_at, metadata_json
310
317
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
311
- `).run(e.artifactId,e.jobId??null,e.kind,e.relativePath,e.sha256??null,e.summary??null,e.operationId??null,e.idempotencyKey??null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}enqueueOutbox(e){this.assertCanMutate(),M({outboxId:e.outboxId,jobId:e.jobId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,type:e.type,status:e.status,deliveryCursor:e.deliveryCursor,timestamp:e.createdAt,reasonCode:e.lastErrorReason??e.lastErrorCode,summary:e.lastErrorSummary??e.deadLetterSummary}),M({outboxId:e.outboxId,timestamp:e.updatedAt}),l(e.nextAttemptAt,"outbox.nextAttemptAt",80),l(e.lastAttemptAt,"outbox.lastAttemptAt",80),l(e.sentAt,"outbox.sentAt",80),l(e.ackedAt,"outbox.ackedAt",80),l(e.deadLetteredAt,"outbox.deadLetteredAt",80),T(e.retryCount,"outbox.retryCount"),T(e.attemptCount,"outbox.attemptCount");const t=S(e.payload);try{const r=this.db.prepare(`
318
+ `).run(e.artifactId,e.jobId??null,e.kind,e.relativePath,e.sha256??null,e.summary??null,e.operationId??null,e.idempotencyKey??null,e.createdAt,t);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}enqueueOutbox(e){this.assertCanMutate(),D({outboxId:e.outboxId,jobId:e.jobId,operationId:e.operationId,idempotencyKey:e.idempotencyKey,type:e.type,status:e.status,deliveryCursor:e.deliveryCursor,timestamp:e.createdAt,reasonCode:e.lastErrorReason??e.lastErrorCode,summary:e.lastErrorSummary??e.deadLetterSummary}),D({outboxId:e.outboxId,timestamp:e.updatedAt}),l(e.nextAttemptAt,"outbox.nextAttemptAt",80),l(e.lastAttemptAt,"outbox.lastAttemptAt",80),l(e.sentAt,"outbox.sentAt",80),l(e.ackedAt,"outbox.ackedAt",80),l(e.deadLetteredAt,"outbox.deadLetteredAt",80),T(e.retryCount,"outbox.retryCount"),T(e.attemptCount,"outbox.attemptCount");const t=S(e.payload);try{const r=this.db.prepare(`
312
319
  INSERT OR IGNORE INTO outbox (
313
320
  outbox_id, job_id, operation_id, idempotency_key, type, status,
314
321
  payload_json, retry_count, attempt_count, delivery_cursor,
@@ -316,7 +323,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
316
323
  last_error_reason, last_error_summary, dead_letter_summary,
317
324
  dead_lettered_at, created_at, updated_at
318
325
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
319
- `).run(e.outboxId,e.jobId??null,e.operationId,e.idempotencyKey??null,e.type,e.status??"pending",t??"{}",e.retryCount??0,e.attemptCount??0,e.deliveryCursor??null,e.nextAttemptAt??null,e.lastAttemptAt??null,e.sentAt??null,e.ackedAt??null,e.lastErrorCode??null,e.lastErrorReason??e.lastErrorCode??null,e.lastErrorSummary??null,e.deadLetterSummary??null,e.deadLetteredAt??null,e.createdAt,e.updatedAt);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}selectOutboxBatch(e){M({outboxId:"outbox-query",timestamp:e.nowIso});const t=Math.max(1,Math.min(100,Math.floor(e.limit))),r=P(e.statuses?.length?e.statuses:["pending","failed"]);for(const d of r)if(!Ee(d))throw new c("sqlite-public-safety-rejected","Continuity SQLite outbox batch query rejected an unknown status.");const s=r.map(()=>"?").join(", ");return this.db.prepare(`
326
+ `).run(e.outboxId,e.jobId??null,e.operationId,e.idempotencyKey??null,e.type,e.status??"pending",t??"{}",e.retryCount??0,e.attemptCount??0,e.deliveryCursor??null,e.nextAttemptAt??null,e.lastAttemptAt??null,e.sentAt??null,e.ackedAt??null,e.lastErrorCode??null,e.lastErrorReason??e.lastErrorCode??null,e.lastErrorSummary??null,e.deadLetterSummary??null,e.deadLetteredAt??null,e.createdAt,e.updatedAt);return this.toWriteResult(r)}catch(r){throw p(r,"sqlite-mutation-failed")}}selectOutboxBatch(e){D({outboxId:"outbox-query",timestamp:e.nowIso});const t=Math.max(1,Math.min(100,Math.floor(e.limit))),r=P(e.statuses?.length?e.statuses:["pending","failed"]);for(const d of r)if(!ge(d))throw new c("sqlite-public-safety-rejected","Continuity SQLite outbox batch query rejected an unknown status.");const s=r.map(()=>"?").join(", ");return this.db.prepare(`
320
327
  SELECT outbox_id, job_id, operation_id, idempotency_key, type, status,
321
328
  payload_json, retry_count, attempt_count, delivery_cursor,
322
329
  next_attempt_at, last_attempt_at, sent_at, acked_at, last_error_code,
@@ -327,7 +334,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
327
334
  AND (status NOT IN ('pending', 'failed') OR next_attempt_at IS NULL OR next_attempt_at <= ?)
328
335
  ORDER BY COALESCE(next_attempt_at, created_at) ASC, created_at ASC, outbox_id ASC
329
336
  LIMIT ?
330
- `).all(...r,e.nowIso,t).map(Et)}markOutboxSent(e){this.assertCanMutate(),M({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.sentAt,reasonCode:e.reasonCode});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if((t.status==="sent"||t.status==="acked")&&t.delivery_cursor===e.deliveryCursor)return g({outboxId:e.outboxId,status:t.status,changes:0,replay:!0,deliveryCursor:e.deliveryCursor,reasonCode:e.reasonCode??"outbox-delivery-replay"});if(t.status==="sent"||t.status==="acked"||t.status==="dead_letter")return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-delivery-conflict"});const r=this.db.prepare(`
337
+ `).all(...r,e.nowIso,t).map(gt)}markOutboxSent(e){this.assertCanMutate(),D({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.sentAt,reasonCode:e.reasonCode});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if((t.status==="sent"||t.status==="acked")&&t.delivery_cursor===e.deliveryCursor)return g({outboxId:e.outboxId,status:t.status,changes:0,replay:!0,deliveryCursor:e.deliveryCursor,reasonCode:e.reasonCode??"outbox-delivery-replay"});if(t.status==="sent"||t.status==="acked"||t.status==="dead_letter")return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-delivery-conflict"});const r=this.db.prepare(`
331
338
  UPDATE outbox
332
339
  SET status = 'sent',
333
340
  delivery_cursor = ?,
@@ -338,7 +345,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
338
345
  updated_at = ?
339
346
  WHERE outbox_id = ?
340
347
  AND status IN ('pending', 'failed')
341
- `).run(e.deliveryCursor,e.sentAt,e.sentAt,e.sentAt,e.outboxId);return g({outboxId:e.outboxId,status:"sent",changes:r.changes,replay:!1,deliveryCursor:e.deliveryCursor,reasonCode:e.reasonCode??"outbox-sent"})})}catch(t){throw p(t,"sqlite-mutation-failed")}}ackOutbox(e){this.assertCanMutate(),M({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.ackedAt,reasonCode:e.reasonCode});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="acked"&&(!e.deliveryCursor||t.delivery_cursor===e.deliveryCursor))return g({outboxId:e.outboxId,status:"acked",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,reasonCode:e.reasonCode??"outbox-ack-replay"});if(t.status!=="sent"||e.deliveryCursor&&t.delivery_cursor!==e.deliveryCursor)return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-ack-conflict"});const r=this.db.prepare(`
348
+ `).run(e.deliveryCursor,e.sentAt,e.sentAt,e.sentAt,e.outboxId);return g({outboxId:e.outboxId,status:"sent",changes:r.changes,replay:!1,deliveryCursor:e.deliveryCursor,reasonCode:e.reasonCode??"outbox-sent"})})}catch(t){throw p(t,"sqlite-mutation-failed")}}ackOutbox(e){this.assertCanMutate(),D({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.ackedAt,reasonCode:e.reasonCode});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="acked"&&(!e.deliveryCursor||t.delivery_cursor===e.deliveryCursor))return g({outboxId:e.outboxId,status:"acked",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,reasonCode:e.reasonCode??"outbox-ack-replay"});if(t.status!=="sent"||e.deliveryCursor&&t.delivery_cursor!==e.deliveryCursor)return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-ack-conflict"});const r=this.db.prepare(`
342
349
  UPDATE outbox
343
350
  SET status = 'acked',
344
351
  acked_at = ?,
@@ -348,7 +355,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
348
355
  last_error_reason = NULL
349
356
  WHERE outbox_id = ?
350
357
  AND status = 'sent'
351
- `).run(e.ackedAt,e.ackedAt,e.outboxId);return g({outboxId:e.outboxId,status:"acked",changes:r.changes,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:e.reasonCode??"outbox-acked"})})}catch(t){throw p(t,"sqlite-mutation-failed")}}failOutboxDelivery(e){this.assertCanMutate(),M({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.failedAt,reasonCode:e.reasonCode,summary:e.summary}),l(e.nextRetryAt,"outbox.nextRetryAt",80);try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="acked")return g({outboxId:e.outboxId,status:"acked",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-already-acked"});if(t.status==="dead_letter")return g({outboxId:e.outboxId,status:"dead_letter",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,deadLetteredAt:t.dead_lettered_at??void 0,reasonCode:t.last_error_reason??t.last_error_code??e.reasonCode});if(e.deliveryCursor&&t.delivery_cursor&&t.delivery_cursor!==e.deliveryCursor)return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor,reasonCode:"outbox-fail-conflict"});const r=Math.max(1,t.attempt_count??0,t.retry_count??0),s=Fe({nowIso:e.failedAt,attemptCount:r,reasonCode:e.reasonCode,summary:e.summary,nextRetryAt:e.nextRetryAt,policy:e.policy}),o=this.db.prepare(`
358
+ `).run(e.ackedAt,e.ackedAt,e.outboxId);return g({outboxId:e.outboxId,status:"acked",changes:r.changes,replay:!1,deliveryCursor:t.delivery_cursor??void 0,reasonCode:e.reasonCode??"outbox-acked"})})}catch(t){throw p(t,"sqlite-mutation-failed")}}failOutboxDelivery(e){this.assertCanMutate(),D({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.failedAt,reasonCode:e.reasonCode,summary:e.summary}),l(e.nextRetryAt,"outbox.nextRetryAt",80);try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="acked")return g({outboxId:e.outboxId,status:"acked",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,reasonCode:"outbox-already-acked"});if(t.status==="dead_letter")return g({outboxId:e.outboxId,status:"dead_letter",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,deadLetteredAt:t.dead_lettered_at??void 0,reasonCode:t.last_error_reason??t.last_error_code??e.reasonCode});if(e.deliveryCursor&&t.delivery_cursor&&t.delivery_cursor!==e.deliveryCursor)return g({outboxId:e.outboxId,status:"conflict",changes:0,replay:!1,deliveryCursor:t.delivery_cursor,reasonCode:"outbox-fail-conflict"});const r=Math.max(1,t.attempt_count??0,t.retry_count??0),s=$e({nowIso:e.failedAt,attemptCount:r,reasonCode:e.reasonCode,summary:e.summary,nextRetryAt:e.nextRetryAt,policy:e.policy}),o=this.db.prepare(`
352
359
  UPDATE outbox
353
360
  SET status = ?,
354
361
  retry_count = MAX(retry_count, ?),
@@ -361,7 +368,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
361
368
  updated_at = ?
362
369
  WHERE outbox_id = ?
363
370
  AND status IN ('pending', 'sent', 'failed')
364
- `).run(s.status,r,s.status==="failed"?s.nextRetryAt??e.failedAt:null,e.reasonCode,e.reasonCode,e.summary??null,s.status==="dead_letter"?e.summary??e.reasonCode:null,s.deadLetteredAt??null,e.failedAt,e.outboxId);return g({outboxId:e.outboxId,status:s.status,changes:o.changes,replay:!1,deliveryCursor:t.delivery_cursor??e.deliveryCursor,reasonCode:s.reasonCode,...s.nextRetryAt?{nextRetryAt:s.nextRetryAt}:{},...s.deadLetteredAt?{deadLetteredAt:s.deadLetteredAt}:{}})})}catch(t){throw p(t,"sqlite-mutation-failed")}}deadLetterOutbox(e){this.assertCanMutate(),M({outboxId:e.outboxId,timestamp:e.deadLetteredAt,reasonCode:e.reasonCode,summary:e.summary});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="dead_letter")return g({outboxId:e.outboxId,status:"dead_letter",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,deadLetteredAt:t.dead_lettered_at??void 0,reasonCode:t.last_error_reason??t.last_error_code??e.reasonCode});const r=this.db.prepare(`
371
+ `).run(s.status,r,s.status==="failed"?s.nextRetryAt??e.failedAt:null,e.reasonCode,e.reasonCode,e.summary??null,s.status==="dead_letter"?e.summary??e.reasonCode:null,s.deadLetteredAt??null,e.failedAt,e.outboxId);return g({outboxId:e.outboxId,status:s.status,changes:o.changes,replay:!1,deliveryCursor:t.delivery_cursor??e.deliveryCursor,reasonCode:s.reasonCode,...s.nextRetryAt?{nextRetryAt:s.nextRetryAt}:{},...s.deadLetteredAt?{deadLetteredAt:s.deadLetteredAt}:{}})})}catch(t){throw p(t,"sqlite-mutation-failed")}}deadLetterOutbox(e){this.assertCanMutate(),D({outboxId:e.outboxId,timestamp:e.deadLetteredAt,reasonCode:e.reasonCode,summary:e.summary});try{return this.runInTransaction(()=>{const t=this.getOutboxTransitionRow(e.outboxId);if(!t)return g({outboxId:e.outboxId,status:"missing",changes:0,replay:!1,reasonCode:"outbox-missing"});if(t.status==="dead_letter")return g({outboxId:e.outboxId,status:"dead_letter",changes:0,replay:!0,deliveryCursor:t.delivery_cursor??void 0,deadLetteredAt:t.dead_lettered_at??void 0,reasonCode:t.last_error_reason??t.last_error_code??e.reasonCode});const r=this.db.prepare(`
365
372
  UPDATE outbox
366
373
  SET status = 'dead_letter',
367
374
  next_attempt_at = NULL,
@@ -535,7 +542,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
535
542
  FROM runner_config
536
543
  WHERE key = 'headless_queue_policy'
537
544
  LIMIT 1
538
- `).get();let d=Pe;if(E(o)&&typeof o.value_json=="string")try{const y=JSON.parse(o.value_json);E(y)&&typeof y.maxItems=="number"&&(d=Y({maxItems:y.maxItems}))}catch{}const n=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'queued' AND dead_lettered_at IS NULL"),u=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'backoff' AND dead_lettered_at IS NULL"),_=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running' AND dead_lettered_at IS NULL"),h=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE dead_lettered_at IS NOT NULL"),b=n+u+_,m=this.db.prepare(`
545
+ `).get();let d=Fe;if(E(o)&&typeof o.value_json=="string")try{const y=JSON.parse(o.value_json);E(y)&&typeof y.maxItems=="number"&&(d=Y({maxItems:y.maxItems}))}catch{}const n=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'queued' AND dead_lettered_at IS NULL"),u=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'backoff' AND dead_lettered_at IS NULL"),_=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running' AND dead_lettered_at IS NULL"),h=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE dead_lettered_at IS NOT NULL"),b=n+u+_,m=this.db.prepare(`
539
546
  SELECT MIN(next_retry_at) AS next_retry_at
540
547
  FROM headless_execution_attempts
541
548
  WHERE status = 'backoff'
@@ -625,19 +632,19 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
625
632
  FROM headless_execution_attempts
626
633
  ORDER BY enqueued_at DESC, attempt_id ASC
627
634
  LIMIT ?
628
- `).all(e.jobLimit),counts:{jobs:t("SELECT COUNT(*) AS count FROM jobs"),activeJobs:t("SELECT COUNT(*) AS count FROM jobs WHERE status IN ('planned', 'active', 'running', 'waiting_external', 'waiting_human', 'backoff', 'paused', 'blocked')"),activeLeases:t("SELECT COUNT(*) AS count FROM job_leases WHERE released_at IS NULL"),dueJobs:t("SELECT COUNT(*) AS count FROM jobs WHERE next_run_at IS NOT NULL AND next_run_at <= ? AND status NOT IN ('completed', 'aborted', 'cancelled')",e.nowIso),staleLeases:t("SELECT COUNT(*) AS count FROM job_leases WHERE released_at IS NULL AND expires_at <= ?",e.nowIso),receipts:t("SELECT COUNT(*) AS count FROM job_receipts"),events:t("SELECT COUNT(*) AS count FROM job_events"),processingOutputSummaries:t("SELECT COUNT(*) AS count FROM job_events WHERE type = ?",O),goalLedgerItems:t("SELECT COUNT(*) AS count FROM goal_ledger_items"),goalVerifiers:t("SELECT COUNT(*) AS count FROM goal_verifiers"),goalReviewGates:t("SELECT COUNT(*) AS count FROM goal_review_gates"),stateSnapshots:t("SELECT COUNT(*) AS count FROM state_snapshots"),headlessExecutionAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts"),headlessQueuedAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status IN ('queued', 'backoff')"),headlessRunningAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running'"),headlessRetryingAttempts:u,headlessDeadLetterAttempts:h,staleHeadlessExecutionAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running' AND lease_released_at IS NULL AND lease_expires_at <= ?",e.nowIso),outbox:t("SELECT COUNT(*) AS count FROM outbox")},outboxCounts:s,queue:{depth:b,queued:n,running:_,retrying:u,deadLetter:h,capacity:d.maxItems,available:Math.max(0,d.maxItems-b),backpressure:b>=d.maxItems,generatedAt:e.nowIso,...i?{nextRetryAt:i}:{},...b>=d.maxItems?{reasonCode:v.CAP_REACHED}:{},publicSafe:!0}}}listProcessingOutputSummaries(e={}){const t=he(e.limit),r=fe(e),s=`
635
+ `).all(e.jobLimit),counts:{jobs:t("SELECT COUNT(*) AS count FROM jobs"),activeJobs:t("SELECT COUNT(*) AS count FROM jobs WHERE status IN ('planned', 'active', 'running', 'waiting_external', 'waiting_human', 'backoff', 'paused', 'blocked')"),activeLeases:t("SELECT COUNT(*) AS count FROM job_leases WHERE released_at IS NULL"),dueJobs:t("SELECT COUNT(*) AS count FROM jobs WHERE next_run_at IS NOT NULL AND next_run_at <= ? AND status NOT IN ('completed', 'aborted', 'cancelled')",e.nowIso),staleLeases:t("SELECT COUNT(*) AS count FROM job_leases WHERE released_at IS NULL AND expires_at <= ?",e.nowIso),receipts:t("SELECT COUNT(*) AS count FROM job_receipts"),events:t("SELECT COUNT(*) AS count FROM job_events"),processingOutputSummaries:t("SELECT COUNT(*) AS count FROM job_events WHERE type = ?",O),goalLedgerItems:t("SELECT COUNT(*) AS count FROM goal_ledger_items"),goalVerifiers:t("SELECT COUNT(*) AS count FROM goal_verifiers"),goalReviewGates:t("SELECT COUNT(*) AS count FROM goal_review_gates"),stateSnapshots:t("SELECT COUNT(*) AS count FROM state_snapshots"),headlessExecutionAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts"),headlessQueuedAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status IN ('queued', 'backoff')"),headlessRunningAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running'"),headlessRetryingAttempts:u,headlessDeadLetterAttempts:h,staleHeadlessExecutionAttempts:t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'running' AND lease_released_at IS NULL AND lease_expires_at <= ?",e.nowIso),outbox:t("SELECT COUNT(*) AS count FROM outbox")},outboxCounts:s,queue:{depth:b,queued:n,running:_,retrying:u,deadLetter:h,capacity:d.maxItems,available:Math.max(0,d.maxItems-b),backpressure:b>=d.maxItems,generatedAt:e.nowIso,...i?{nextRetryAt:i}:{},...b>=d.maxItems?{reasonCode:v.CAP_REACHED}:{},publicSafe:!0}}}listProcessingOutputSummaries(e={}){const t=fe(e.limit),r=be(e),s=`
629
636
  SELECT event_id, job_id, operation_id, summary, reason_code, created_at, metadata_json
630
637
  FROM job_events
631
638
  WHERE type = ?${r.sql}
632
639
  ORDER BY created_at DESC, event_id DESC
633
640
  LIMIT ?
634
- `;return this.db.prepare(`SELECT * FROM (${s}) ORDER BY created_at ASC, event_id ASC`).all(O,...r.params,t).map(Ie)}pollProcessingOutputSummaries(e={}){const t=he(e.limit),r=ht(e.cursor),s=fe(e),o=r?" AND (created_at > ? OR (created_at = ? AND event_id > ?))":"",d=`
641
+ `;return this.db.prepare(`SELECT * FROM (${s}) ORDER BY created_at ASC, event_id ASC`).all(O,...r.params,t).map(Ee)}pollProcessingOutputSummaries(e={}){const t=fe(e.limit),r=ft(e.cursor),s=be(e),o=r?" AND (created_at > ? OR (created_at = ? AND event_id > ?))":"",d=`
635
642
  SELECT event_id, job_id, operation_id, summary, reason_code, created_at, metadata_json
636
643
  FROM job_events
637
644
  WHERE type = ?${s.sql}${o}
638
645
  ORDER BY created_at ASC, event_id ASC
639
646
  LIMIT ?
640
- `,n=[O];n.push(...s.params),r&&n.push(r.createdAt,r.createdAt,r.eventId),n.push(t+1);const u=this.db.prepare(d).all(...n),_=u.slice(0,t).map(Ie),h=_[_.length-1];return{summaries:_,...h?{nextCursor:h.cursor}:e.cursor?{nextCursor:e.cursor}:{},hasMore:u.length>t,publicSafe:!0}}listDueJobs(e){const t=Math.max(1,Math.min(50,Math.floor(e.limit)));return this.db.prepare(`
647
+ `,n=[O];n.push(...s.params),r&&n.push(r.createdAt,r.createdAt,r.eventId),n.push(t+1);const u=this.db.prepare(d).all(...n),_=u.slice(0,t).map(Ee),h=_[_.length-1];return{summaries:_,...h?{nextCursor:h.cursor}:e.cursor?{nextCursor:e.cursor}:{},hasMore:u.length>t,publicSafe:!0}}listDueJobs(e){const t=Math.max(1,Math.min(50,Math.floor(e.limit)));return this.db.prepare(`
641
648
  SELECT j.job_id, j.kind, j.status, j.summary, j.reason_code, j.created_at,
642
649
  j.updated_at, j.next_run_at, j.metadata_json,
643
650
  (SELECT COUNT(*)
@@ -675,7 +682,7 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
675
682
  AND lease_expires_at <= ?
676
683
  ORDER BY lease_expires_at ASC, attempt_id ASC
677
684
  LIMIT ?
678
- `).all(o,s),n=[],u=[],_=Y(e.policy);for(const m of d){if(typeof m.attempt_id!="string"||m.attempt_id.length===0)continue;const i=typeof m.retry_count=="number"?m.retry_count:0,y=typeof m.max_attempts=="number"?m.max_attempts:1,C=typeof m.attempt_count=="number"?m.attempt_count:0;Math.max(C,i+1)>=y?u.push(m.attempt_id):n.push({attemptId:m.attempt_id,nextRetryAt:We(e.nowIso,i+1,_)})}let h=0;for(const m of n)h+=this.db.prepare(`
685
+ `).all(o,s),n=[],u=[],_=Y(e.policy);for(const m of d){if(typeof m.attempt_id!="string"||m.attempt_id.length===0)continue;const i=typeof m.retry_count=="number"?m.retry_count:0,y=typeof m.max_attempts=="number"?m.max_attempts:1,C=typeof m.attempt_count=="number"?m.attempt_count:0;Math.max(C,i+1)>=y?u.push(m.attempt_id):n.push({attemptId:m.attempt_id,nextRetryAt:Be(e.nowIso,i+1,_)})}let h=0;for(const m of n)h+=this.db.prepare(`
679
686
  UPDATE headless_execution_attempts
680
687
  SET status = 'backoff',
681
688
  retry_count = retry_count + 1,
@@ -710,4 +717,4 @@ import{Buffer as z}from"node:buffer";import{createHash as k}from"node:crypto";im
710
717
  checksum TEXT NOT NULL,
711
718
  applied_at TEXT NOT NULL
712
719
  );
713
- `)}applyMigrations(){this.db.transaction(()=>{for(const t of tt){const r=ct(t.sql),s=this.db.prepare("SELECT version, name, checksum FROM continuity_migrations WHERE version = ?").get(t.version);if(s){if(s.checksum!==r||s.name!==t.name)throw new c("sqlite-migration-conflict",`Continuity SQLite migration ${t.version} checksum conflict.`);continue}this.db.exec(t.sql),this.db.prepare("INSERT INTO continuity_migrations (version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(t.version,t.name,r,this.now()),this.db.pragma(`user_version = ${t.version}`)}})()}assertCanMutate(){if(this.mutationBlocked)throw new c("sqlite-mutation-blocked","Continuity SQLite mutation is blocked after integrity failure.",{mutationBlocked:!0})}toWriteResult(e){const t=e.changes>0;return{inserted:t,replay:!t,changes:e.changes}}}export{O as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_EVENT_TYPE,Qe as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_MAX_CHARS,Ge as CONTINUITY_PUBLIC_STAGES,Ke as CONTINUITY_SQLITE_FILENAME,de as CONTINUITY_SQLITE_RELATIVE_DIR,Ft as CONTINUITY_SQLITE_SCHEMA_VERSION,le as CONTINUITY_STAGE_HISTORY_MAX,Rt as ContinuitySqliteStore,c as ContinuitySqliteStoreError,ie as DEFAULT_CONTINUITY_PROCESSING_SUMMARY_LIMIT,Ve as DEFAULT_CONTINUITY_SQLITE_BUSY_TIMEOUT_MS,Je as MAX_CONTINUITY_PROCESSING_SUMMARY_LIMIT,ce as SQLITE_ADAPTER_INSTALL_GUIDANCE,Ce as continuitySqliteStorePath,$t as inspectEpicOperationalSqliteBinding,ue as isContinuityPublicStage,St as loadBetterSqlite3Adapter,et as normalizeContinuityStageIteration,xt as openContinuitySqliteReadOnly,Bt as openContinuitySqliteStore,Ze as sanitizeContinuityStageHistory,_e as sanitizeContinuityStageTimestamp};
720
+ `)}applyMigrations(){this.db.transaction(()=>{for(const t of rt){const r=ut(t.sql),s=this.db.prepare("SELECT version, name, checksum FROM continuity_migrations WHERE version = ?").get(t.version);if(s){if(s.checksum!==r||s.name!==t.name)throw new c("sqlite-migration-conflict",`Continuity SQLite migration ${t.version} checksum conflict.`);continue}this.db.exec(t.sql),this.db.prepare("INSERT INTO continuity_migrations (version, name, checksum, applied_at) VALUES (?, ?, ?, ?)").run(t.version,t.name,r,this.now()),this.db.pragma(`user_version = ${t.version}`)}})()}assertCanMutate(){if(this.mutationBlocked)throw new c("sqlite-mutation-blocked","Continuity SQLite mutation is blocked after integrity failure.",{mutationBlocked:!0})}toWriteResult(e){const t=e.changes>0;return{inserted:t,replay:!t,changes:e.changes}}}export{O as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_EVENT_TYPE,Ge as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_MAX_CHARS,Xe as CONTINUITY_PUBLIC_STAGES,Qe as CONTINUITY_SQLITE_FILENAME,ie as CONTINUITY_SQLITE_RELATIVE_DIR,$t as CONTINUITY_SQLITE_SCHEMA_VERSION,le as CONTINUITY_STAGE_HISTORY_MAX,Ot as ContinuitySqliteStore,c as ContinuitySqliteStoreError,ce as DEFAULT_CONTINUITY_PROCESSING_SUMMARY_LIMIT,Je as DEFAULT_CONTINUITY_SQLITE_BUSY_TIMEOUT_MS,ze as MAX_CONTINUITY_PROCESSING_SUMMARY_LIMIT,ee as SQLITE_ADAPTER_INSTALL_GUIDANCE,Se as continuitySqliteStorePath,Kt as inspectEpicOperationalSqliteBinding,ue as isContinuityPublicStage,xt as loadBetterSqlite3Adapter,at as normalizeContinuityStageIteration,Nt as openContinuitySqliteReadOnly,Yt as openContinuitySqliteStore,tt as sanitizeContinuityStageHistory,_e as sanitizeContinuityStageTimestamp};
@@ -93,6 +93,12 @@ export interface DirectYoloCheckpointOptions {
93
93
  readonly storyId: string;
94
94
  readonly headSha: string;
95
95
  }) => Promise<unknown>;
96
+ /**
97
+ * Process-local observer for the opaque P205 authority minted by this exact
98
+ * execution. Recovery callers may forward it into the same invoke snapshot.
99
+ * It is never persisted, serialized or accepted as an input authority.
100
+ */
101
+ readonly captureTransientAuthority?: (authority: P205TransientExecutionAuthority) => void;
96
102
  /** Test seam executed after push and before the final locked checkpoint CAS. */
97
103
  readonly beforeCheckpointPersist?: () => Promise<void>;
98
104
  /** Test seam for crash-window reproduction after durable CAS and before release. */
@@ -150,6 +156,10 @@ export declare function verifyDirectYoloIntegrationCommit(authority: DirectYoloC
150
156
  export declare function recoverLegacyDirectYoloStoryCheckpoint(options: DirectYoloCheckpointOptions & {
151
157
  readonly commitSha: string;
152
158
  }): Promise<DirectYoloCheckpointResult<StoryCommitCheckpoint>>;
159
+ /** @internal Historical authority is admitted only by published reconciliation. */
160
+ export declare function recoverReconciledDirectYoloStoryCheckpoint(options: DirectYoloCheckpointOptions & {
161
+ readonly commitSha: string;
162
+ }, expectedGraphRevision: string): Promise<DirectYoloCheckpointResult<StoryCommitCheckpoint>>;
153
163
  type LogicalAuthority = Awaited<ReturnType<typeof resolveLogicalAuthority>>;
154
164
  /**
155
165
  * P225.07 root integration authority: the same logical authority as direct