@ornexus/neocortex 4.66.21 → 4.66.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1194 -1194
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/continuity/sqlite-store.d.ts +23 -0
- package/packages/client/dist/continuity/sqlite-store.js +96 -68
- package/packages/client/dist/git/published-story-reconciliation.js +5 -5
- package/packages/client/dist/runner/headless/run-yolo.js +1 -1
- package/packages/client/dist/runner/headless/run-yoloop.js +4 -4
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/neocortex.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex-sentinel.md +1 -1
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/codex/neocortex.toml +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/deepseek-harness/SKILL.md +1 -1
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/gemini-cli/agents/neocortex.md +2 -2
- package/targets-stubs/grok/SKILL.md +1 -1
- package/targets-stubs/kimi/neocortex.md +1 -1
- package/targets-stubs/openclaw/SKILL.md +1 -1
- package/targets-stubs/opencode/neocortex-root.md +2 -2
- package/targets-stubs/opencode/neocortex.md +2 -2
- package/targets-stubs/vscode/neocortex.agent.md +2 -2
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";import{chmodSync as z,closeSync as Se,existsSync as te,mkdirSync as ae,openSync as Ae,readSync as xe}from"node:fs";import{dirname as re,join as se}from"node:path";import{INITIAL_CONTINUITY_SQLITE_MIGRATION as Re}from"./migrations/001-initial-schema.js";import{PROCESSING_OUTPUT_SUMMARY_SQLITE_MIGRATION as Oe}from"./migrations/002-processing-output-summary-indexes.js";import{HEADLESS_EXECUTION_ATTEMPTS_SQLITE_MIGRATION as Ne}from"./migrations/003-headless-execution-attempts.js";import{OUTBOX_DELIVERY_STATE_SQLITE_MIGRATION as Te}from"./migrations/004-outbox-delivery-state.js";import{BOUNDED_HEADLESS_QUEUE_SQLITE_MIGRATION as Le}from"./migrations/005-bounded-headless-queue.js";import{NATIVE_AGENT_DISPATCHES_SQLITE_MIGRATION as ve}from"./migrations/006-native-agent-dispatches.js";import{NATIVE_LAUNCH_RETRY_SQLITE_MIGRATION as je}from"./migrations/007-native-launch-retry.js";import{isNativeLaunchRefusal as Me,nativeLaunchRetryKey as ke}from"../../../shared/dist/yoloop/native-launch-retry.js";import{NATIVE_AGENT_TERMINAL_STATES as oe,isNativeAgentDispatchReceiptV1 as X,isNativeAgentStateTransitionAllowed as De,isNativeDispatchBindingV1 as we,isNativeHostAttestationV1 as Ue}from"./native-agent-types.js";import{CONTINUITY_QUEUE_REASON_CODES as v,CONTINUITY_RECEIPT_COMPACTION_EVENT_TYPE as F,CONTINUITY_RECEIPT_RETENTION_REASON_CODES as B,DEFAULT_CONTINUITY_QUEUE_POLICY as qe,computeContinuityQueueRetryAt as Pe,computeContinuityOutboxFailureDecision as He,normalizeContinuityQueuePolicy as $,normalizeContinuityQueuePriority as We,normalizeContinuityQueueScope as Fe,normalizeContinuityRetentionPolicy as Be}from"./outbox.js";const ne=".neocortex/continuity",$e="continuity.sqlite",Ht=7,Ye=5e3,O="processing_output_summary",Ke=2e3,de=20,Ve=100,ie="Install the optional Enterprise continuity SQLite adapter with `npm install --workspace packages/client better-sqlite3 --include=optional` or reinstall Neocortex with optional dependencies enabled.",Qe=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"]),ce=20,Ge=new Set(Qe),Je=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;function le(a){return typeof a=="string"&&Ge.has(a)}function ue(a){if(typeof a!="string")return;const e=a.trim();if(!(e.length===0||e.length>40)&&Je.test(e))return e}function ze(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(!b(t)||!le(t.stage))continue;const r=ue(t.at);r&&e.push({stage:t.stage,at:r})}return e.slice(-ce)}function Xe(a){if(!(typeof a!="number"||!Number.isFinite(a)||a<0))return Math.floor(a)}class i 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(!X(e))throw new i("sqlite-integrity-failed","Native-agent receipt failed its closed public contract.",{mutationBlocked:!0});return e}const Ze=[Re,Oe,Ne,Te,Le,ve,je],et=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"]),_e=/(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,me=/(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,tt=new Set(["unsafe_key","raw_log","prompt_body","private_url","local_absolute_path","secret","protected_field","unbounded_text","unbounded_number","unknown_required_operation","missing"]),at=/(corrupt|malformed|not a database|file is not a database|database disk image is malformed)/i,rt=/(foreign key constraint failed|SQLITE_CONSTRAINT_FOREIGNKEY)/i,Z="p185:v1:",st=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"]),ot=new Set(["foreground_invoke","scheduled_tick","runner_tick","manual_tick","headless_execution","jobs_command","invoke_watch","portal_render"]);function nt(a){return import(a)}function dt(a){return`sha256:${D("sha256").update(a).digest("hex")}`}function b(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function it(a){return a instanceof Error?a.message:String(a)}function ct(a){return b(a)&&typeof a.code=="string"?a.code:void 0}function m(a,e){if(a instanceof i)return a;const t=it(a),r=ct(a);return r==="SQLITE_CORRUPT"||r==="SQLITE_NOTADB"||at.test(t)?new i("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"||rt.test(t)?new i("sqlite-foreign-key-failed","Continuity SQLite foreign-key validation failed; mutation was rejected.",{cause:a}):new i(e,t,{cause:a})}function S(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)&&tt.has(a))return;if(me.test(a))throw new i("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)=>S(t,`${e}[${r}]`));return}if(b(a)){for(const[t,r]of Object.entries(a)){const s=t==="terminationToken"&&e.endsWith(".releaseBlocked")&&r==="[YOLOOP_RELEASE_BLOCKED]";if(_e.test(t)&&!s)throw new i("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe key at ${e}.${t}.`);S(r,`${e}.${t}`)}return}throw new i("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsupported value at ${e}.`)}}function E(a,e){if(a!==void 0&&me.test(a))throw new i("sqlite-public-safety-rejected",`Continuity SQLite text rejected unsafe value at ${e}.`)}function Y(a,e,t=240){if(a.trim().length===0)throw new i("sqlite-public-safety-rejected",`Continuity SQLite processing summary text is required at ${e}.`);if(E(a,e),a.length>t)throw new i("sqlite-public-safety-rejected",`Continuity SQLite processing summary text exceeded the public bound at ${e}.`)}function K(a){const e={};if(!a)return e;for(const[t,r]of Object.entries(a))if(st.has(t)&&!_e.test(t))try{S(r,`metadata.${t}`),e[t]=r}catch{}return e}function lt(a){const e={...K(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&&ot.has(a.source)&&(e.processingOutputSource=a.source),K(e)}function he(a){const e=Math.floor(a??de);return Number.isFinite(e)?Math.max(1,Math.min(Ve,e)):de}function ut(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-${D("sha256").update(a.executionId).digest("hex").slice(0,32)}`}function _t(a){return`${Z}${J.from(JSON.stringify([a.created_at,a.event_id]),"utf8").toString("base64url")}`}function mt(a){if(a?.startsWith(Z))try{const e=a.slice(Z.length),t=JSON.parse(J.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 pe(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 be(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:_t(e)}}function g(a){return a?(S(a,"metadata"),JSON.stringify(a)):null}function ht(a,e,t){const r=n=>`sha256:${D("sha256").update(n.map(o=>[o.id,o.status,o.reasonCode].join(":")).sort().join(`
|
|
2
|
-
`)).digest("hex")}`,s=r(e),d=r(t);return{receipts:s,outputs:d,aggregate:`sha256:${D("sha256").update(`${a}:${s}:${d}`).digest("hex")}`}}function yt(a){if(!a)return{};try{const e=JSON.parse(a);return b(e)?{...e}:{}}catch{return{}}}function c(a,e,t,r=!1){if(a===void 0){if(r)throw new i("sqlite-public-safety-rejected",`Continuity SQLite text is required at ${e}.`);return}if(E(a,e),a.trim().length===0||a.length>t)throw new i("sqlite-public-safety-rejected",`Continuity SQLite text exceeded the public bound at ${e}.`)}function N(a,e){if(a!==void 0&&(!Number.isFinite(a)||a<0||Math.floor(a)!==a))throw new i("sqlite-public-safety-rejected",`Continuity SQLite numeric value rejected at ${e}.`)}function M(a){c(a.outboxId,"outbox.outboxId",160,!0),c(a.jobId,"outbox.jobId",160),c(a.operationId,"outbox.operationId",160),c(a.idempotencyKey,"outbox.idempotencyKey",160),c(a.type,"outbox.type",80),c(a.status,"outbox.status",40),c(a.deliveryCursor,"outbox.deliveryCursor",200),c(a.timestamp,"outbox.timestamp",80),c(a.reasonCode,"outbox.reasonCode",100),c(a.summary,"outbox.summary",240)}function Ee(a){return a==="pending"||a==="sent"||a==="acked"||a==="failed"||a==="dead_letter"}function pt(a){return typeof a=="string"&&Ee(a)?a:"failed"}function y(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 b(e)?(S(e,"outbox.payload"),e):{}}catch{return{}}}function Et(a){return{outboxId:String(a.outbox_id??""),...y(a.job_id)?{jobId:y(a.job_id)}:{},operationId:String(a.operation_id??""),...y(a.idempotency_key)?{idempotencyKey:y(a.idempotency_key)}:{},type:String(a.type??""),status:pt(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,...y(a.delivery_cursor)?{deliveryCursor:y(a.delivery_cursor)}:{},...y(a.next_attempt_at)?{nextAttemptAt:y(a.next_attempt_at)}:{},...y(a.last_attempt_at)?{lastAttemptAt:y(a.last_attempt_at)}:{},...y(a.sent_at)?{sentAt:y(a.sent_at)}:{},...y(a.acked_at)?{ackedAt:y(a.acked_at)}:{},...y(a.last_error_code)?{lastErrorCode:y(a.last_error_code)}:{},...y(a.last_error_reason)?{lastErrorReason:y(a.last_error_reason)}:{},...y(a.last_error_summary)?{lastErrorSummary:y(a.last_error_summary)}:{},...y(a.dead_letter_summary)?{deadLetterSummary:y(a.dead_letter_summary)}:{},...y(a.dead_lettered_at)?{deadLetteredAt:y(a.dead_lettered_at)}:{},createdAt:String(a.created_at??""),updatedAt:String(a.updated_at??""),publicSafe:!0}}function C(a){return{...a,publicSafe:!0}}function T(a,e){return a===void 0?null:(S(a,e),JSON.stringify(a))}function U(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()){c(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 i("sqlite-public-safety-rejected",`Continuity SQLite rejected non-relative path at relativePaths[${t}].`)}return e}function V(a){const e={...K(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=U(a.relativePaths)),K(e)}function L(a){c(a.attemptId,"headless_execution.attemptId",160,!0),c(a.executionId,"headless_execution.executionId",160,!0),c(a.jobId,"headless_execution.jobId",160,!0),c(a.directiveHash,"headless_execution.directiveHash",160),c(a.targetRef,"headless_execution.targetRef",240),c(a.storyId,"headless_execution.storyId",120),c(a.epicId,"headless_execution.epicId",120),c(a.runtimeId,"headless_execution.runtimeId",80),c(a.modelId,"headless_execution.modelId",120),c(a.runtimeSource,"headless_execution.runtimeSource",40),c(a.reasonCode,"headless_execution.reasonCode",100),c(a.publicSummary,"headless_execution.publicSummary",240),c(a.leaseId,"headless_execution.leaseId",160),c(a.runnerId,"headless_execution.runnerId",160),c(a.timestamp,"headless_execution.timestamp",80)}function q(a){if(Array.isArray(a)){const e=a[0];return b(e)?Object.values(e)[0]:e}return b(a)?Object.values(a)[0]:a}function It(a){return et.includes(a)}function P(a){return Array.from(new Set(a))}function ft(a){const e=b(a)&&"default"in a?a.default:a;if(typeof e!="function")throw new i("sqlite-adapter-unavailable","Optional better-sqlite3 adapter did not export a database constructor.",{guidance:ie});const t=e;return{adapterName:"better-sqlite3",open(r,s){return new t(r,s)}}}async function Ct(a=nt){try{const e=await a("better-sqlite3");return{ok:!0,adapter:ft(e)}}catch(e){return e instanceof i?{ok:!1,error:e}:{ok:!1,error:new i("sqlite-adapter-unavailable","Optional Enterprise continuity SQLite adapter better-sqlite3 is unavailable.",{cause:e,guidance:ie})}}}function Ie(a){return se(a,ne,$e)}function gt(a){const e=se(a,ne);ae(e,{recursive:!0,mode:448});try{z(e,448)}catch{}return e}async function Wt(a){const e=a.adapter??await Ce(a.adapterLoader),t=a.filePath??Ie(a.projectRoot);if(a.strictReadOnly)fe(t);else if(a.filePath){ae(re(t),{recursive:!0,mode:448});try{z(re(t),448)}catch{}}else gt(a.projectRoot);let r;try{r=e.open(t,a.strictReadOnly?{fileMustExist:!0,readonly:!0}:void 0)}catch(d){throw m(d,"sqlite-integrity-failed")}const s=new At({db:r,filePath:t,adapterName:e.adapterName,busyTimeoutMs:a.busyTimeoutMs??Ye,integrityCheck:a.integrityCheck??!0,now:a.now??(()=>new Date().toISOString())});try{if(a.strictReadOnly)return s.runIntegrityCheck(),s.getSchemaVersion(),s;if(s.initialize(),te(t))try{z(t,384)}catch{}return s}catch(d){try{r.close()}catch{}throw d}}function fe(a){if(!te(a))throw new i("sqlite-projection-missing","Continuity database is unavailable for physical read-only inspection.",{mutationBlocked:!0});let e;try{const t=Ae(a,"r");try{if(e=J.alloc(20),xe(t,e,0,e.length,0)<e.length)throw new Error("short-header")}finally{Se(t)}}catch(t){throw new i("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 i("sqlite-integrity-failed","Continuity database header is not a recognized SQLite database.",{mutationBlocked:!0});if(e[18]===2||e[19]===2)throw new i("sqlite-projection-wal-unsafe","Continuity database requires an unsafe WAL read profile.",{mutationBlocked:!0})}async function St(a){const e=Ie(a.projectRoot);fe(e);const t=a.adapter??await Ce(a.adapterLoader);let r,s=!1;try{r=t.open(e,{fileMustExist:!0,readonly:!0}),s=!0;const n=q(r.pragma("integrity_check",{simple:!0}));if(String(n).toLowerCase()!=="ok")throw new Error("integrity")}catch(n){throw new i(s?"sqlite-integrity-failed":"sqlite-projection-adapter-incompatible","Continuity database failed physical read-only inspection.",{cause:n,mutationBlocked:!0})}const d=n=>{const o=n.trim().replace(/^\(+/u,"").toLowerCase();if(!/^(select|with\s)/u.test(o)||/\b(insert|update|delete|replace|create|alter|drop|pragma|attach|detach|vacuum|reindex)\b/u.test(o))throw new i("sqlite-mutation-blocked","Statement is not in the physical read-only query profile.",{mutationBlocked:!0})};return Object.freeze({filePath:e,adapterName:t.adapterName,all(n,...o){return d(n),r.prepare(n).all(...o)},get(n,...o){return d(n),r.prepare(n).get(...o)},close(){r.close()}})}async function Ft(a){if(!Number.isSafeInteger(a.authorityRevision)||a.authorityRevision<0||!/^[a-f0-9]{64}$/.test(a.sourceDigest))throw new i("sqlite-integrity-failed","Epic operational SQLite binding input is invalid.",{mutationBlocked:!0});let e;try{e=await St(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(!b(s)||s.sha256!==a.sourceDigest||typeof s.metadata_json!="string")return!1;try{const d=JSON.parse(s.metadata_json);return b(d)&&d.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 i?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 Ce(a){const e=a?await a():await Ct();if(!e.ok)throw e.error;return e.adapter}class At{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 m(e,"sqlite-migration-failed")}}close(){this.db.close()}pragmaValue(e){return q(this.db.pragma(e,{simple:!0}))}runIntegrityCheck(){try{if(String(q(this.db.pragma("integrity_check",{simple:!0}))??"").toLowerCase()!=="ok")throw this.mutationBlocked=!0,new i("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,m(e,"sqlite-integrity-failed")}}getSchemaVersion(){const e=this.db.prepare("SELECT COALESCE(MAX(version), 0) AS version FROM continuity_migrations").get();return b(e)&&typeof e.version=="number"?e.version:0}countRows(e){if(!It(e))throw new i("sqlite-public-safety-rejected","Unknown continuity table name.");const t=this.db.prepare(`SELECT COUNT(*) AS count FROM ${e}`).get();return b(t)&&typeof t.count=="number"?t.count:0}reserveNativeAgentDispatch(e){if(this.assertCanMutate(),!we(e.binding)||!Ue(e.hostAttestation))throw new i("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(!X(t))throw new i("sqlite-public-safety-rejected","Native-agent reservation rejected unsafe public fields.");try{return this.runInTransaction(()=>{const r=this.db.prepare(`
|
|
1
|
+
import{Buffer as J}from"node:buffer";import{createHash as k}from"node:crypto";import{chmodSync as z,closeSync as Se,existsSync as te,mkdirSync as ae,openSync as Ae,readSync as xe}from"node:fs";import{dirname as re,join as se}from"node:path";import{INITIAL_CONTINUITY_SQLITE_MIGRATION as Re}from"./migrations/001-initial-schema.js";import{PROCESSING_OUTPUT_SUMMARY_SQLITE_MIGRATION as Ne}from"./migrations/002-processing-output-summary-indexes.js";import{HEADLESS_EXECUTION_ATTEMPTS_SQLITE_MIGRATION as Oe}from"./migrations/003-headless-execution-attempts.js";import{OUTBOX_DELIVERY_STATE_SQLITE_MIGRATION as Te}from"./migrations/004-outbox-delivery-state.js";import{BOUNDED_HEADLESS_QUEUE_SQLITE_MIGRATION as Le}from"./migrations/005-bounded-headless-queue.js";import{NATIVE_AGENT_DISPATCHES_SQLITE_MIGRATION as ve}from"./migrations/006-native-agent-dispatches.js";import{NATIVE_LAUNCH_RETRY_SQLITE_MIGRATION as je}from"./migrations/007-native-launch-retry.js";import{isNativeLaunchRefusal as Me,nativeLaunchRetryKey as De}from"../../../shared/dist/yoloop/native-launch-retry.js";import{NATIVE_AGENT_TERMINAL_STATES as oe,isNativeAgentDispatchReceiptV1 as X,isNativeAgentStateTransitionAllowed as ke,isNativeDispatchBindingV1 as we,isNativeHostAttestationV1 as Ue}from"./native-agent-types.js";import{CONTINUITY_QUEUE_REASON_CODES as v,CONTINUITY_RECEIPT_COMPACTION_EVENT_TYPE as F,CONTINUITY_RECEIPT_RETENTION_REASON_CODES as B,DEFAULT_CONTINUITY_QUEUE_POLICY as qe,computeContinuityQueueRetryAt as Pe,computeContinuityOutboxFailureDecision as He,normalizeContinuityQueuePolicy as $,normalizeContinuityQueuePriority as We,normalizeContinuityQueueScope as Fe,normalizeContinuityRetentionPolicy as Be}from"./outbox.js";const ne=".neocortex/continuity",$e="continuity.sqlite",Ht=7,Ye=5e3,N="processing_output_summary",Ke=2e3,de=20,Ve=100,ie="Install the optional Enterprise continuity SQLite adapter with `npm install --workspace packages/client better-sqlite3 --include=optional` or reinstall Neocortex with optional dependencies enabled.",Qe=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"]),ce=20,Ge=new Set(Qe),Je=/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?(?:Z|[+-]\d{2}:?\d{2})?$/;function le(a){return typeof a=="string"&&Ge.has(a)}function ue(a){if(typeof a!="string")return;const e=a.trim();if(!(e.length===0||e.length>40)&&Je.test(e))return e}function ze(a){if(!Array.isArray(a))return[];const e=[];for(const t of a){if(!E(t)||!le(t.stage))continue;const r=ue(t.at);r&&e.push({stage:t.stage,at:r})}return e.slice(-ce)}function Xe(a){if(!(typeof a!="number"||!Number.isFinite(a)||a<0))return Math.floor(a)}class i 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(!X(e))throw new i("sqlite-integrity-failed","Native-agent receipt failed its closed public contract.",{mutationBlocked:!0});return e}const Ze=[Re,Ne,Oe,Te,Le,ve,je],et=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"]),_e=/(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,me=/(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,tt=new Set(["unsafe_key","raw_log","prompt_body","private_url","local_absolute_path","secret","protected_field","unbounded_text","unbounded_number","unknown_required_operation","missing"]),at=/(corrupt|malformed|not a database|file is not a database|database disk image is malformed)/i,rt=/(foreign key constraint failed|SQLITE_CONSTRAINT_FOREIGNKEY)/i,Z="p185:v1:",st=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"]),ot=new Set(["foreground_invoke","scheduled_tick","runner_tick","manual_tick","headless_execution","jobs_command","invoke_watch","portal_render"]);function nt(a){return import(a)}function dt(a){return`sha256:${k("sha256").update(a).digest("hex")}`}function E(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function it(a){return a instanceof Error?a.message:String(a)}function ct(a){return E(a)&&typeof a.code=="string"?a.code:void 0}function y(a,e){if(a instanceof i)return a;const t=it(a),r=ct(a);return r==="SQLITE_CORRUPT"||r==="SQLITE_NOTADB"||at.test(t)?new i("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"||rt.test(t)?new i("sqlite-foreign-key-failed","Continuity SQLite foreign-key validation failed; mutation was rejected.",{cause:a}):new i(e,t,{cause:a})}function S(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)&&tt.has(a))return;if(me.test(a))throw new i("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)=>S(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(_e.test(t)&&!s)throw new i("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsafe key at ${e}.${t}.`);S(r,`${e}.${t}`)}return}throw new i("sqlite-public-safety-rejected",`Continuity SQLite metadata rejected unsupported value at ${e}.`)}}function I(a,e){if(a!==void 0&&me.test(a))throw new i("sqlite-public-safety-rejected",`Continuity SQLite text rejected unsafe value at ${e}.`)}function Y(a,e,t=240){if(a.trim().length===0)throw new i("sqlite-public-safety-rejected",`Continuity SQLite processing summary text is required at ${e}.`);if(I(a,e),a.length>t)throw new i("sqlite-public-safety-rejected",`Continuity SQLite processing summary text exceeded the public bound at ${e}.`)}function K(a){const e={};if(!a)return e;for(const[t,r]of Object.entries(a))if(st.has(t)&&!_e.test(t))try{S(r,`metadata.${t}`),e[t]=r}catch{}return e}function lt(a){const e={...K(a.metadata),schemaVersion:1,contractVersion:"continuity-v1",eventType:N,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&&ot.has(a.source)&&(e.processingOutputSource=a.source),K(e)}function ye(a){const e=Math.floor(a??de);return Number.isFinite(e)?Math.max(1,Math.min(Ve,e)):de}function ut(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 _t(a){return`${Z}${J.from(JSON.stringify([a.created_at,a.event_id]),"utf8").toString("base64url")}`}function mt(a){if(a?.startsWith(Z))try{const e=a.slice(Z.length),t=JSON.parse(J.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 he(a){return a?P(a.map(e=>w("job",e)).filter(e=>!!e)):[]}function pe(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=he(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=he(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 be(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:_t(e)}}function C(a){return a?(S(a,"metadata"),JSON.stringify(a)):null}function yt(a,e,t){const r=d=>`sha256:${k("sha256").update(d.map(o=>[o.id,o.status,o.reasonCode].join(":")).sort().join(`
|
|
2
|
+
`)).digest("hex")}`,s=r(e),n=r(t);return{receipts:s,outputs:n,aggregate:`sha256:${k("sha256").update(`${a}:${s}:${n}`).digest("hex")}`}}function ht(a){if(!a)return{};try{const e=JSON.parse(a);return E(e)?{...e}:{}}catch{return{}}}function c(a,e,t,r=!1){if(a===void 0){if(r)throw new i("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 i("sqlite-public-safety-rejected",`Continuity SQLite text exceeded the public bound at ${e}.`)}function O(a,e){if(a!==void 0&&(!Number.isFinite(a)||a<0||Math.floor(a)!==a))throw new i("sqlite-public-safety-rejected",`Continuity SQLite numeric value rejected at ${e}.`)}function M(a){c(a.outboxId,"outbox.outboxId",160,!0),c(a.jobId,"outbox.jobId",160),c(a.operationId,"outbox.operationId",160),c(a.idempotencyKey,"outbox.idempotencyKey",160),c(a.type,"outbox.type",80),c(a.status,"outbox.status",40),c(a.deliveryCursor,"outbox.deliveryCursor",200),c(a.timestamp,"outbox.timestamp",80),c(a.reasonCode,"outbox.reasonCode",100),c(a.summary,"outbox.summary",240)}function Ie(a){return a==="pending"||a==="sent"||a==="acked"||a==="failed"||a==="dead_letter"}function pt(a){return typeof a=="string"&&Ie(a)?a:"failed"}function p(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)?(S(e,"outbox.payload"),e):{}}catch{return{}}}function It(a){return{outboxId:String(a.outbox_id??""),...p(a.job_id)?{jobId:p(a.job_id)}:{},operationId:String(a.operation_id??""),...p(a.idempotency_key)?{idempotencyKey:p(a.idempotency_key)}:{},type:String(a.type??""),status:pt(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,...p(a.delivery_cursor)?{deliveryCursor:p(a.delivery_cursor)}:{},...p(a.next_attempt_at)?{nextAttemptAt:p(a.next_attempt_at)}:{},...p(a.last_attempt_at)?{lastAttemptAt:p(a.last_attempt_at)}:{},...p(a.sent_at)?{sentAt:p(a.sent_at)}:{},...p(a.acked_at)?{ackedAt:p(a.acked_at)}:{},...p(a.last_error_code)?{lastErrorCode:p(a.last_error_code)}:{},...p(a.last_error_reason)?{lastErrorReason:p(a.last_error_reason)}:{},...p(a.last_error_summary)?{lastErrorSummary:p(a.last_error_summary)}:{},...p(a.dead_letter_summary)?{deadLetterSummary:p(a.dead_letter_summary)}:{},...p(a.dead_lettered_at)?{deadLetteredAt:p(a.dead_lettered_at)}:{},createdAt:String(a.created_at??""),updatedAt:String(a.updated_at??""),publicSafe:!0}}function g(a){return{...a,publicSafe:!0}}function T(a,e){return a===void 0?null:(S(a,e),JSON.stringify(a))}function U(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()){c(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 i("sqlite-public-safety-rejected",`Continuity SQLite rejected non-relative path at relativePaths[${t}].`)}return e}function V(a){const e={...K(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=U(a.relativePaths)),K(e)}function L(a){c(a.attemptId,"headless_execution.attemptId",160,!0),c(a.executionId,"headless_execution.executionId",160,!0),c(a.jobId,"headless_execution.jobId",160,!0),c(a.directiveHash,"headless_execution.directiveHash",160),c(a.targetRef,"headless_execution.targetRef",240),c(a.storyId,"headless_execution.storyId",120),c(a.epicId,"headless_execution.epicId",120),c(a.runtimeId,"headless_execution.runtimeId",80),c(a.modelId,"headless_execution.modelId",120),c(a.runtimeSource,"headless_execution.runtimeSource",40),c(a.reasonCode,"headless_execution.reasonCode",100),c(a.publicSummary,"headless_execution.publicSummary",240),c(a.leaseId,"headless_execution.leaseId",160),c(a.runnerId,"headless_execution.runnerId",160),c(a.timestamp,"headless_execution.timestamp",80)}function q(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 Et(a){return et.includes(a)}function P(a){return Array.from(new Set(a))}function ft(a){const e=E(a)&&"default"in a?a.default:a;if(typeof e!="function")throw new i("sqlite-adapter-unavailable","Optional better-sqlite3 adapter did not export a database constructor.",{guidance:ie});const t=e;return{adapterName:"better-sqlite3",open(r,s){return new t(r,s)}}}async function gt(a=nt){try{const e=await a("better-sqlite3");return{ok:!0,adapter:ft(e)}}catch(e){return e instanceof i?{ok:!1,error:e}:{ok:!1,error:new i("sqlite-adapter-unavailable","Optional Enterprise continuity SQLite adapter better-sqlite3 is unavailable.",{cause:e,guidance:ie})}}}function Ee(a){return se(a,ne,$e)}function Ct(a){const e=se(a,ne);ae(e,{recursive:!0,mode:448});try{z(e,448)}catch{}return e}async function Wt(a){const e=a.adapter??await ge(a.adapterLoader),t=a.filePath??Ee(a.projectRoot);if(a.strictReadOnly)fe(t);else if(a.filePath){ae(re(t),{recursive:!0,mode:448});try{z(re(t),448)}catch{}}else Ct(a.projectRoot);let r;try{r=e.open(t,a.strictReadOnly?{fileMustExist:!0,readonly:!0}:void 0)}catch(n){throw y(n,"sqlite-integrity-failed")}const s=new At({db:r,filePath:t,adapterName:e.adapterName,busyTimeoutMs:a.busyTimeoutMs??Ye,integrityCheck:a.integrityCheck??!0,now:a.now??(()=>new Date().toISOString())});try{if(a.strictReadOnly)return s.runIntegrityCheck(),s.getSchemaVersion(),s;if(s.initialize(),te(t))try{z(t,384)}catch{}return s}catch(n){try{r.close()}catch{}throw n}}function fe(a){if(!te(a))throw new i("sqlite-projection-missing","Continuity database is unavailable for physical read-only inspection.",{mutationBlocked:!0});let e;try{const t=Ae(a,"r");try{if(e=J.alloc(20),xe(t,e,0,e.length,0)<e.length)throw new Error("short-header")}finally{Se(t)}}catch(t){throw new i("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 i("sqlite-integrity-failed","Continuity database header is not a recognized SQLite database.",{mutationBlocked:!0});if(e[18]===2||e[19]===2)throw new i("sqlite-projection-wal-unsafe","Continuity database requires an unsafe WAL read profile.",{mutationBlocked:!0})}async function St(a){const e=Ee(a.projectRoot);fe(e);const t=a.adapter??await ge(a.adapterLoader);let r,s=!1;try{r=t.open(e,{fileMustExist:!0,readonly:!0}),s=!0;const d=q(r.pragma("integrity_check",{simple:!0}));if(String(d).toLowerCase()!=="ok")throw new Error("integrity")}catch(d){throw new i(s?"sqlite-integrity-failed":"sqlite-projection-adapter-incompatible","Continuity database failed physical read-only inspection.",{cause:d,mutationBlocked:!0})}const n=d=>{const o=d.trim().replace(/^\(+/u,"").toLowerCase();if(!/^(select|with\s)/u.test(o)||/\b(insert|update|delete|replace|create|alter|drop|pragma|attach|detach|vacuum|reindex)\b/u.test(o))throw new i("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,...o){return n(d),r.prepare(d).all(...o)},get(d,...o){return n(d),r.prepare(d).get(...o)},close(){r.close()}})}async function Ft(a){if(!Number.isSafeInteger(a.authorityRevision)||a.authorityRevision<0||!/^[a-f0-9]{64}$/.test(a.sourceDigest))throw new i("sqlite-integrity-failed","Epic operational SQLite binding input is invalid.",{mutationBlocked:!0});let e;try{e=await St(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 n=JSON.parse(s.metadata_json);return E(n)&&n.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 i?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 ge(a){const e=a?await a():await gt();if(!e.ok)throw e.error;return e.adapter}class At{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 y(e,"sqlite-migration-failed")}}close(){this.db.close()}pragmaValue(e){return q(this.db.pragma(e,{simple:!0}))}runIntegrityCheck(){try{if(String(q(this.db.pragma("integrity_check",{simple:!0}))??"").toLowerCase()!=="ok")throw this.mutationBlocked=!0,new i("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,y(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(!Et(e))throw new i("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(),!we(e.binding)||!Ue(e.hostAttestation))throw new i("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(!X(t))throw new i("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(o=>o.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 o=r.length===1?j(r[0]):null;if(!o||!Me(o)||t.topology!=="native-agent"||e.hostAttestation.hostKind==="unknown"||e.hostAttestation.origin==="explicit-override"||t.dispatchKey!==
|
|
5
|
+
`).all(t.dispatchKey,t.storyId,t.graphRevision),s=r.find(o=>o.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 o=r.length===1?j(r[0]):null;if(!o||!Me(o)||t.topology!=="native-agent"||e.hostAttestation.hostKind==="unknown"||e.hostAttestation.origin==="explicit-override"||t.dispatchKey!==De(o.dispatchKey))throw new Error("native-agent-reservation-binding-conflict")}const n=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),
|
|
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 i("sqlite-mutation-failed","Native-agent reservation conflicts with an existing story graph binding.");return Object.freeze({receipt:j(d),reserved:n.changes===1,replay:n.changes===0})})}catch(r){throw y(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 i("sqlite-mutation-failed","Native-agent dispatch reservation is missing.");const r=j(t),s=oe.has(e.state)?e.terminalAt??e.observedAt:null,n=e.handle??r.handle,d=e.parentHandle===void 0?r.parentHandle:e.parentHandle,o={...r,handle:n,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(!X(o))throw new i("sqlite-public-safety-rejected","Native-agent observation rejected unsafe or inconsistent fields.");if(r.handle&&e.handle&&r.handle!==e.handle)throw new i("sqlite-mutation-failed","Native-agent observation handle conflicts with the reserved dispatch.");if(!ke(r.state,e.state))throw new i("sqlite-mutation-failed","Native-agent observation attempted a terminal or non-monotonic regression.");if(r.state===o.state&&r.handle===o.handle&&r.parentHandle===o.parentHandle&&r.topology===o.topology&&r.observedAt===o.observedAt&&r.terminalAt===o.terminalAt&&r.freshness===o.freshness&&r.observationSource===o.observationSource&&r.reasonCode===o.reasonCode)return Object.freeze({receipt:r,applied:!1,replay:!0});if(e.expectedRevision!==r.revision)throw new i("sqlite-mutation-failed","Native-agent observation CAS revision conflict.");if(r.observedAt&&Date.parse(e.observedAt)<Date.parse(r.observedAt))throw new i("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 J}from"node:buffer";import{createHash as D}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(o.dispatchKey,o.revision,o.state,o.handle,o.parentHandle,o.topology,o.observedAt,o.terminalAt,o.freshness,o.observationSource,o.reasonCode),Object.freeze({receipt:o,applied:!0,replay:!1})})}catch(t){throw
|
|
22
|
+
`).run(o.dispatchKey,o.revision,o.state,o.handle,o.parentHandle,o.topology,o.observedAt,o.terminalAt,o.freshness,o.observationSource,o.reasonCode),Object.freeze({receipt:o,applied:!0,replay:!1})})}catch(t){throw y(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),n=Math.max(1e3,t.staleAfterMs??3e4),d=Date.parse(t.nowIso??this.now()),o=s.observedAt?Date.parse(s.observedAt):NaN;return!oe.has(s.state)&&Number.isFinite(d)&&(!Number.isFinite(o)||d-o>n)?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 ?
|
|
@@ -28,12 +28,16 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
28
28
|
WHERE state NOT IN ('completed', 'failed', 'interrupted')
|
|
29
29
|
ORDER BY COALESCE(observed_at, requested_at) DESC, dispatch_key DESC
|
|
30
30
|
LIMIT ?
|
|
31
|
-
`).all(e);return Object.freeze(t.map(j))}
|
|
32
|
-
SELECT
|
|
31
|
+
`).all(e);return Object.freeze(t.map(j))}getUnsettledStoryWorker(e,t=this.now()){c(e,"headless_resume.storyId",160,!0),c(t,"headless_resume.nowIso",80,!0);const r=this.db.prepare(`
|
|
32
|
+
SELECT attempt_id AS attemptId, status, runner_id AS ownerRunnerId,
|
|
33
|
+
lease_id AS leaseId, lease_expires_at AS leaseExpiresAt
|
|
34
|
+
FROM headless_execution_attempts
|
|
33
35
|
WHERE directive_kind = 'run_yolo' AND story_id = ?
|
|
34
|
-
AND (status
|
|
36
|
+
AND (status IN ('running', 'backoff', 'timed_out')
|
|
37
|
+
OR dead_letter_reason_code = ? OR reason_code IN (?, ?, ?))
|
|
38
|
+
ORDER BY COALESCE(started_at, enqueued_at) DESC, attempt_id DESC
|
|
35
39
|
LIMIT 1
|
|
36
|
-
`).get(e,v.ATTEMPTS_EXHAUSTED,v.LEASE_TIMEOUT_RETRY);return
|
|
40
|
+
`).get(e,v.ATTEMPTS_EXHAUSTED,v.LEASE_TIMEOUT_RETRY,"headless-resume-effect-unverified","headless-execution-failed");if(!r||typeof r.attemptId!="string"||typeof r.status!="string")return null;const s=typeof r.leaseExpiresAt=="string"&&Number.isFinite(Date.parse(t))&&Date.parse(r.leaseExpiresAt)<=Date.parse(t),n=r.status==="running"&&s?"story-worktree-worker-liveness-unverified":r.status==="running"?"story-worktree-worker-active":r.status==="backoff"?"story-worktree-worker-retry-unverified":r.status==="timed_out"?"story-worktree-worker-timeout-unverified":"story-worktree-worker-effect-unverified";return{attemptId:r.attemptId,status:r.status,ownerRunnerId:typeof r.ownerRunnerId=="string"?r.ownerRunnerId:null,leaseId:typeof r.leaseId=="string"?r.leaseId:null,leaseExpiresAt:typeof r.leaseExpiresAt=="string"?r.leaseExpiresAt:null,reasonCode:n}}hasUnsettledStoryWorker(e){return this.getUnsettledStoryWorker(e)!==null}findNativeAgentDispatchRow(e,t,r){return this.db.prepare(`
|
|
37
41
|
SELECT * FROM native_agent_dispatches
|
|
38
42
|
WHERE dispatch_key = ? AND story_id = ? AND graph_revision = ?
|
|
39
43
|
`).get(e,t,r)}getLocalConsoleAttachmentState(e){c(e,"local_console.jobId",160,!0);const t=this.db.prepare(`
|
|
@@ -45,30 +49,27 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
45
49
|
FROM jobs j
|
|
46
50
|
WHERE j.job_id = ?
|
|
47
51
|
LIMIT 1
|
|
48
|
-
`).get(e);return!
|
|
52
|
+
`).get(e);return!E(t)||typeof t.job_id!="string"?null:{jobId:t.job_id,kind:typeof t.kind=="string"?t.kind:"unknown",status:typeof t.status=="string"?t.status:"unknown",activeLeaseCount:typeof t.active_lease_count=="number"?t.active_lease_count:0,runningHeadlessAttemptCount:typeof t.running_headless_attempt_count=="number"?t.running_headless_attempt_count:0,publicSafe:!0}}recordJob(e){this.assertCanMutate(),I(e.summary,"jobs.summary");const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
49
53
|
INSERT OR IGNORE INTO jobs (
|
|
50
54
|
job_id, kind, status, summary, reason_code, created_at, updated_at,
|
|
51
55
|
next_run_at, goal_id, loop_id, campaign_id, operation_id,
|
|
52
56
|
idempotency_key, metadata_json
|
|
53
57
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
54
|
-
`).run(e.jobId,e.kind,e.status,e.summary??null,e.reasonCode??null,e.createdAt,e.updatedAt,e.nextRunAt??null,e.goalId??null,e.loopId??null,e.campaignId??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw
|
|
58
|
+
`).run(e.jobId,e.kind,e.status,e.summary??null,e.reasonCode??null,e.createdAt,e.updatedAt,e.nextRunAt??null,e.goalId??null,e.loopId??null,e.campaignId??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw y(r,"sqlite-mutation-failed")}}appendEvent(e){this.assertCanMutate(),I(e.summary,"job_events.summary");const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
55
59
|
INSERT OR IGNORE INTO job_events (
|
|
56
60
|
event_id, job_id, operation_id, idempotency_key, event_sequence,
|
|
57
61
|
type, summary, reason_code, created_at, metadata_json
|
|
58
62
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
59
|
-
`).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
|
|
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 y(r,"sqlite-mutation-failed")}}recordProcessingOutputSummary(e){Y(e.executionId,"processing_output_summary.executionId",160),Y(e.jobId,"processing_output_summary.jobId",160),Y(e.publicSummary,"processing_output_summary.publicSummary",Ke),Y(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:ut(e),jobId:e.jobId,operationId:e.executionId,idempotencyKey:e.idempotencyKey??e.executionId,type:N,summary:e.publicSummary,reasonCode:e.reasonCode,createdAt:e.createdAt,metadata:lt(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(),L({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}),c(e.notBeforeAt,"headless_execution.notBeforeAt",80),c(e.operationId,"headless_execution.operationId",160),c(e.idempotencyKey,"headless_execution.idempotencyKey",160),O(e.retryCount,"headless_execution.retryCount"),O(e.maxAttempts,"headless_execution.maxAttempts"),e.maxAttempts!==void 0&&e.maxAttempts<1)throw new i("sqlite-public-safety-rejected","Continuity SQLite maxAttempts must be greater than zero.");e.metadata&&S(e.metadata,"headless_execution.metadata");const t=$({maxItems:e.queueCap,maxAttempts:e.maxAttempts}),r=We(e.queuePriority),s=Fe(e.queueScope),n=U(e.relativePaths),d=V({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:n,metadata:e.metadata});return this.runInTransaction(()=>{const o=this.db.prepare(`
|
|
60
64
|
SELECT value_json
|
|
61
65
|
FROM runner_config
|
|
62
66
|
WHERE key = 'headless_queue_policy'
|
|
63
67
|
LIMIT 1
|
|
64
|
-
`).get();let l=t.maxItems;if(e.queueCap===void 0&&
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
updated_at = excluded.updated_at
|
|
70
|
-
`).run(JSON.stringify({maxItems:l}),e.enqueuedAt);const I=this.db.prepare(`
|
|
71
|
-
SELECT attempt_id
|
|
68
|
+
`).get();let l=t.maxItems;if(e.queueCap===void 0&&E(o)&&typeof o.value_json=="string")try{const u=JSON.parse(o.value_json);E(u)&&typeof u.maxItems=="number"&&(l=$({maxItems:u.maxItems}).maxItems)}catch{}const _=this.db.prepare(`
|
|
69
|
+
SELECT attempt_id, execution_id, job_id, directive_hash, directive_kind,
|
|
70
|
+
command_class, target_kind, target_ref, story_id, epic_id,
|
|
71
|
+
runtime_id, model_id, runtime_source,
|
|
72
|
+
operation_id, idempotency_key
|
|
72
73
|
FROM headless_execution_attempts
|
|
73
74
|
WHERE attempt_id = ?
|
|
74
75
|
OR (? IS NOT NULL AND operation_id = ?)
|
|
@@ -79,7 +80,13 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
79
80
|
FROM headless_execution_attempts
|
|
80
81
|
WHERE status IN ('queued', 'backoff', 'running')
|
|
81
82
|
AND dead_lettered_at IS NULL
|
|
82
|
-
`).get(),f=
|
|
83
|
+
`).get(),f=E(h)&&typeof h.count=="number"?h.count:0;if(_)return _.attempt_id===e.attemptId&&_.execution_id===e.executionId&&_.job_id===e.jobId&&_.directive_hash===e.directiveHash&&_.directive_kind===e.directiveKind&&_.command_class===e.commandClass&&_.target_kind===e.targetKind&&_.target_ref===e.targetRef&&_.story_id===(e.storyId??null)&&_.epic_id===(e.epicId??null)&&_.runtime_id===(e.runtimeId??null)&&_.model_id===(e.modelId??null)&&_.runtime_source===(e.runtimeSource??null)&&_.operation_id===(e.operationId??null)&&_.idempotency_key===(e.idempotencyKey??null)?{inserted:!1,replay:!0,changes:0,accepted:!0,backpressure:f>=l,queueDepth:f,queueCap:l,publicSafe:!0}:{inserted:!1,replay:!1,changes:0,accepted:!1,backpressure:!1,queueDepth:f,queueCap:l,reasonCode:"headless-resume-binding-conflict",publicSafe:!0};if(f>=l)return{inserted:!1,replay:!1,changes:0,accepted:!1,backpressure:!0,queueDepth:f,queueCap:l,reasonCode:v.CAP_REACHED,publicSafe:!0};this.db.prepare(`
|
|
84
|
+
INSERT INTO runner_config (key, value_json, updated_at)
|
|
85
|
+
VALUES ('headless_queue_policy', ?, ?)
|
|
86
|
+
ON CONFLICT(key) DO UPDATE SET
|
|
87
|
+
value_json = excluded.value_json,
|
|
88
|
+
updated_at = excluded.updated_at
|
|
89
|
+
`).run(JSON.stringify({maxItems:l}),e.enqueuedAt);const m=this.db.prepare(`
|
|
83
90
|
INSERT INTO headless_execution_attempts (
|
|
84
91
|
attempt_id, execution_id, job_id, directive_hash, directive_kind,
|
|
85
92
|
command_class, target_kind, target_ref, story_id, epic_id, runtime_id,
|
|
@@ -89,7 +96,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
89
96
|
relative_paths_json, metadata_json, queue_priority, queue_scope,
|
|
90
97
|
attempt_count, next_retry_at
|
|
91
98
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)
|
|
92
|
-
`).run(e.attemptId,e.executionId,e.jobId,e.directiveHash,e.directiveKind,e.commandClass,e.targetKind,e.targetRef,e.storyId??null,e.epicId??null,e.runtimeId??null,e.modelId??null,e.runtimeSource??null,e.status??"queued",e.reasonCode??null,e.publicSummary??null,e.enqueuedAt,e.status==="backoff"?e.notBeforeAt??e.enqueuedAt:null,e.retryCount??0,t.maxAttempts,e.operationId??null,e.idempotencyKey??null,T(e.counts,"headless_execution.counts"),T(e.hashes,"headless_execution.hashes"),T(e.redactionSummary,"headless_execution.redactionSummary"),T(
|
|
99
|
+
`).run(e.attemptId,e.executionId,e.jobId,e.directiveHash,e.directiveKind,e.commandClass,e.targetKind,e.targetRef,e.storyId??null,e.epicId??null,e.runtimeId??null,e.modelId??null,e.runtimeSource??null,e.status??"queued",e.reasonCode??null,e.publicSummary??null,e.enqueuedAt,e.status==="backoff"?e.notBeforeAt??e.enqueuedAt:null,e.retryCount??0,t.maxAttempts,e.operationId??null,e.idempotencyKey??null,T(e.counts,"headless_execution.counts"),T(e.hashes,"headless_execution.hashes"),T(e.redactionSummary,"headless_execution.redactionSummary"),T(n,"headless_execution.relativePaths"),C(d),r,s,e.notBeforeAt??e.enqueuedAt);return{inserted:m.changes>0,replay:!1,changes:m.changes,accepted:m.changes>0,backpressure:f+m.changes>=l,queueDepth:f+m.changes,queueCap:l,publicSafe:!0}})}listDueHeadlessExecutionAttempts(e){const t=Math.max(1,Math.min(50,Math.floor(e.limit)));return c(e.nowIso,"headless_execution.nowIso",80,!0),this.db.prepare(`
|
|
93
100
|
SELECT attempt_id, execution_id, job_id, directive_hash, directive_kind,
|
|
94
101
|
command_class, target_kind, target_ref, story_id, epic_id,
|
|
95
102
|
runtime_id, model_id, runtime_source, status, reason_code,
|
|
@@ -114,7 +121,28 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
114
121
|
WHERE directive_hash = ?
|
|
115
122
|
AND status = 'completed'${r}
|
|
116
123
|
LIMIT 1
|
|
117
|
-
`).get(...s)?.found===1}
|
|
124
|
+
`).get(...s)?.found===1}getAppliedHeadlessExecutionReceipt(e){for(const[r,s]of Object.entries(e))c(s,`headless_resume.${r}`,r==="targetRef"?240:160,!0);const t=this.db.prepare(`
|
|
125
|
+
SELECT r.receipt_id AS receiptId, r.created_at AS createdAt,
|
|
126
|
+
r.reason_code AS reasonCode, a.runner_id AS ownerRunnerId,
|
|
127
|
+
a.lease_id AS leaseId
|
|
128
|
+
FROM headless_execution_attempts a
|
|
129
|
+
JOIN job_receipts r ON r.job_id = a.job_id
|
|
130
|
+
WHERE a.attempt_id = ? AND a.execution_id = ? AND a.job_id = ?
|
|
131
|
+
AND a.story_id = ? AND a.target_ref = ?
|
|
132
|
+
AND a.directive_kind = 'run_yolo' AND a.target_kind = 'story'
|
|
133
|
+
AND a.status = 'completed' AND a.completed_at IS NOT NULL
|
|
134
|
+
AND a.runner_id IS NOT NULL AND a.lease_id IS NOT NULL
|
|
135
|
+
AND a.lease_released_at IS NOT NULL
|
|
136
|
+
AND a.started_at IS NOT NULL AND r.created_at >= a.started_at
|
|
137
|
+
AND r.operation_id = a.execution_id || ':completed:receipt'
|
|
138
|
+
AND r.idempotency_key = a.directive_hash || ':completed:receipt'
|
|
139
|
+
AND r.status = 'applied'
|
|
140
|
+
AND json_array_length(r.applied_operation_ids_json) = 1
|
|
141
|
+
AND json_extract(r.applied_operation_ids_json, '$[0]') = a.execution_id
|
|
142
|
+
AND json_extract(r.metadata_json, '$.attemptId') = a.attempt_id
|
|
143
|
+
AND json_extract(r.metadata_json, '$.hashes.directive') = a.directive_hash
|
|
144
|
+
LIMIT 1
|
|
145
|
+
`).get(e.attemptId,e.executionId,e.jobId,e.storyId,e.targetRef);return t&&typeof t.receiptId=="string"&&typeof t.createdAt=="string"&&typeof t.reasonCode=="string"&&typeof t.ownerRunnerId=="string"&&typeof t.leaseId=="string"?{receiptId:t.receiptId,createdAt:t.createdAt,reasonCode:t.reasonCode,ownerRunnerId:t.ownerRunnerId,leaseId:t.leaseId}:null}claimHeadlessExecutionAttempt(e){this.assertCanMutate(),L({attemptId:e.attemptId,executionId:e.attemptId,jobId:e.attemptId,leaseId:e.leaseId,runnerId:e.runnerId,reasonCode:e.reasonCode,timestamp:e.claimedAt}),c(e.leaseExpiresAt,"headless_execution.leaseExpiresAt",80,!0);try{const t=this.db.prepare(`
|
|
118
146
|
UPDATE headless_execution_attempts
|
|
119
147
|
SET status = 'running',
|
|
120
148
|
lease_id = ?,
|
|
@@ -130,7 +158,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
130
158
|
AND dead_lettered_at IS NULL
|
|
131
159
|
AND (COALESCE(next_retry_at, not_before_at) IS NULL OR COALESCE(next_retry_at, not_before_at) <= ?)
|
|
132
160
|
AND (lease_id IS NULL OR lease_released_at IS NOT NULL OR lease_expires_at <= ?)
|
|
133
|
-
`).run(e.leaseId,e.runnerId,e.claimedAt,e.claimedAt,e.leaseExpiresAt,e.reasonCode??null,e.attemptId,e.claimedAt,e.claimedAt);return this.toWriteResult(t)}catch(t){throw
|
|
161
|
+
`).run(e.leaseId,e.runnerId,e.claimedAt,e.claimedAt,e.leaseExpiresAt,e.reasonCode??null,e.attemptId,e.claimedAt,e.claimedAt);return this.toWriteResult(t)}catch(t){throw y(t,"sqlite-mutation-failed")}}acquireNextHeadlessExecutionAttempt(e){return this.assertCanMutate(),L({attemptId:e.leaseId,executionId:e.leaseId,jobId:e.leaseId,leaseId:e.leaseId,runnerId:e.runnerId,reasonCode:e.reasonCode,timestamp:e.claimedAt}),c(e.leaseExpiresAt,"headless_execution.leaseExpiresAt",80,!0),this.runInTransaction(()=>{const t=this.db.prepare(`
|
|
134
162
|
SELECT attempt_id
|
|
135
163
|
FROM headless_execution_attempts
|
|
136
164
|
WHERE status IN ('queued', 'backoff')
|
|
@@ -169,7 +197,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
169
197
|
AND status = 'running'
|
|
170
198
|
AND lease_released_at IS NULL
|
|
171
199
|
AND lease_expires_at > ?
|
|
172
|
-
`).run(e.heartbeatAt,e.leaseExpiresAt??null,e.attemptId,e.leaseId,e.runnerId,e.heartbeatAt);return this.toWriteResult(t)}catch(t){throw
|
|
200
|
+
`).run(e.heartbeatAt,e.leaseExpiresAt??null,e.attemptId,e.leaseId,e.runnerId,e.heartbeatAt);return this.toWriteResult(t)}catch(t){throw y(t,"sqlite-mutation-failed")}}releaseHeadlessExecutionAttempt(e){this.assertCanMutate(),L({attemptId:e.attemptId,executionId:e.attemptId,jobId:e.attemptId,leaseId:e.leaseId,reasonCode:e.reasonCode,timestamp:e.releasedAt}),c(e.notBeforeAt,"headless_execution.notBeforeAt",80),O(e.retryCount,"headless_execution.retryCount");try{const t=this.db.prepare(`
|
|
173
201
|
UPDATE headless_execution_attempts
|
|
174
202
|
SET status = COALESCE(?, status),
|
|
175
203
|
reason_code = COALESCE(?, reason_code),
|
|
@@ -185,8 +213,8 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
185
213
|
AND lease_id = ?
|
|
186
214
|
AND status = 'running'
|
|
187
215
|
AND lease_released_at IS NULL
|
|
188
|
-
`).run(e.status??null,e.reasonCode??null,e.notBeforeAt??null,e.retryCount??null,e.status??null,e.notBeforeAt??null,e.status??null,e.releasedAt,e.attemptId,e.leaseId);return this.toWriteResult(t)}catch(t){throw
|
|
189
|
-
AND lease_released_at IS NULL${e.runnerId?" AND runner_id = ?":""}`:"",
|
|
216
|
+
`).run(e.status??null,e.reasonCode??null,e.notBeforeAt??null,e.retryCount??null,e.status??null,e.notBeforeAt??null,e.status??null,e.releasedAt,e.attemptId,e.leaseId);return this.toWriteResult(t)}catch(t){throw y(t,"sqlite-mutation-failed")}}completeHeadlessExecutionAttempt(e){this.assertCanMutate(),L({attemptId:e.attemptId,executionId:e.attemptId,jobId:e.attemptId,leaseId:e.leaseId,runnerId:e.runnerId,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.completedAt}),c(e.notBeforeAt,"headless_execution.notBeforeAt",80),O(e.durationMs,"headless_execution.durationMs"),O(e.retryCount,"headless_execution.retryCount"),e.metadata&&S(e.metadata,"headless_execution.metadata");const t=U(e.relativePaths),r=V({attemptId:e.attemptId,executionId:e.executionId??e.attemptId,jobId:e.jobId??e.attemptId,status:e.status,reasonCode:e.reasonCode,durationMs:e.durationMs,retryCount:e.retryCount,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:t,metadata:e.metadata}),s=e.leaseId?` AND lease_id = ?
|
|
217
|
+
AND lease_released_at IS NULL${e.runnerId?" AND runner_id = ?":""}`:"",n=e.leaseId?"status = 'running'":"status NOT IN ('completed', 'failed', 'timed_out', 'skipped')",d=[e.status,e.completedAt,e.durationMs??null,e.reasonCode??null,e.publicSummary??null,e.notBeforeAt??null,e.retryCount??null,e.status,e.notBeforeAt??null,e.counts?T(e.counts,"headless_execution.counts"):null,e.hashes?T(e.hashes,"headless_execution.hashes"):null,e.redactionSummary?T(e.redactionSummary,"headless_execution.redactionSummary"):null,t?T(t,"headless_execution.relativePaths"):null,C(r),e.completedAt,e.attemptId];e.leaseId&&d.push(e.leaseId),e.leaseId&&e.runnerId&&d.push(e.runnerId);try{const o=this.db.prepare(`
|
|
190
218
|
UPDATE headless_execution_attempts
|
|
191
219
|
SET status = ?,
|
|
192
220
|
completed_at = ?,
|
|
@@ -206,20 +234,20 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
206
234
|
metadata_json = COALESCE(?, metadata_json),
|
|
207
235
|
lease_released_at = COALESCE(lease_released_at, ?)
|
|
208
236
|
WHERE attempt_id = ?${s}
|
|
209
|
-
AND ${
|
|
210
|
-
`).run(...
|
|
237
|
+
AND ${n}
|
|
238
|
+
`).run(...d);return this.toWriteResult(o)}catch(o){throw y(o,"sqlite-mutation-failed")}}recordHeadlessExecutionReceipt(e){L({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,reasonCode:e.reasonCode,timestamp:e.createdAt}),e.metadata&&S(e.metadata,"headless_execution.metadata");const t=U(e.relativePaths),r=V({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,status:e.status,reasonCode:e.reasonCode,counts:e.counts,hashes:e.hashes,redactionSummary:e.redactionSummary,relativePaths:t,metadata:e.metadata});return this.appendReceipt({receiptId:e.receiptId,jobId:e.jobId,operationId:e.operationId??e.executionId,idempotencyKey:e.idempotencyKey??e.executionId,status:e.status,reasonCode:e.reasonCode,appliedOperationIds:e.status==="applied"?[e.executionId]:void 0,ignoredOperationIds:e.status==="ignored"?[e.executionId]:void 0,createdAt:e.createdAt,metadata:r})}recordHeadlessExecutionSummary(e){L({attemptId:e.attemptId,executionId:e.executionId,jobId:e.jobId,runtimeId:e.runtimeId,modelId:e.modelId,reasonCode:e.reasonCode,publicSummary:e.publicSummary,timestamp:e.createdAt}),O(e.durationMs,"headless_execution.durationMs"),e.metadata&&S(e.metadata,"headless_execution.metadata");const t=U(e.relativePaths),r=V({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=C(e.metadata);try{const r=this.db.prepare(`
|
|
211
239
|
INSERT OR IGNORE INTO job_receipts (
|
|
212
240
|
receipt_id, job_id, operation_id, idempotency_key, status, reason_code,
|
|
213
241
|
applied_operation_ids_json, ignored_operation_ids_json, created_at, metadata_json
|
|
214
242
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
215
|
-
`).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
|
|
243
|
+
`).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 y(r,"sqlite-mutation-failed")}}compactPublicReceiptsAndOutputs(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new i("sqlite-public-safety-rejected","Continuity receipt compaction requires a valid public timestamp.");const r=Be(e.policy),s=new Date(t-r.receipts.maxAgeMs).toISOString(),n=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}),o=this.selectOutputRetentionCandidates({cutoff:n,maxItems:r.processingOutputs.maxItems,maxBytes:r.processingOutputs.maxBytes,limit:r.maxDeleteRowsPerRun}),l=[...d,...o].sort((u,b)=>u.createdAt.localeCompare(b.createdAt)||u.id.localeCompare(b.id)).slice(0,r.maxDeleteRowsPerRun);if(l.length===0)return{status:"noop",summaries:[],counts:{receiptsRemoved:0,outputsRemoved:0,bytesRemoved:0,summariesCreated:0},reasonCode:B.NOOP,publicSafe:!0};const _=l.filter(u=>u.kind==="receipt"),h=l.filter(u=>u.kind==="output");for(const u of P(_.map(b=>b.jobId)))this.preserveReceiptDerivedIteration(u,e.nowIso);this.deleteRetentionCandidates("job_receipts","receipt_id",_.map(u=>u.id)),this.deleteRetentionCandidates("job_events","event_id",h.map(u=>u.id));const f=new Map;for(const u of l)f.set(u.jobId,[...f.get(u.jobId)??[],u]);const m=[];for(const[u,b]of[...f.entries()].sort(([x],[A])=>x.localeCompare(A))){const x=b.filter(D=>D.kind==="receipt"),A=b.filter(D=>D.kind==="output"),Q=this.retainedReceiptOutputCounts(u),G=yt(u,x,A),R={receiptsRemoved:x.length,receiptsRetained:Q.receipts,outputsRemoved:A.length,outputsRetained:Q.outputs,bytesRemoved:b.reduce((D,Ce)=>D+Ce.approxBytes,0),bytesRetained:Q.bytes,redactions:0},H=`Compacted public receipt and processing evidence: receipts removed ${R.receiptsRemoved}, retained ${R.receiptsRetained}; summaries removed ${R.outputsRemoved}, retained ${R.outputsRetained}; bytes removed ${R.bytesRemoved}, retained ${R.bytesRetained}.`;c(H,"receipt_compaction.publicSummary",500,!0);const W=`receipt-compaction-${k("sha256").update(`${u}:${e.nowIso}:${G.aggregate}`).digest("hex").slice(0,32)}`,ee={schemaVersion:1,contractVersion:"continuity-v1",policyVersion:1,type:F,summaryId:W,jobId:u,scope:"local_sqlite",status:"compacted",createdAt:e.nowIso,reasonCodes:[B.COMPACTED],counts:R,hashes:G,publicSummary:H,publicSafe:!0};this.appendEvent({eventId:W,jobId:u,operationId:`op-${W}`,idempotencyKey:`idem-${W}`,type:F,summary:H,reasonCode:B.COMPACTED,createdAt:e.nowIso,metadata:{schemaVersion:1,contractVersion:"continuity-v1",eventType:F,jobId:u,reasonCodes:ee.reasonCodes,counts:R,hashes:G,publicSummary:H}}),this.pruneReceiptCompactionSummaries(u,r.maxCompactionSummariesPerJob),m.push(ee)}return{status:"compacted",summaries:m,counts:{receiptsRemoved:_.length,outputsRemoved:h.length,bytesRemoved:l.reduce((u,b)=>u+b.approxBytes,0),summariesCreated:m.length},reasonCode:B.COMPACTED,publicSafe:!0}})}catch(d){throw y(d,"sqlite-mutation-failed")}}updateJobStatus(e){this.assertCanMutate();try{const t=this.db.prepare(`
|
|
216
244
|
UPDATE jobs
|
|
217
245
|
SET status = ?,
|
|
218
246
|
reason_code = COALESCE(?, reason_code),
|
|
219
247
|
updated_at = ?,
|
|
220
248
|
next_run_at = COALESCE(?, next_run_at)
|
|
221
249
|
WHERE job_id = ?
|
|
222
|
-
`).run(e.status,e.reasonCode??null,e.updatedAt,e.nextRunAt??null,e.jobId);if(t.changes===0)throw new i("sqlite-foreign-key-failed",`Continuity SQLite job ${e.jobId} was not found for status update.`);return this.toWriteResult(t)}catch(t){throw
|
|
250
|
+
`).run(e.status,e.reasonCode??null,e.updatedAt,e.nextRunAt??null,e.jobId);if(t.changes===0)throw new i("sqlite-foreign-key-failed",`Continuity SQLite job ${e.jobId} was not found for status update.`);return this.toWriteResult(t)}catch(t){throw y(t,"sqlite-mutation-failed")}}recordJobStageProgress(e){this.assertCanMutate(),c(e.jobId,"job_stage.jobId",160,!0);const t=le(e.currentStage)?e.currentStage:void 0,r=Xe(e.iteration);if(!t&&r===void 0)return{inserted:!1,replay:!1,changes:0};const s=ue(e.at);try{const n=this.db.prepare("SELECT metadata_json FROM jobs WHERE job_id = ?").get(e.jobId);if(!n)return{inserted:!1,replay:!1,changes:0};const d=ht(typeof n.metadata_json=="string"?n.metadata_json:null);if(t&&(d.currentStage=t),r!==void 0&&(d.iteration=r),t&&s&&e.appendHistory!==!1){const l=ze(d.stageHistory);l.push({stage:t,at:s}),d.stageHistory=l.slice(-ce)}const o=this.db.prepare("UPDATE jobs SET metadata_json = ? WHERE job_id = ?").run(C(d),e.jobId);return this.toWriteResult(o)}catch(n){throw y(n,"sqlite-mutation-failed")}}updateJobAndExistingGoalCampaignStatus(e){return this.runInTransaction(()=>{const t=this.db.prepare(`
|
|
223
251
|
UPDATE jobs
|
|
224
252
|
SET status = ?,
|
|
225
253
|
reason_code = COALESCE(?, reason_code),
|
|
@@ -232,26 +260,26 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
232
260
|
reason_code = COALESCE(?, reason_code),
|
|
233
261
|
updated_at = ?
|
|
234
262
|
WHERE job_id = ?
|
|
235
|
-
`).run(e.status,e.reasonCode??null,e.updatedAt,e.jobId);return this.toWriteResult({changes:t.changes+r.changes})})}scheduleNextTick(e){return this.updateJobStatus({jobId:e.jobId,status:"active",updatedAt:e.updatedAt,reasonCode:e.reasonCode,nextRunAt:e.scheduledAt})}acquireLease(e){this.assertCanMutate();const t=
|
|
263
|
+
`).run(e.status,e.reasonCode??null,e.updatedAt,e.jobId);return this.toWriteResult({changes:t.changes+r.changes})})}scheduleNextTick(e){return this.updateJobStatus({jobId:e.jobId,status:"active",updatedAt:e.updatedAt,reasonCode:e.reasonCode,nextRunAt:e.scheduledAt})}acquireLease(e){this.assertCanMutate();const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
236
264
|
INSERT OR IGNORE INTO job_leases (
|
|
237
265
|
lease_id, job_id, runner_id, status, acquired_at, expires_at,
|
|
238
266
|
operation_id, idempotency_key, metadata_json
|
|
239
267
|
) VALUES (?, ?, ?, 'acquired', ?, ?, ?, ?, ?)
|
|
240
|
-
`).run(e.leaseId,e.jobId,e.runnerId,e.acquiredAt,e.expiresAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw
|
|
268
|
+
`).run(e.leaseId,e.jobId,e.runnerId,e.acquiredAt,e.expiresAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw y(r,"sqlite-mutation-failed")}}releaseLease(e){this.assertCanMutate();try{const t=this.db.prepare(`
|
|
241
269
|
UPDATE job_leases
|
|
242
270
|
SET status = 'released', released_at = ?
|
|
243
271
|
WHERE lease_id = ? AND released_at IS NULL
|
|
244
|
-
`).run(e.releasedAt,e.leaseId);if(t.changes===0)throw new i("sqlite-foreign-key-failed",`Continuity SQLite lease ${e.leaseId} was not found for release.`);return this.toWriteResult(t)}catch(t){throw
|
|
272
|
+
`).run(e.releasedAt,e.leaseId);if(t.changes===0)throw new i("sqlite-foreign-key-failed",`Continuity SQLite lease ${e.leaseId} was not found for release.`);return this.toWriteResult(t)}catch(t){throw y(t,"sqlite-mutation-failed")}}recordStateSnapshot(e){this.assertCanMutate(),I(e.summary,"state_snapshots.summary"),I(e.relativePath,"state_snapshots.relative_path");const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
245
273
|
INSERT OR IGNORE INTO state_snapshots (
|
|
246
274
|
snapshot_id, job_id, kind, relative_path, sha256, summary, captured_at,
|
|
247
275
|
operation_id, idempotency_key, metadata_json
|
|
248
276
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
249
|
-
`).run(e.snapshotId,e.jobId??null,e.kind,e.relativePath??null,e.sha256??null,e.summary??null,e.capturedAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw
|
|
277
|
+
`).run(e.snapshotId,e.jobId??null,e.kind,e.relativePath??null,e.sha256??null,e.summary??null,e.capturedAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw y(r,"sqlite-mutation-failed")}}recordArtifact(e){this.assertCanMutate(),I(e.kind,"artifacts.kind"),I(e.relativePath,"artifacts.relative_path"),I(e.summary,"artifacts.summary");const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
250
278
|
INSERT OR IGNORE INTO artifacts (
|
|
251
279
|
artifact_id, job_id, kind, relative_path, sha256, summary,
|
|
252
280
|
operation_id, idempotency_key, created_at, metadata_json
|
|
253
281
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
254
|
-
`).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
|
|
282
|
+
`).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 y(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}),c(e.nextAttemptAt,"outbox.nextAttemptAt",80),c(e.lastAttemptAt,"outbox.lastAttemptAt",80),c(e.sentAt,"outbox.sentAt",80),c(e.ackedAt,"outbox.ackedAt",80),c(e.deadLetteredAt,"outbox.deadLetteredAt",80),O(e.retryCount,"outbox.retryCount"),O(e.attemptCount,"outbox.attemptCount");const t=C(e.payload);try{const r=this.db.prepare(`
|
|
255
283
|
INSERT OR IGNORE INTO outbox (
|
|
256
284
|
outbox_id, job_id, operation_id, idempotency_key, type, status,
|
|
257
285
|
payload_json, retry_count, attempt_count, delivery_cursor,
|
|
@@ -259,7 +287,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
259
287
|
last_error_reason, last_error_summary, dead_letter_summary,
|
|
260
288
|
dead_lettered_at, created_at, updated_at
|
|
261
289
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
262
|
-
`).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
|
|
290
|
+
`).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 y(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(!Ie(d))throw new i("sqlite-public-safety-rejected","Continuity SQLite outbox batch query rejected an unknown status.");const s=r.map(()=>"?").join(", ");return this.db.prepare(`
|
|
263
291
|
SELECT outbox_id, job_id, operation_id, idempotency_key, type, status,
|
|
264
292
|
payload_json, retry_count, attempt_count, delivery_cursor,
|
|
265
293
|
next_attempt_at, last_attempt_at, sent_at, acked_at, last_error_code,
|
|
@@ -270,7 +298,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
270
298
|
AND (status NOT IN ('pending', 'failed') OR next_attempt_at IS NULL OR next_attempt_at <= ?)
|
|
271
299
|
ORDER BY COALESCE(next_attempt_at, created_at) ASC, created_at ASC, outbox_id ASC
|
|
272
300
|
LIMIT ?
|
|
273
|
-
`).all(...r,e.nowIso,t).map(
|
|
301
|
+
`).all(...r,e.nowIso,t).map(It)}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(`
|
|
274
302
|
UPDATE outbox
|
|
275
303
|
SET status = 'sent',
|
|
276
304
|
delivery_cursor = ?,
|
|
@@ -281,7 +309,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
281
309
|
updated_at = ?
|
|
282
310
|
WHERE outbox_id = ?
|
|
283
311
|
AND status IN ('pending', 'failed')
|
|
284
|
-
`).run(e.deliveryCursor,e.sentAt,e.sentAt,e.sentAt,e.outboxId);return
|
|
312
|
+
`).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 y(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(`
|
|
285
313
|
UPDATE outbox
|
|
286
314
|
SET status = 'acked',
|
|
287
315
|
acked_at = ?,
|
|
@@ -291,7 +319,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
291
319
|
last_error_reason = NULL
|
|
292
320
|
WHERE outbox_id = ?
|
|
293
321
|
AND status = 'sent'
|
|
294
|
-
`).run(e.ackedAt,e.ackedAt,e.outboxId);return
|
|
322
|
+
`).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 y(t,"sqlite-mutation-failed")}}failOutboxDelivery(e){this.assertCanMutate(),M({outboxId:e.outboxId,deliveryCursor:e.deliveryCursor,timestamp:e.failedAt,reasonCode:e.reasonCode,summary:e.summary}),c(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=He({nowIso:e.failedAt,attemptCount:r,reasonCode:e.reasonCode,summary:e.summary,nextRetryAt:e.nextRetryAt,policy:e.policy}),n=this.db.prepare(`
|
|
295
323
|
UPDATE outbox
|
|
296
324
|
SET status = ?,
|
|
297
325
|
retry_count = MAX(retry_count, ?),
|
|
@@ -304,7 +332,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
304
332
|
updated_at = ?
|
|
305
333
|
WHERE outbox_id = ?
|
|
306
334
|
AND status IN ('pending', 'sent', 'failed')
|
|
307
|
-
`).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
|
|
335
|
+
`).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:n.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 y(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(`
|
|
308
336
|
UPDATE outbox
|
|
309
337
|
SET status = 'dead_letter',
|
|
310
338
|
next_attempt_at = NULL,
|
|
@@ -316,13 +344,13 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
316
344
|
updated_at = ?
|
|
317
345
|
WHERE outbox_id = ?
|
|
318
346
|
AND status <> 'acked'
|
|
319
|
-
`).run(e.reasonCode,e.reasonCode,e.summary,e.summary,e.deadLetteredAt,e.deadLetteredAt,e.outboxId);return
|
|
347
|
+
`).run(e.reasonCode,e.reasonCode,e.summary,e.summary,e.deadLetteredAt,e.deadLetteredAt,e.outboxId);return g({outboxId:e.outboxId,status:"dead_letter",changes:r.changes,replay:!1,deliveryCursor:t.delivery_cursor??void 0,deadLetteredAt:e.deadLetteredAt,reasonCode:e.reasonCode})})}catch(t){throw y(t,"sqlite-mutation-failed")}}retryOutboxEntries(e){this.assertCanMutate();const t=Math.max(1,Math.min(100,Math.floor(e.limit))),r=P(e.statuses?.length?e.statuses:["failed","dead_letter"]),s=e.reasonCode??"backoff-scheduled";I(s,"outbox.last_error_code"),I(e.nextAttemptAt,"outbox.next_attempt_at");try{return this.runInTransaction(()=>{const n=r.map(()=>"?").join(", "),o=this.db.prepare(`
|
|
320
348
|
SELECT outbox_id
|
|
321
349
|
FROM outbox
|
|
322
|
-
WHERE status IN (${
|
|
350
|
+
WHERE status IN (${n})
|
|
323
351
|
ORDER BY updated_at ASC, outbox_id ASC
|
|
324
352
|
LIMIT ?
|
|
325
|
-
`).all(...r,t).map(h=>h.outbox_id).filter(h=>typeof h=="string"&&h.length>0);if(o.length===0)return{retriedOutboxIds:[],changes:0,reasonCode:s,publicSafe:!0};const l=o.map(()=>"?").join(", "),
|
|
353
|
+
`).all(...r,t).map(h=>h.outbox_id).filter(h=>typeof h=="string"&&h.length>0);if(o.length===0)return{retriedOutboxIds:[],changes:0,reasonCode:s,publicSafe:!0};const l=o.map(()=>"?").join(", "),_=this.db.prepare(`
|
|
326
354
|
UPDATE outbox
|
|
327
355
|
SET status = 'pending',
|
|
328
356
|
retry_count = retry_count + 1,
|
|
@@ -336,7 +364,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
336
364
|
dead_lettered_at = NULL,
|
|
337
365
|
updated_at = ?
|
|
338
366
|
WHERE outbox_id IN (${l})
|
|
339
|
-
`).run(e.nextAttemptAt??e.nowIso,s,s,e.nowIso,...o);return{retriedOutboxIds:o,changes:
|
|
367
|
+
`).run(e.nextAttemptAt??e.nowIso,s,s,e.nowIso,...o);return{retriedOutboxIds:o,changes:_.changes,reasonCode:s,publicSafe:!0}})}catch(n){throw y(n,"sqlite-mutation-failed")}}upsertGoalCampaign(e){this.assertCanMutate(),I(e.title,"goal_campaigns.title"),I(e.publicSummary,"goal_campaigns.public_summary");const t=C(e.metadata);try{const r=this.db.prepare(`
|
|
340
368
|
INSERT INTO goal_campaigns (
|
|
341
369
|
campaign_id, job_id, status, title, public_summary, reason_code,
|
|
342
370
|
created_at, updated_at, operation_id, idempotency_key, metadata_json
|
|
@@ -350,7 +378,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
350
378
|
operation_id = excluded.operation_id,
|
|
351
379
|
idempotency_key = excluded.idempotency_key,
|
|
352
380
|
metadata_json = excluded.metadata_json
|
|
353
|
-
`).run(e.campaignId,e.jobId,e.status,e.title??null,e.publicSummary??null,e.reasonCode??null,e.createdAt,e.updatedAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw
|
|
381
|
+
`).run(e.campaignId,e.jobId,e.status,e.title??null,e.publicSummary??null,e.reasonCode??null,e.createdAt,e.updatedAt,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(r)}catch(r){throw y(r,"sqlite-mutation-failed")}}upsertGoalLedgerItem(e){this.assertCanMutate(),I(e.summary,"goal_ledger_items.summary");const t=C(e.metadata);try{this.ensureGoalCampaign(e.campaignId,e.jobId,e.createdAt,e.updatedAt);const r=this.db.prepare(`
|
|
354
382
|
INSERT INTO goal_ledger_items (
|
|
355
383
|
item_id, campaign_id, operation_id, idempotency_key, item_type, status,
|
|
356
384
|
summary, reason_code, created_at, updated_at, metadata_json
|
|
@@ -361,7 +389,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
361
389
|
reason_code = excluded.reason_code,
|
|
362
390
|
updated_at = excluded.updated_at,
|
|
363
391
|
metadata_json = excluded.metadata_json
|
|
364
|
-
`).run(e.itemId,e.campaignId,e.operationId??null,e.idempotencyKey??null,e.itemType,e.status,e.summary,e.reasonCode??null,e.createdAt,e.updatedAt,t);return this.toWriteResult(r)}catch(r){throw
|
|
392
|
+
`).run(e.itemId,e.campaignId,e.operationId??null,e.idempotencyKey??null,e.itemType,e.status,e.summary,e.reasonCode??null,e.createdAt,e.updatedAt,t);return this.toWriteResult(r)}catch(r){throw y(r,"sqlite-mutation-failed")}}upsertGoalVerifier(e){this.assertCanMutate(),I(e.summary,"goal_verifiers.summary");const t=C(e.metadata);try{const r=e.lastCheckedAt??this.now();this.ensureGoalCampaign(e.campaignId,e.jobId,r,r);const s=this.db.prepare(`
|
|
365
393
|
INSERT INTO goal_verifiers (
|
|
366
394
|
verifier_id, campaign_id, kind, status, summary, reason_code,
|
|
367
395
|
last_checked_at, operation_id, idempotency_key, metadata_json
|
|
@@ -372,7 +400,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
372
400
|
reason_code = excluded.reason_code,
|
|
373
401
|
last_checked_at = excluded.last_checked_at,
|
|
374
402
|
metadata_json = excluded.metadata_json
|
|
375
|
-
`).run(e.verifierId,e.campaignId,e.kind,e.status,e.summary??null,e.reasonCode??null,e.lastCheckedAt??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(s)}catch(r){throw
|
|
403
|
+
`).run(e.verifierId,e.campaignId,e.kind,e.status,e.summary??null,e.reasonCode??null,e.lastCheckedAt??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(s)}catch(r){throw y(r,"sqlite-mutation-failed")}}upsertGoalReviewGate(e){this.assertCanMutate(),I(e.summary,"goal_review_gates.summary");const t=C(e.metadata);try{const r=this.now();this.ensureGoalCampaign(e.campaignId,e.jobId,r,r);const s=this.db.prepare(`
|
|
376
404
|
INSERT INTO goal_review_gates (
|
|
377
405
|
gate_id, campaign_id, status, summary, required, reason_code,
|
|
378
406
|
operation_id, idempotency_key, metadata_json
|
|
@@ -383,7 +411,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
383
411
|
required = excluded.required,
|
|
384
412
|
reason_code = excluded.reason_code,
|
|
385
413
|
metadata_json = excluded.metadata_json
|
|
386
|
-
`).run(e.gateId,e.campaignId,e.status,e.summary??null,e.required?1:0,e.reasonCode??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(s)}catch(r){throw
|
|
414
|
+
`).run(e.gateId,e.campaignId,e.status,e.summary??null,e.required?1:0,e.reasonCode??null,e.operationId??null,e.idempotencyKey??null,t);return this.toWriteResult(s)}catch(r){throw y(r,"sqlite-mutation-failed")}}recordOperationAudit(e){return this.appendReceipt(e)}hasOperationRef(e,t){this.assertCanMutate();const r=["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"],s=r.map(o=>`SELECT 1 AS found FROM ${o} WHERE operation_id = ?${t?" OR idempotency_key = ?":""}`),n=r.flatMap(()=>t?[e,t]:[e]);return!!this.db.prepare(`${s.join(" UNION ALL ")} LIMIT 1`).get(...n)}jobExists(e){return!!this.db.prepare("SELECT 1 AS found FROM jobs WHERE job_id = ? LIMIT 1").get(e)}getHeadlessExecutionAttempt(e){return this.db.prepare(`
|
|
387
415
|
SELECT attempt_id, execution_id, job_id, directive_hash, directive_kind,
|
|
388
416
|
command_class, target_kind, target_ref, story_id, epic_id,
|
|
389
417
|
runtime_id, model_id, runtime_source, status, reason_code,
|
|
@@ -403,7 +431,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
403
431
|
FROM outbox
|
|
404
432
|
WHERE outbox_id = ?
|
|
405
433
|
LIMIT 1
|
|
406
|
-
`).get(e);if(!(!t||!
|
|
434
|
+
`).get(e);if(!(!t||!E(t)))return t}selectReceiptRetentionCandidates(e){return this.db.prepare(`
|
|
407
435
|
WITH sized AS (
|
|
408
436
|
SELECT receipt_id, job_id, status, reason_code, created_at,
|
|
409
437
|
length(receipt_id) + length(job_id) + length(status) + length(created_at)
|
|
@@ -441,7 +469,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
441
469
|
WHERE created_at < ? OR retain_rank > ? OR cumulative_bytes > ?
|
|
442
470
|
ORDER BY created_at ASC, event_id ASC
|
|
443
471
|
LIMIT ?
|
|
444
|
-
`).all(
|
|
472
|
+
`).all(N,e.cutoff,e.maxItems,e.maxBytes,e.limit).flatMap(r=>typeof r.event_id!="string"||typeof r.job_id!="string"?[]:[{kind:"output",id:r.event_id,jobId:r.job_id,status:typeof r.type=="string"?r.type:N,reasonCode:typeof r.reason_code=="string"?r.reason_code:"continuity-ok",createdAt:typeof r.created_at=="string"?r.created_at:e.cutoff,approxBytes:typeof r.approx_bytes=="number"&&r.approx_bytes>=0?Math.floor(r.approx_bytes):0}])}deleteRetentionCandidates(e,t,r){if(r.length===0)return;const s=r.map(()=>"?").join(", ");this.db.prepare(`DELETE FROM ${e} WHERE ${t} IN (${s})`).run(...r)}preserveReceiptDerivedIteration(e,t){const r=this.db.prepare(`
|
|
445
473
|
SELECT COUNT(*) AS iteration
|
|
446
474
|
FROM job_receipts
|
|
447
475
|
WHERE job_id = ?
|
|
@@ -462,7 +490,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
462
490
|
+ COALESCE(length(reason_code), 0) + COALESCE(length(metadata_json), 0)), 0) AS bytes
|
|
463
491
|
FROM job_events
|
|
464
492
|
WHERE job_id = ? AND type = ?
|
|
465
|
-
`).get(e,
|
|
493
|
+
`).get(e,N);return{receipts:typeof t?.count=="number"?t.count:0,outputs:typeof r?.count=="number"?r.count:0,bytes:(typeof t?.bytes=="number"?t.bytes:0)+(typeof r?.bytes=="number"?r.bytes:0)}}pruneReceiptCompactionSummaries(e,t){this.db.prepare(`
|
|
466
494
|
DELETE FROM job_events
|
|
467
495
|
WHERE event_id IN (
|
|
468
496
|
SELECT event_id
|
|
@@ -471,20 +499,20 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
471
499
|
ORDER BY created_at DESC, event_id DESC
|
|
472
500
|
LIMIT -1 OFFSET ?
|
|
473
501
|
)
|
|
474
|
-
`).run(e,F,t)}runInTransaction(e){this.assertCanMutate();const t=this.db.transaction(e);try{return typeof t.immediate=="function"?t.immediate():t()}catch(r){throw
|
|
502
|
+
`).run(e,F,t)}runInTransaction(e){this.assertCanMutate();const t=this.db.transaction(e);try{return typeof t.immediate=="function"?t.immediate():t()}catch(r){throw y(r,"sqlite-mutation-failed")}}collectSnapshotRows(e){const t=(b,...x)=>{const A=this.db.prepare(b).get(...x);return E(A)&&typeof A.count=="number"?A.count:0},r=this.db.prepare(`
|
|
475
503
|
SELECT status, COUNT(*) AS count FROM outbox GROUP BY status
|
|
476
|
-
`).all(),s={};for(const
|
|
504
|
+
`).all(),s={};for(const b of r)typeof b.status=="string"&&typeof b.count=="number"&&(s[b.status]=b.count);const n=this.db.prepare(`
|
|
477
505
|
SELECT value_json
|
|
478
506
|
FROM runner_config
|
|
479
507
|
WHERE key = 'headless_queue_policy'
|
|
480
508
|
LIMIT 1
|
|
481
|
-
`).get();let
|
|
509
|
+
`).get();let d=qe;if(E(n)&&typeof n.value_json=="string")try{const b=JSON.parse(n.value_json);E(b)&&typeof b.maxItems=="number"&&(d=$({maxItems:b.maxItems}))}catch{}const o=t("SELECT COUNT(*) AS count FROM headless_execution_attempts WHERE status = 'queued' AND dead_lettered_at IS NULL"),l=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"),f=o+l+_,m=this.db.prepare(`
|
|
482
510
|
SELECT MIN(next_retry_at) AS next_retry_at
|
|
483
511
|
FROM headless_execution_attempts
|
|
484
512
|
WHERE status = 'backoff'
|
|
485
513
|
AND dead_lettered_at IS NULL
|
|
486
514
|
AND next_retry_at IS NOT NULL
|
|
487
|
-
`).get(),u=
|
|
515
|
+
`).get(),u=E(m)&&typeof m.next_retry_at=="string"?m.next_retry_at:void 0;return{schemaVersion:this.getSchemaVersion(),jobs:this.db.prepare(`
|
|
488
516
|
SELECT job_id, kind, status, summary, reason_code, created_at, updated_at,
|
|
489
517
|
next_run_at, metadata_json,
|
|
490
518
|
(SELECT COUNT(*)
|
|
@@ -568,19 +596,19 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
568
596
|
FROM headless_execution_attempts
|
|
569
597
|
ORDER BY enqueued_at DESC, attempt_id ASC
|
|
570
598
|
LIMIT ?
|
|
571
|
-
`).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 = ?",
|
|
599
|
+
`).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 = ?",N),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:l,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:f,queued:o,running:_,retrying:l,deadLetter:h,capacity:d.maxItems,available:Math.max(0,d.maxItems-f),backpressure:f>=d.maxItems,generatedAt:e.nowIso,...u?{nextRetryAt:u}:{},...f>=d.maxItems?{reasonCode:v.CAP_REACHED}:{},publicSafe:!0}}}listProcessingOutputSummaries(e={}){const t=ye(e.limit),r=pe(e),s=`
|
|
572
600
|
SELECT event_id, job_id, operation_id, summary, reason_code, created_at, metadata_json
|
|
573
601
|
FROM job_events
|
|
574
602
|
WHERE type = ?${r.sql}
|
|
575
603
|
ORDER BY created_at DESC, event_id DESC
|
|
576
604
|
LIMIT ?
|
|
577
|
-
`;return this.db.prepare(`SELECT * FROM (${s}) ORDER BY created_at ASC, event_id ASC`).all(
|
|
605
|
+
`;return this.db.prepare(`SELECT * FROM (${s}) ORDER BY created_at ASC, event_id ASC`).all(N,...r.params,t).map(be)}pollProcessingOutputSummaries(e={}){const t=ye(e.limit),r=mt(e.cursor),s=pe(e),n=r?" AND (created_at > ? OR (created_at = ? AND event_id > ?))":"",d=`
|
|
578
606
|
SELECT event_id, job_id, operation_id, summary, reason_code, created_at, metadata_json
|
|
579
607
|
FROM job_events
|
|
580
|
-
WHERE type = ?${s.sql}${
|
|
608
|
+
WHERE type = ?${s.sql}${n}
|
|
581
609
|
ORDER BY created_at ASC, event_id ASC
|
|
582
610
|
LIMIT ?
|
|
583
|
-
`,o=[
|
|
611
|
+
`,o=[N];o.push(...s.params),r&&o.push(r.createdAt,r.createdAt,r.eventId),o.push(t+1);const l=this.db.prepare(d).all(...o),_=l.slice(0,t).map(be),h=_[_.length-1];return{summaries:_,...h?{nextCursor:h.cursor}:e.cursor?{nextCursor:e.cursor}:{},hasMore:l.length>t,publicSafe:!0}}listDueJobs(e){const t=Math.max(1,Math.min(50,Math.floor(e.limit)));return this.db.prepare(`
|
|
584
612
|
SELECT j.job_id, j.kind, j.status, j.summary, j.reason_code, j.created_at,
|
|
585
613
|
j.updated_at, j.next_run_at, j.metadata_json,
|
|
586
614
|
(SELECT COUNT(*)
|
|
@@ -598,19 +626,19 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
598
626
|
AND j.status NOT IN ('waiting_external', 'waiting_human', 'paused', 'blocked', 'completed', 'aborted', 'cancelled')
|
|
599
627
|
ORDER BY j.next_run_at ASC, j.job_id ASC
|
|
600
628
|
LIMIT ?
|
|
601
|
-
`).all(e.nowIso,t)}recoverStaleLeases(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new i("sqlite-public-safety-rejected","Continuity SQLite stale lease recovery received an invalid timestamp.");const r=Math.max(0,Math.floor(e.staleAfterMs)),s=Math.max(1,Math.min(100,Math.floor(e.limit))),
|
|
629
|
+
`).all(e.nowIso,t)}recoverStaleLeases(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new i("sqlite-public-safety-rejected","Continuity SQLite stale lease recovery received an invalid timestamp.");const r=Math.max(0,Math.floor(e.staleAfterMs)),s=Math.max(1,Math.min(100,Math.floor(e.limit))),n=new Date(t-r).toISOString();try{return this.runInTransaction(()=>{const o=this.db.prepare(`
|
|
602
630
|
SELECT lease_id
|
|
603
631
|
FROM job_leases
|
|
604
632
|
WHERE released_at IS NULL
|
|
605
633
|
AND expires_at <= ?
|
|
606
634
|
ORDER BY expires_at ASC, lease_id ASC
|
|
607
635
|
LIMIT ?
|
|
608
|
-
`).all(
|
|
636
|
+
`).all(n,s).map(h=>h.lease_id).filter(h=>typeof h=="string"&&h.length>0);if(o.length===0)return{recoveredLeaseIds:[],safeExpiredAtOrBefore:n,changes:0};const l=o.map(()=>"?").join(", "),_=this.db.prepare(`
|
|
609
637
|
UPDATE job_leases
|
|
610
638
|
SET status = 'expired', released_at = ?
|
|
611
639
|
WHERE released_at IS NULL
|
|
612
640
|
AND lease_id IN (${l})
|
|
613
|
-
`).run(e.nowIso,...o);return{recoveredLeaseIds:o,safeExpiredAtOrBefore:
|
|
641
|
+
`).run(e.nowIso,...o);return{recoveredLeaseIds:o,safeExpiredAtOrBefore:n,changes:_.changes}})}catch(d){throw y(d,"sqlite-mutation-failed")}}recoverStaleHeadlessExecutionAttempts(e){this.assertCanMutate();const t=Date.parse(e.nowIso);if(!Number.isFinite(t))throw new i("sqlite-public-safety-rejected","Continuity SQLite headless stale recovery received an invalid timestamp.");const r=Math.max(0,Math.floor(e.staleAfterMs)),s=Math.max(1,Math.min(100,Math.floor(e.limit))),n=new Date(t-r).toISOString();try{return this.runInTransaction(()=>{const d=this.db.prepare(`
|
|
614
642
|
SELECT attempt_id, retry_count, max_attempts, attempt_count
|
|
615
643
|
FROM headless_execution_attempts
|
|
616
644
|
WHERE status = 'running'
|
|
@@ -618,7 +646,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
618
646
|
AND lease_expires_at <= ?
|
|
619
647
|
ORDER BY lease_expires_at ASC, attempt_id ASC
|
|
620
648
|
LIMIT ?
|
|
621
|
-
`).all(
|
|
649
|
+
`).all(n,s),o=[],l=[],_=$(e.policy);for(const m of d){if(typeof m.attempt_id!="string"||m.attempt_id.length===0)continue;const u=typeof m.retry_count=="number"?m.retry_count:0,b=typeof m.max_attempts=="number"?m.max_attempts:1,x=typeof m.attempt_count=="number"?m.attempt_count:0;Math.max(x,u+1)>=b?l.push(m.attempt_id):o.push({attemptId:m.attempt_id,nextRetryAt:Pe(e.nowIso,u+1,_)})}let h=0;for(const m of o)h+=this.db.prepare(`
|
|
622
650
|
UPDATE headless_execution_attempts
|
|
623
651
|
SET status = 'backoff',
|
|
624
652
|
retry_count = retry_count + 1,
|
|
@@ -629,7 +657,7 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
629
657
|
WHERE attempt_id = ?
|
|
630
658
|
AND status = 'running'
|
|
631
659
|
AND lease_released_at IS NULL
|
|
632
|
-
`).run(v.LEASE_TIMEOUT_RETRY,e.nowIso,
|
|
660
|
+
`).run(v.LEASE_TIMEOUT_RETRY,e.nowIso,m.nextRetryAt,m.nextRetryAt,m.attemptId).changes;if(l.length>0){const m=l.map(()=>"?").join(", ");h+=this.db.prepare(`
|
|
633
661
|
UPDATE headless_execution_attempts
|
|
634
662
|
SET status = 'failed',
|
|
635
663
|
retry_count = retry_count + 1,
|
|
@@ -639,10 +667,10 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
639
667
|
dead_lettered_at = ?,
|
|
640
668
|
dead_letter_reason_code = ?,
|
|
641
669
|
next_retry_at = NULL
|
|
642
|
-
WHERE attempt_id IN (${
|
|
670
|
+
WHERE attempt_id IN (${m})
|
|
643
671
|
AND status = 'running'
|
|
644
672
|
AND lease_released_at IS NULL
|
|
645
|
-
`).run(v.ATTEMPTS_EXHAUSTED,e.nowIso,e.nowIso,e.nowIso,v.ATTEMPTS_EXHAUSTED,...l).changes}const f=o.map(
|
|
673
|
+
`).run(v.ATTEMPTS_EXHAUSTED,e.nowIso,e.nowIso,e.nowIso,v.ATTEMPTS_EXHAUSTED,...l).changes}const f=o.map(m=>m.attemptId);return{recoveredAttemptIds:[...f,...l],failedAttemptIds:l,retryingAttemptIds:f,deadLetteredAttemptIds:l,safeExpiredAtOrBefore:n,changes:h,publicSafe:!0}})}catch(d){throw y(d,"sqlite-mutation-failed")}}ensureGoalCampaign(e,t,r,s){this.db.prepare(`
|
|
646
674
|
INSERT OR IGNORE INTO goal_campaigns (
|
|
647
675
|
campaign_id, job_id, status, public_summary, created_at, updated_at
|
|
648
676
|
) VALUES (?, ?, 'active', 'Public goal campaign summary unavailable', ?, ?)
|
|
@@ -653,4 +681,4 @@ import{Buffer as J}from"node:buffer";import{createHash as D}from"node:crypto";im
|
|
|
653
681
|
checksum TEXT NOT NULL,
|
|
654
682
|
applied_at TEXT NOT NULL
|
|
655
683
|
);
|
|
656
|
-
`)}applyMigrations(){this.db.transaction(()=>{for(const t of Ze){const r=dt(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 i("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 i("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{
|
|
684
|
+
`)}applyMigrations(){this.db.transaction(()=>{for(const t of Ze){const r=dt(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 i("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 i("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{N as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_EVENT_TYPE,Ke as CONTINUITY_PROCESSING_OUTPUT_SUMMARY_MAX_CHARS,Qe as CONTINUITY_PUBLIC_STAGES,$e as CONTINUITY_SQLITE_FILENAME,ne as CONTINUITY_SQLITE_RELATIVE_DIR,Ht as CONTINUITY_SQLITE_SCHEMA_VERSION,ce as CONTINUITY_STAGE_HISTORY_MAX,At as ContinuitySqliteStore,i as ContinuitySqliteStoreError,de as DEFAULT_CONTINUITY_PROCESSING_SUMMARY_LIMIT,Ye as DEFAULT_CONTINUITY_SQLITE_BUSY_TIMEOUT_MS,Ve as MAX_CONTINUITY_PROCESSING_SUMMARY_LIMIT,ie as SQLITE_ADAPTER_INSTALL_GUIDANCE,Ee as continuitySqliteStorePath,Ft as inspectEpicOperationalSqliteBinding,le as isContinuityPublicStage,gt as loadBetterSqlite3Adapter,Xe as normalizeContinuityStageIteration,St as openContinuitySqliteReadOnly,Wt as openContinuitySqliteStore,ze as sanitizeContinuityStageHistory,ue as sanitizeContinuityStageTimestamp};
|