@tnunamak/dalan 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +176 -0
- package/CONTRIBUTING.md +26 -0
- package/LICENSE +204 -0
- package/PROTOCOL.md +351 -0
- package/README.md +215 -2
- package/SECURITY.md +30 -0
- package/bin/dalan.mjs +43 -0
- package/bin/dot-acp-agent.mjs +377 -0
- package/bin/dot-alert.mjs +9 -0
- package/bin/dot-deadman.mjs +82 -0
- package/bin/dot-heartbeat.mjs +29 -0
- package/bin/dot-pr-reviewer.mjs +32 -0
- package/bin/dot-worker.mjs +764 -0
- package/docs/chatgpt-worker-onboarding.md +112 -0
- package/docs/claude-worker-onboarding.md +113 -0
- package/docs/codex-to-muse.md +175 -0
- package/docs/connect-chatgpt.md +83 -0
- package/docs/connection-longevity.md +43 -0
- package/docs/dalan-upgrade.md +246 -0
- package/docs/deadman.md +61 -0
- package/docs/dot-pr-reviewer.config.example.json +9 -0
- package/docs/durability-audit.md +27 -0
- package/docs/keycloak-client-chatgpt-dot-bridge.json +59 -0
- package/docs/keycloak-oauth-setup.md +30 -0
- package/docs/local-agent-mcp.md +41 -0
- package/docs/manual-setup.md +135 -0
- package/docs/mirror-fetch.md +97 -0
- package/docs/operations.md +799 -0
- package/docs/operator-duties.md +68 -0
- package/docs/owner-integrator.md +27 -0
- package/docs/portable-auth-profile.md +107 -0
- package/docs/pr-head-reviewer.md +70 -0
- package/docs/pr-preflight.md +28 -0
- package/docs/pull-queue.md +131 -0
- package/docs/pull-workers.md +94 -0
- package/docs/redaction.md +27 -0
- package/docs/service-setup.md +219 -0
- package/docs/setup-reference.md +80 -0
- package/docs/t3-connector-icon.png +0 -0
- package/docs/t3-integration.md +51 -0
- package/docs/t3-result-retry-delivery.md +41 -0
- package/docs/t3-reverse-control.md +107 -0
- package/docs/usage.md +443 -0
- package/docs/worker-clients.md +290 -0
- package/integrations/t3/acp-kit/src/capability.mjs +25 -0
- package/integrations/t3/acp-kit/src/errors.mjs +13 -0
- package/integrations/t3/acp-kit/src/index.mjs +5 -0
- package/integrations/t3/acp-kit/src/lock.mjs +155 -0
- package/integrations/t3/acp-kit/src/session-store.mjs +36 -0
- package/integrations/t3/acp-kit/src/t3-envelope.mjs +62 -0
- package/package.json +67 -4
- package/packages/job-core/README.md +18 -0
- package/packages/job-core/index.mjs +2 -0
- package/packages/job-core/package.json +8 -0
- package/packages/job-core/protocol/canonical.mjs +11 -0
- package/packages/job-core/protocol/v0/command.schema.json +1154 -0
- package/packages/job-core/protocol/v0/event.schema.json +77 -0
- package/packages/job-core/protocol/v0/reply.schema.json +59 -0
- package/packages/job-core/transitions.mjs +25 -0
- package/scripts/daily-selfcheck.mjs +135 -0
- package/scripts/dalan-try-selfcheck.mjs +29 -0
- package/scripts/lib/expose-tailscale.mjs +408 -0
- package/scripts/live-trial/common.mjs +272 -0
- package/scripts/monitor-targets.mjs +44 -0
- package/scripts/upgrade-drain.mjs +39 -0
- package/scripts/worker-bridge-setup.mjs +925 -0
- package/src/ack-ledger.mjs +37 -0
- package/src/acp-bridge.mjs +418 -0
- package/src/acp-context.mjs +138 -0
- package/src/admin-socket.mjs +14 -0
- package/src/alerts.mjs +147 -0
- package/src/artifact-journal.mjs +75 -0
- package/src/as-files.mjs +347 -0
- package/src/as-store.mjs +456 -0
- package/src/as.mjs +538 -0
- package/src/auth.mjs +166 -0
- package/src/builtin-http.mjs +22 -0
- package/src/check-coverage.mjs +38 -0
- package/src/check-lint.mjs +88 -0
- package/src/check-readiness.mjs +112 -0
- package/src/check-response.mjs +19 -0
- package/src/child-exit.mjs +18 -0
- package/src/child-registry.mjs +94 -0
- package/src/claim-command-ledger.mjs +51 -0
- package/src/cli-help.mjs +186 -0
- package/src/cli-name.mjs +16 -0
- package/src/connect-cli.mjs +126 -0
- package/src/consumers.mjs +61 -0
- package/src/deadman.mjs +329 -0
- package/src/delivery.mjs +19 -0
- package/src/demo-worker.mjs +150 -0
- package/src/destinations/index.mjs +23 -0
- package/src/destinations/none.mjs +15 -0
- package/src/destinations/t3.mjs +109 -0
- package/src/diagnostic.mjs +78 -0
- package/src/docs-url.mjs +9 -0
- package/src/drain-runner.mjs +9 -0
- package/src/drained-owner.mjs +26 -0
- package/src/drained-slot.mjs +70 -0
- package/src/drained.mjs +40 -0
- package/src/durable-waiters.mjs +236 -0
- package/src/env.mjs +19 -0
- package/src/execution.mjs +112 -0
- package/src/failure-type.mjs +28 -0
- package/src/get-summary.mjs +32 -0
- package/src/git-env.mjs +15 -0
- package/src/host-budget-receipts.mjs +154 -0
- package/src/host-budget-seccomp.py +33 -0
- package/src/host-budget-service.mjs +54 -0
- package/src/host-budget-stop.mjs +26 -0
- package/src/host-budget-storage.py +259 -0
- package/src/host-budget.mjs +149 -0
- package/src/host-cgroup.mjs +23 -0
- package/src/host-check-allowlist.mjs +42 -0
- package/src/host-execution-policy.mjs +38 -0
- package/src/host-health.mjs +34 -0
- package/src/host-stop-reverify.mjs +44 -0
- package/src/inbox.mjs +55 -0
- package/src/integrator.mjs +322 -0
- package/src/job-retention.mjs +69 -0
- package/src/legacy-names.mjs +8 -0
- package/src/lifecycle.mjs +291 -0
- package/src/limits.mjs +31 -0
- package/src/loopback.mjs +9 -0
- package/src/mcp-outcome.mjs +79 -0
- package/src/mcp-sse.mjs +62 -0
- package/src/mcp-stdio.mjs +191 -0
- package/src/mirror-fetch-lock.py +164 -0
- package/src/mirror-fetch.mjs +174 -0
- package/src/notify-ledger.mjs +82 -0
- package/src/objectives.mjs +129 -0
- package/src/owner-report-artifact.mjs +66 -0
- package/src/patch-apply.mjs +84 -0
- package/src/path-syntax.mjs +16 -0
- package/src/paths.mjs +67 -0
- package/src/pr-head-reviewer.mjs +596 -0
- package/src/pr-preflight.mjs +51 -0
- package/src/prepared-node-modules.mjs +129 -0
- package/src/process-inspection.mjs +36 -0
- package/src/projects.mjs +480 -0
- package/src/protocol-artifact-commands.mjs +52 -0
- package/src/protocol-delivery-driver.mjs +167 -0
- package/src/protocol-finish.mjs +100 -0
- package/src/protocol-owner-command.mjs +35 -0
- package/src/protocol-owner-mutations.mjs +22 -0
- package/src/protocol-owner-waiters.mjs +67 -0
- package/src/protocol-retention.mjs +52 -0
- package/src/protocol-services.mjs +61 -0
- package/src/protocol-stop-observer.mjs +131 -0
- package/src/publish-plan.mjs +245 -0
- package/src/pull-queue.mjs +159 -0
- package/src/redaction.mjs +763 -0
- package/src/rejections.mjs +18 -0
- package/src/request-log.mjs +102 -0
- package/src/restore-check.mjs +90 -0
- package/src/result-binding.mjs +65 -0
- package/src/route-setting.mjs +24 -0
- package/src/runtime-check.mjs +13 -0
- package/src/sandbox-supervisor.mjs +105 -0
- package/src/schema-subset.mjs +186 -0
- package/src/scopes.mjs +15 -0
- package/src/server.mjs +1468 -0
- package/src/service-migrate-workers.mjs +113 -0
- package/src/service.mjs +388 -0
- package/src/setup.mjs +63 -0
- package/src/shutdown-signal.mjs +12 -0
- package/src/signal-sandbox-processes.py +56 -0
- package/src/signal.mjs +119 -0
- package/src/status-evidence.mjs +47 -0
- package/src/status-summary.mjs +54 -0
- package/src/store.mjs +3069 -0
- package/src/submission-policy.mjs +623 -0
- package/src/subscription-storage.mjs +64 -0
- package/src/t3-audit.mjs +120 -0
- package/src/t3-control.mjs +102 -0
- package/src/t3-transport.mjs +158 -0
- package/src/t3.mjs +209 -0
- package/src/terminal-safe.mjs +19 -0
- package/src/tool-registry.mjs +453 -0
- package/src/try-command.mjs +11 -0
- package/src/try-exposure.mjs +908 -0
- package/src/try-hosted-clients.mjs +46 -0
- package/src/try-hosted.mjs +444 -0
- package/src/try-selfcheck.mjs +168 -0
- package/src/try.mjs +635 -0
- package/src/webhooks.mjs +86 -0
- package/src/work-order.mjs +265 -0
- package/src/worker-instructions.mjs +26 -0
- package/src/worker-prompt.mjs +4 -0
- package/src/workers.mjs +632 -0
- package/src/workspace.mjs +1065 -0
- package/systemd/dot-bridge-heartbeat.service +18 -0
- package/systemd/dot-bridge-heartbeat.timer +10 -0
- package/systemd/dot-bridge-selfcheck.service +12 -0
- package/systemd/dot-bridge-selfcheck.timer +11 -0
- package/systemd/dot-bridge.service +17 -0
- package/systemd/dot-deadman.service +30 -0
- package/systemd/dot-pr-reviewer.service +11 -0
- package/systemd/dot-pr-reviewer.timer +10 -0
package/src/store.mjs
ADDED
|
@@ -0,0 +1,3069 @@
|
|
|
1
|
+
import {PullQueue,migratePullQueue,PULL_PAGE_PREFIX} from './pull-queue.mjs';
|
|
2
|
+
import { defaultPath } from './paths.mjs';
|
|
3
|
+
import { readEnv } from './env.mjs';
|
|
4
|
+
import { validateOwnerNote } from './submission-policy.mjs';
|
|
5
|
+
import { redactOutput } from './redaction.mjs';
|
|
6
|
+
import { statusEvidence } from './status-evidence.mjs';
|
|
7
|
+
import { assertPreflight } from './pr-preflight.mjs';
|
|
8
|
+
import { lifecycleSchema, backfillLifecycle, progressType } from './lifecycle.mjs';
|
|
9
|
+
import { objectiveSources, metaFields, normalizeMeta, toStoredSource, fromStoredSource, canonicalMetaValue, canonicalKindSql, canonicalKindLabel, storedObjectiveKey, storedTaskKind, verifyObjective } from './objectives.mjs';
|
|
10
|
+
import { legacyFixLoopName } from './legacy-names.mjs';
|
|
11
|
+
import { LEGACY_PROFILE, canSee, resolveWorker, destinationDisclosure, destinationDifferences, destinationError, connectionsDigest } from './workers.mjs';
|
|
12
|
+
import { TRUST } from './execution.mjs';
|
|
13
|
+
import { inferWorkerReport, observeTransition } from './failure-type.mjs';
|
|
14
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
15
|
+
import { acquireSubscriptionStorage, SubscriptionCodec } from './subscription-storage.mjs';
|
|
16
|
+
import { randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import {migrateClaimCommands,createClaimCommands} from './claim-command-ledger.mjs';
|
|
19
|
+
import {migrateArtifactJournal} from './artifact-journal.mjs';
|
|
20
|
+
import {migrateResultBindings} from './result-binding.mjs';
|
|
21
|
+
import {migrateJobRetention} from './job-retention.mjs';
|
|
22
|
+
import {migrateProtocolOwnerWaiters,materializeProtocolWaiters} from './protocol-owner-waiters.mjs';
|
|
23
|
+
import {finishProtocol} from './protocol-finish.mjs';
|
|
24
|
+
import {answerProtocolQuestion,cancelProtocolJob} from './protocol-owner-mutations.mjs';
|
|
25
|
+
import {defineProtocolRetentionInTransaction,assertProtocolAvailable as checkProtocolAvailable} from './protocol-retention.mjs';
|
|
26
|
+
import {migrateProtocolDelivery} from './protocol-delivery-driver.mjs';
|
|
27
|
+
import {migrateProtocolStopObserver} from './protocol-stop-observer.mjs';
|
|
28
|
+
|
|
29
|
+
// A reserved HTTP response is a live effect channel. Persist its owner so a
|
|
30
|
+
// second process cannot reset a reservation whose callback can still respond.
|
|
31
|
+
function waiterProcessIdentity(pid=process.pid) {
|
|
32
|
+
const identity={pid};
|
|
33
|
+
if(process.platform==='linux') try {
|
|
34
|
+
identity.boot=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim();
|
|
35
|
+
identity.namespace=fs.readlinkSync(`/proc/${pid}/ns/pid`);
|
|
36
|
+
const stat=fs.readFileSync(`/proc/${pid}/stat`,'utf8');
|
|
37
|
+
identity.start=stat.slice(stat.lastIndexOf(')')+2).split(' ')[19];
|
|
38
|
+
} catch {}
|
|
39
|
+
return identity;
|
|
40
|
+
}
|
|
41
|
+
function waiterOwnerGone(attemptId) {
|
|
42
|
+
if(typeof attemptId!=='string'||!attemptId.startsWith('wait:')) return false;
|
|
43
|
+
let owner;try{owner=JSON.parse(attemptId.slice(5));}catch{return false;}
|
|
44
|
+
if(!Number.isSafeInteger(owner.pid)||owner.pid<1) return false;
|
|
45
|
+
const local=waiterProcessIdentity();
|
|
46
|
+
if(owner.boot&&local.boot&&owner.boot!==local.boot) return true;
|
|
47
|
+
if(process.platform==='linux'&&(!owner.namespace||owner.namespace!==local.namespace)) return false;
|
|
48
|
+
try{process.kill(owner.pid,0);}catch(error){return error.code==='ESRCH';}
|
|
49
|
+
const current=waiterProcessIdentity(owner.pid);
|
|
50
|
+
return !!(owner.boot&&owner.start&¤t.boot&¤t.start&&(owner.boot!==current.boot||owner.start!==current.start));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const SUPPORTED_SCHEMA_VERSION = 66;
|
|
54
|
+
const monotonicMs=()=>Number(process.hrtime.bigint())/1e6;
|
|
55
|
+
function systemBootId() {
|
|
56
|
+
if(process.platform!=='linux') return null;
|
|
57
|
+
try { const id=fs.readFileSync('/proc/sys/kernel/random/boot_id','utf8').trim(); return id||null; }
|
|
58
|
+
catch { return null; }
|
|
59
|
+
}
|
|
60
|
+
const protocolError=code=>{throw Object.assign(new Error(code),{code});};
|
|
61
|
+
const protocolNat=value=>Number.isSafeInteger(value)&&value>=0;
|
|
62
|
+
export function validateProtocol(value) {
|
|
63
|
+
if(!value||typeof value!=='object'||Array.isArray(value)||
|
|
64
|
+
Object.keys(value).sort().join(',')!=='destination,policy,profile,retain_until_ms,scope,source'||
|
|
65
|
+
value.profile!=='job-v0'||!['source','scope','policy','destination'].every(k=>typeof value[k]==='string'&&value[k].trim().length>0)||
|
|
66
|
+
!protocolNat(value.retain_until_ms))protocolError('invalid_protocol');
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const questionError=(code,message)=>Object.assign(new Error(`${code}: ${message}`),{code});
|
|
71
|
+
function validateQuestion(questionId,text) {
|
|
72
|
+
if(typeof questionId!=='string'||!/^[A-Za-z0-9_.:-]{1,128}$/.test(questionId)) throw new Error('invalid question_id');
|
|
73
|
+
if(arguments.length>1&&(typeof text!=='string'||!text.trim()||Buffer.byteLength(text)>4096)) throw new Error('question text must be 1-4096 UTF-8 bytes');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function unsupportedSchemaVersion(found) {
|
|
77
|
+
return new Error(`database schema version ${found} is newer than supported version ${SUPPORTED_SCHEMA_VERSION}; use matching or newer Dalan code, or restore a consistent compatible backup. Do not reset user_version.`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Owner decisions on a finished result, in the words the CLI takes. 'stale' is only ever written by the sweep.
|
|
81
|
+
export const decisionTypes=['accepted','applied','useful_no_change','useful_negative','not_useful','stale'];
|
|
82
|
+
export const MAX_INTEGRATION_PATCH_BYTES=262144;
|
|
83
|
+
import os from 'node:os';
|
|
84
|
+
import path from 'node:path';
|
|
85
|
+
import { fileURLToPath } from 'node:url';
|
|
86
|
+
|
|
87
|
+
function canonical(value) {
|
|
88
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
89
|
+
if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])]));
|
|
90
|
+
return value;
|
|
91
|
+
}
|
|
92
|
+
// Only successful live claim/progress receipts may use this guidance. request_action is about this
|
|
93
|
+
// request; next_action stays the queued-work hint from nextQueued.
|
|
94
|
+
export function nonterminalOutcome(id,receipt) {
|
|
95
|
+
const next=receipt.blocker_forwarded
|
|
96
|
+
? `Request ${id} remains open. Resolve the blocker within scope or call finish with outcome blocked; progress is not finish.`
|
|
97
|
+
: `Keep working on request ${id}. Send progress about every minute. Call finish when done; progress is not finish.`;
|
|
98
|
+
return {...receipt,terminal:false,request_action:next};
|
|
99
|
+
}
|
|
100
|
+
const stamp = () => new Date().toISOString();
|
|
101
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
102
|
+
function validateSubmitKey(key) {
|
|
103
|
+
if(key!==null&&(typeof key!=='string'||key.length<1||key.length>128)) throw new Error('invalid command_key: use a nonempty string of at most 128 characters');
|
|
104
|
+
}
|
|
105
|
+
// Admission controls (queue caps, preflights) may change; the accepted job's intent cannot.
|
|
106
|
+
// Intent digests are persisted, so they hash the stored spelling of the source, objective key and task kind: a retry hashes the same before and after the rename.
|
|
107
|
+
const storedMeta=(meta,legacy)=>({...meta,objective_key:storedObjectiveKey(meta.objective_key,legacy),task_kind:storedTaskKind(meta.task_kind,legacy),source:toStoredSource(meta.source,legacy)});
|
|
108
|
+
function submitIntentDigest(identity,delivery,environmentId,review,priority,meta,targetWorker,execution,requiredCapabilities,destinationRevision=null,legacyFixNames=true) {
|
|
109
|
+
return hash(JSON.stringify(canonical({payload:identity,delivery,environmentId:environmentId??'',review:!!review,priority,meta:storedMeta(normalizeMeta(meta),legacyFixNames),targetWorker,execution,requiredCapabilities,...(destinationRevision===null?{}:{destination_revision:destinationRevision})})));
|
|
110
|
+
}
|
|
111
|
+
const defaultRedeliveryLimits={intervalMs:600000,maxCount:3,silenceMs:1200000,leaseMs:3600000,laneCapacity:6,rewakeMs:90000,rewakeWindowMs:7200000,rewakeStaleMs:1200000,breakSilenceMs:1200000,breakProbeMs:1800000,maxClaimsPerHour:90,maxToolCallsPerHour:1000,maxToolCallsPer24h:10000,maxResponseBytesPerHour:8000000,maxResponseBytesPer24h:100000000};
|
|
112
|
+
const HOUR=3600000, iso=ms=>new Date(ms).toISOString();
|
|
113
|
+
export const QUEUE_WINDOW=Object.freeze({minSamples:5,factor:3,minMs:15*60000,maxMs:12*HOUR});
|
|
114
|
+
const queueKindSql=canonicalKindSql("COALESCE(a.task_kind,json_extract(a.payload,'$.task_kind'),CASE WHEN a.review=1 THEN 'review' ELSE json_extract(a.payload,'$.execution_scope') END,'unknown')");
|
|
115
|
+
export const breakNoticeText=ids=>`the worker is on a usage break; do this yourself with a cheap model if it is urgent, or leave it queued (requests: ${ids.slice(0,20).join(', ')}${ids.length>20?` and ${ids.length-20} more`:''})`;
|
|
116
|
+
// When a queued row most recently entered the queue: its latest lifecycle 'queued' event, or created_at if retention removed it.
|
|
117
|
+
const queuedAt="COALESCE((SELECT max(l.at) FROM lifecycle_events l WHERE l.request_id=a.request_id AND l.type='queued'),a.created_at)";
|
|
118
|
+
// The pause is temporary: a worker that gave up after this error never claimed again, so the message says to come back.
|
|
119
|
+
export const pausedClaimMessage='bridge paused (temporary): new claims are refused until the operator resumes. Keep working on jobs you already hold, then call list_pending and claim again later; claims are accepted as soon as the pause ends.';
|
|
120
|
+
// Priority orders list_pending and re-wake; it never hides or refuses work. Within a priority, an item the worker passed over
|
|
121
|
+
// (skipped_at) goes behind the others, then oldest first.
|
|
122
|
+
const LIST_ORDER="CASE priority WHEN 'normal' THEN 0 ELSE 1 END,skipped_at IS NOT NULL,created_at";
|
|
123
|
+
// An item is marked skipped_by_worker when the worker passes it over, by either of two signals:
|
|
124
|
+
// - passed over: the worker claimed an assignment listed after it, SKIP_AFTER_PASSED times, while it had listed this one within
|
|
125
|
+
// PASSED_SEEN_MS. This detects items repeatedly pushed behind newer work before they enter the claimable window.
|
|
126
|
+
// - eligible: it sat in the first free_lanes entries (the ones the worker could claim) at a poll SKIP_AFTER_ELIGIBLE_MS after
|
|
127
|
+
// the first such poll, and was not claimed. A poll that shows no free lane forgets this clock: waiting for a lane is not a skip.
|
|
128
|
+
const SKIP_AFTER_PASSED=3, PASSED_SEEN_MS=180000, SKIP_AFTER_ELIGIBLE_MS=600000, LISTED_POLL_GAP_MS=30000;
|
|
129
|
+
// Preparation expiry uses one predicate for every queued count, list, gate and sweep.
|
|
130
|
+
// Learned windows end at first claim; claims rows survive abandonment and requeue.
|
|
131
|
+
export const validUntilOf=payload=>{const ms=typeof payload?.valid_until==='string'?Date.parse(payload.valid_until):NaN;return Number.isFinite(ms)?iso(ms):null;};
|
|
132
|
+
const expired=nowMs=>`(valid_until IS NOT NULL AND valid_until<='${iso(nowMs)}' AND NOT (COALESCE(valid_until_source,'')='queue_p90' AND request_id IN (SELECT request_id FROM claims)))`;
|
|
133
|
+
const live=nowMs=>`NOT ${expired(nowMs)} AND (request_id NOT IN (SELECT request_id FROM protocol_jobs) OR request_id IN (
|
|
134
|
+
SELECT p.request_id FROM protocol_jobs p JOIN job_retention_policy r ON r.job=p.request_id
|
|
135
|
+
WHERE CAST(json_extract(p.settings,'$.retain_until_ms') AS INTEGER)>'${nowMs}'
|
|
136
|
+
AND NOT EXISTS (SELECT 1 FROM job_retention_tombstones t WHERE t.job=p.request_id)
|
|
137
|
+
))`;
|
|
138
|
+
export const expiredError=(validUntil,{cancelled=false,requeue=false}={})=>`assignment_expired: its prepared inputs were valid until ${validUntil}; ${cancelled?'the bridge cancelled it and will not requeue it':requeue?'the bridge has not cancelled it; the expiry sweep will evaluate whether it can requeue it':'the bridge has not cancelled it yet and will not requeue it'}. Call list_pending, then claim another listed assignment.`;
|
|
139
|
+
const denialPattern=/auto-?review|guardian|denied|not approved|paused out of precaution/i;
|
|
140
|
+
export const workerGuidance='If auto-review or Guardian denies an action, stop that line of work, report BLOCKED: with the denied action, and never retry or rephrase to get around it. A denial or error about one assignment does not affect another: an error naming a different request_id (for example a finished assignment) is not a revocation of this one. An assignment with a new request_id that the owner submitted is a separate, fresh owner request, made after the owner saw the earlier outcome; it is not a retry of a denied action, so judge it on its own merits. If finish answers assignment_cancelled, the owner withdrew that request: this is not a denial and nothing to work around or retry; stop work on it and move on. Read the response to see whether bounded audit evidence was retained; output after the lease deadline is dropped. Check owner_notes on this assignment with get before finishing. Reading UI source that renders or validates a credential input field is ordinary UI work; the restriction is on revealing, copying, changing or transmitting actual secret values.';
|
|
141
|
+
export const matchesDenial=text=>denialPattern.test(text);
|
|
142
|
+
// Evidence that the worker cannot take work: its note says the reviewer denied a claim. The worker never retries a denied line, so
|
|
143
|
+
// re-waking that request is noise; a capacity-overrun denial means the worker is full, so no re-wake helps until a slot frees.
|
|
144
|
+
const capacityHoldMaxMs=30*60000;
|
|
145
|
+
const claimDenial=/\b(?:denied|rejected|refused|not approved)\b/i;
|
|
146
|
+
|
|
147
|
+
export function loadRedeliveryLimits(file=defaultPath(os.homedir(),'.config/dot-bridge/limits.json')) {
|
|
148
|
+
if(!fs.existsSync(file)) return {...defaultRedeliveryLimits};
|
|
149
|
+
if((fs.statSync(file).mode&0o777)!==0o600) throw new Error('limits policy must be mode 0600');
|
|
150
|
+
const value=JSON.parse(fs.readFileSync(file,'utf8'));
|
|
151
|
+
// Legacy keys, still validated so existing files load. Neither drives re-wake any more: the interval only sets the
|
|
152
|
+
// alive_not_claiming status threshold (2x interval); max_count is ignored.
|
|
153
|
+
const intervalMs=value.assignment_reannounce_interval_ms??defaultRedeliveryLimits.intervalMs;
|
|
154
|
+
const maxCount=value.assignment_reannounce_max_count??defaultRedeliveryLimits.maxCount;
|
|
155
|
+
if(!Number.isInteger(intervalMs)||intervalMs<60000||intervalMs>86400000) throw new Error('invalid assignment_reannounce_interval_ms');
|
|
156
|
+
if(!Number.isInteger(maxCount)||maxCount<0||maxCount>10) throw new Error('invalid assignment_reannounce_max_count');
|
|
157
|
+
const silenceMs=value.pause_suspected_silence_ms??defaultRedeliveryLimits.silenceMs;
|
|
158
|
+
// A claim lease expires at last claim activity + leaseMs. stale_claim_ms is the legacy name, read only when claim_lease_ms is absent.
|
|
159
|
+
const leaseKey=value.claim_lease_ms!=null?'claim_lease_ms':value.stale_claim_ms!=null?'stale_claim_ms':null;
|
|
160
|
+
const leaseMs=leaseKey?value[leaseKey]:defaultRedeliveryLimits.leaseMs;
|
|
161
|
+
if(!Number.isInteger(silenceMs)||silenceMs<60000||silenceMs>86400000) throw new Error('invalid pause_suspected_silence_ms');
|
|
162
|
+
if(!Number.isInteger(leaseMs)||leaseMs<60000||leaseMs>604800000) throw new Error(`invalid ${leaseKey}`);
|
|
163
|
+
// Denominator of utilization metrics: how many lanes the worker can work in parallel. Independent of the claim cap (max_claimed_outer_assignments).
|
|
164
|
+
// worker_* limits keys are the current names; the dot_* names are read as aliases so existing files keep working.
|
|
165
|
+
const laneCapacity=value.worker_lane_capacity??value.dot_lane_capacity??defaultRedeliveryLimits.laneCapacity;
|
|
166
|
+
if(!Number.isInteger(laneCapacity)||laneCapacity<1||laneCapacity>10) throw new Error('invalid worker_lane_capacity');
|
|
167
|
+
// Queue re-wake: minimum gap between wakes of one subscription, and how long after entering the queue an item is re-woken.
|
|
168
|
+
const rewakeMs=value.queue_rewake_ms??defaultRedeliveryLimits.rewakeMs;
|
|
169
|
+
if(!Number.isInteger(rewakeMs)||rewakeMs<30000||rewakeMs>3600000) throw new Error('invalid queue_rewake_ms');
|
|
170
|
+
const rewakeWindowMs=value.queue_rewake_window_ms??defaultRedeliveryLimits.rewakeWindowMs;
|
|
171
|
+
if(!Number.isInteger(rewakeWindowMs)||rewakeWindowMs<600000||rewakeWindowMs>86400000) throw new Error('invalid queue_rewake_window_ms');
|
|
172
|
+
const rewakeStaleMs=value.queue_rewake_stale_ms??defaultRedeliveryLimits.rewakeStaleMs;
|
|
173
|
+
if(!Number.isInteger(rewakeStaleMs)||rewakeStaleMs<300000||rewakeStaleMs>86400000) throw new Error('invalid queue_rewake_stale_ms');
|
|
174
|
+
// Usage break: silence that infers a break, and the gap between probe wakes during one.
|
|
175
|
+
const breakSilenceMs=value.worker_break_silence_ms??value.dot_break_silence_ms??defaultRedeliveryLimits.breakSilenceMs;
|
|
176
|
+
if(!Number.isInteger(breakSilenceMs)||breakSilenceMs<60000||breakSilenceMs>86400000) throw new Error('invalid worker_break_silence_ms');
|
|
177
|
+
const breakProbeMs=value.worker_break_probe_ms??value.dot_break_probe_ms??defaultRedeliveryLimits.breakProbeMs;
|
|
178
|
+
if(!Number.isInteger(breakProbeMs)||breakProbeMs<60000||breakProbeMs>86400000) throw new Error('invalid worker_break_probe_ms');
|
|
179
|
+
// Throttle: rolling-hour ceilings for drainer submits and re-wakes. The worker's own claim calls are never refused.
|
|
180
|
+
const maxClaimsPerHour=value.max_claims_per_hour??defaultRedeliveryLimits.maxClaimsPerHour;
|
|
181
|
+
if(!Number.isInteger(maxClaimsPerHour)||maxClaimsPerHour<1||maxClaimsPerHour>1000) throw new Error('invalid max_claims_per_hour');
|
|
182
|
+
// Budget tool calls over rolling daily and hourly windows to limit bursts.
|
|
183
|
+
const maxToolCallsPerHour=value.max_tool_calls_per_hour??defaultRedeliveryLimits.maxToolCallsPerHour;
|
|
184
|
+
if(!Number.isInteger(maxToolCallsPerHour)||maxToolCallsPerHour<1||maxToolCallsPerHour>100000) throw new Error('invalid max_tool_calls_per_hour');
|
|
185
|
+
const maxToolCallsPer24h=value.max_tool_calls_per_24h??defaultRedeliveryLimits.maxToolCallsPer24h;
|
|
186
|
+
if(!Number.isInteger(maxToolCallsPer24h)||maxToolCallsPer24h<10||maxToolCallsPer24h>10000000) throw new Error('invalid max_tool_calls_per_24h');
|
|
187
|
+
// Rolling-hour ceiling on the bytes of MCP responses to the worker's tool calls (a usage break likely meters tokens).
|
|
188
|
+
// Use a rolling 24 h byte budget and an hourly burst ceiling. The rolling budget limits sustained response volume;
|
|
189
|
+
// the hourly ceiling limits a short burst.
|
|
190
|
+
const maxResponseBytesPerHour=value.max_response_bytes_per_hour??defaultRedeliveryLimits.maxResponseBytesPerHour;
|
|
191
|
+
if(!Number.isInteger(maxResponseBytesPerHour)||maxResponseBytesPerHour<100000||maxResponseBytesPerHour>1000000000) throw new Error('invalid max_response_bytes_per_hour');
|
|
192
|
+
const maxResponseBytesPer24h=value.max_response_bytes_per_24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
|
|
193
|
+
if(!Number.isInteger(maxResponseBytesPer24h)||maxResponseBytesPer24h<1000000||maxResponseBytesPer24h>10000000000) throw new Error('invalid max_response_bytes_per_24h');
|
|
194
|
+
return {intervalMs,maxCount,silenceMs,leaseMs,laneCapacity,rewakeMs,rewakeWindowMs,rewakeStaleMs,breakSilenceMs,breakProbeMs,maxClaimsPerHour,maxToolCallsPerHour,maxToolCallsPer24h,maxResponseBytesPer24h,maxResponseBytesPerHour};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Gates that cap one rolling hour. They hold background work before agent-requested work (see rollingUsage).
|
|
198
|
+
// A learned limit never cuts below this share of the configured one. This prevents a quiet period from reducing the limit
|
|
199
|
+
// below a useful fraction of the operator's configured value.
|
|
200
|
+
export const learnedFloorFraction=0.25;
|
|
201
|
+
|
|
202
|
+
// Configured resume workers and the legacy worker receive acquisition guidance. This does not enable idle rotation.
|
|
203
|
+
const defaultResumeIdleMs=120000;
|
|
204
|
+
// With a trusted OS clock across restarts, thirty minutes allows passive recovery but bounds the delivery hold.
|
|
205
|
+
export const UNCERTAIN_DELIVERY_MAX_AGE_MS=30*60_000;
|
|
206
|
+
export function resumeNudge(threshold=defaultResumeIdleMs) {
|
|
207
|
+
const seconds=Math.max(30,Math.floor(threshold/2/30000)*30);
|
|
208
|
+
const interval=seconds%60===0?`${seconds/60} minute${seconds===60?'':'s'}`:`${seconds} seconds`;
|
|
209
|
+
return `Generate one random acquisition_id per run and pass it on every claim call, including retries. Keep that acquisition_id, claimant and returned claim_id in your own saved run state across QUESTION/answer pauses and reconnects: an answered question continues the same acquisition. A separate run must use its own acquisition_id; do not copy another run's grant from get. Post progress at least every ${interval} with what is done and what remains, so a resumed run can continue; if your run may end, post progress first.`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function databasePath(file) {
|
|
213
|
+
try {
|
|
214
|
+
if(file instanceof URL) {
|
|
215
|
+
const url=new URL(file);
|
|
216
|
+
if(url.protocol!=='file:'||url.host) return null;
|
|
217
|
+
url.search=''; url.hash='';
|
|
218
|
+
return fileURLToPath(url);
|
|
219
|
+
}
|
|
220
|
+
if(typeof file!=='string'||file===':memory:') return null;
|
|
221
|
+
if(file.startsWith('file:')) {
|
|
222
|
+
const url=new URL(file);
|
|
223
|
+
if(url.protocol!=='file:'||url.host) return null;
|
|
224
|
+
url.search=''; url.hash='';
|
|
225
|
+
return fileURLToPath(url);
|
|
226
|
+
}
|
|
227
|
+
return path.resolve(file);
|
|
228
|
+
} catch { return null; }
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Resolve through the nearest existing ancestor before SQLite creates the filename.
|
|
232
|
+
function databaseLocation(file) {
|
|
233
|
+
let existing=path.resolve(file);const missing=[];
|
|
234
|
+
for(;;) {
|
|
235
|
+
try { return path.join(fs.realpathSync(existing),...missing); }
|
|
236
|
+
catch(error) {
|
|
237
|
+
if(error.code!=='ENOENT'&&error.code!=='ENOTDIR') throw error;
|
|
238
|
+
const parent=path.dirname(existing);if(parent===existing) throw error;
|
|
239
|
+
missing.unshift(path.basename(existing));existing=parent;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function isDefaultHomeDatabase(file) {
|
|
245
|
+
const requested=databasePath(file);
|
|
246
|
+
if(!requested) return false;
|
|
247
|
+
const homes=new Set([os.homedir()]);
|
|
248
|
+
try { homes.add(os.userInfo().homedir); } catch {}
|
|
249
|
+
const defaults=[];
|
|
250
|
+
for(const home of homes) for(const name of ['dot-bridge','dalan']) defaults.push(path.join(home,'.local/share',name,'bridge.db'));
|
|
251
|
+
for(const target of defaults) {
|
|
252
|
+
if(path.resolve(requested)===path.resolve(target)) return true;
|
|
253
|
+
// Canonical paths catch symlinks; device/inode also catches hard links.
|
|
254
|
+
try {
|
|
255
|
+
const canonicalTarget=databaseLocation(target);
|
|
256
|
+
const canonicalRequested=databaseLocation(requested);
|
|
257
|
+
if(canonicalRequested===canonicalTarget) return true;
|
|
258
|
+
const targetStat=fs.statSync(target),requestedStat=fs.statSync(requested);
|
|
259
|
+
if(targetStat.dev===requestedStat.dev&&targetStat.ino===requestedStat.ino) return true;
|
|
260
|
+
} catch {}
|
|
261
|
+
}
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function refuseDefaultHomeMigration(file, authorized) {
|
|
266
|
+
// This prevents accidental imports/tools from migrating the service DB; it cannot constrain same-UID code.
|
|
267
|
+
if(authorized||!isDefaultHomeDatabase(file)) return;
|
|
268
|
+
const filename=databasePath(file);
|
|
269
|
+
if(!filename) return;
|
|
270
|
+
let exists;
|
|
271
|
+
try { exists=fs.statSync(filename).isFile(); }
|
|
272
|
+
catch(error) { if(error.code!=='ENOENT') throw error; }
|
|
273
|
+
let version=0,db;
|
|
274
|
+
try {
|
|
275
|
+
if(exists) {
|
|
276
|
+
db=new DatabaseSync(file,{readOnly:true});
|
|
277
|
+
version=db.prepare('PRAGMA user_version').get().user_version;
|
|
278
|
+
}
|
|
279
|
+
} finally { db?.close(); }
|
|
280
|
+
if(version<SUPPORTED_SCHEMA_VERSION) {
|
|
281
|
+
throw new Error(`refusing to migrate default-home Dalan database at ${file} (schema ${version} < ${SUPPORTED_SCHEMA_VERSION}); service startup must pass allowDefaultHomeMigration: true. This is an accidental-migration guard, not a security boundary against same-UID code.`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export class Store {
|
|
286
|
+
constructor(file, options={}) {
|
|
287
|
+
this.resumeIdleOption=options.resumeIdleMs;
|
|
288
|
+
this.workers=options.workers??LEGACY_PROFILE;
|
|
289
|
+
this.destinationProfile=options.destinationProfile??null;
|
|
290
|
+
// Server-side diagnostic only: receives the raw configuration error that destinationConfigurationError hides from callers.
|
|
291
|
+
this.onConfigError=options.onConfigError??null;
|
|
292
|
+
this.allowedDotSubjects=options.allowedDotSubjects??null;
|
|
293
|
+
const wallNow=options.now??Date.now;
|
|
294
|
+
this.monotonicNow=options.elapsedNow??monotonicMs;
|
|
295
|
+
this.leaseBootId=options.bootId??(options.now?null:systemBootId());
|
|
296
|
+
if(options.elapsedNow) {
|
|
297
|
+
const epoch=wallNow(),elapsed=options.elapsedNow();
|
|
298
|
+
this.nowMs=()=>Math.floor(epoch+options.elapsedNow()-elapsed);
|
|
299
|
+
} else if(options.now) this.nowMs=options.now;
|
|
300
|
+
else {
|
|
301
|
+
const epoch=Date.now(),elapsed=process.hrtime.bigint();
|
|
302
|
+
this.nowMs=()=>Math.floor(epoch+Number(process.hrtime.bigint()-elapsed)/1e6);
|
|
303
|
+
}
|
|
304
|
+
this.capacity=options.capacity??6;
|
|
305
|
+
this.backgroundMaxInFlight=options.backgroundMaxInFlight??4;
|
|
306
|
+
this.limits=options.limits??{...defaultRedeliveryLimits};
|
|
307
|
+
this.skipExpireMs=options.skipExpireMs??6*3600000;
|
|
308
|
+
this.connectionIsLive=options.connectionIsLive??null;
|
|
309
|
+
this.stamp=()=>new Date(this.nowMs()).toISOString();
|
|
310
|
+
this.startedMs=this.nowMs();
|
|
311
|
+
refuseDefaultHomeMigration(file,options.allowDefaultHomeMigration===true);
|
|
312
|
+
this.db = new DatabaseSync(file);
|
|
313
|
+
let storage;
|
|
314
|
+
try {
|
|
315
|
+
this.db.exec('PRAGMA busy_timeout=30000');
|
|
316
|
+
const version = this.db.prepare('PRAGMA user_version').get().user_version;
|
|
317
|
+
if (version > SUPPORTED_SCHEMA_VERSION) throw unsupportedSchemaVersion(version);
|
|
318
|
+
storage = acquireSubscriptionStorage(file);
|
|
319
|
+
const current = this.db.prepare('PRAGMA user_version').get().user_version;
|
|
320
|
+
if (current > SUPPORTED_SCHEMA_VERSION) throw unsupportedSchemaVersion(current);
|
|
321
|
+
const hasStorage = !!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subscription_storage_meta'").get();
|
|
322
|
+
this.subscriptionCodec = new SubscriptionCodec(storage.key ?? storage.loadKey(current >= 52 || hasStorage));
|
|
323
|
+
this.db.exec(`PRAGMA secure_delete=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA recursive_triggers=ON; PRAGMA busy_timeout=5000;
|
|
324
|
+
CREATE TABLE IF NOT EXISTS assignments (request_id TEXT PRIMARY KEY, payload TEXT NOT NULL, payload_hash TEXT NOT NULL, thread_id TEXT NOT NULL, environment_id TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued', created_at TEXT NOT NULL, cancelled_at TEXT);
|
|
325
|
+
CREATE TABLE IF NOT EXISTS claims (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), claimant TEXT NOT NULL, claim_id TEXT NOT NULL UNIQUE, claimed_at TEXT NOT NULL);
|
|
326
|
+
CREATE TABLE IF NOT EXISTS progress (id INTEGER PRIMARY KEY, request_id TEXT NOT NULL REFERENCES assignments(request_id), note TEXT NOT NULL, created_at TEXT NOT NULL);
|
|
327
|
+
CREATE TABLE IF NOT EXISTS reports (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), claim_id TEXT NOT NULL, outcome TEXT NOT NULL, summary TEXT NOT NULL, result TEXT NOT NULL, receipt_id TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL, late INTEGER NOT NULL DEFAULT 0);
|
|
328
|
+
CREATE TABLE IF NOT EXISTS subscriptions (id TEXT PRIMARY KEY, principal TEXT NOT NULL, url TEXT NOT NULL, args TEXT NOT NULL, secret TEXT NOT NULL, expires_at TEXT NOT NULL, verified_at TEXT NOT NULL);
|
|
329
|
+
CREATE TABLE IF NOT EXISTS notifications (id TEXT PRIMARY KEY, kind TEXT NOT NULL, request_id TEXT NOT NULL REFERENCES assignments(request_id), subscription_id TEXT, body TEXT, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL DEFAULT 0, last_error TEXT, argv TEXT, created_at TEXT NOT NULL);
|
|
330
|
+
CREATE TABLE IF NOT EXISTS messages (message_id TEXT PRIMARY KEY, text TEXT NOT NULL, text_sha256 TEXT NOT NULL, preview TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TEXT NOT NULL, acknowledged_at TEXT);
|
|
331
|
+
CREATE TABLE IF NOT EXISTS bridge_state (key TEXT PRIMARY KEY,value TEXT NOT NULL) WITHOUT ROWID;
|
|
332
|
+
CREATE INDEX IF NOT EXISTS notifications_due ON notifications(state,next_at);`);
|
|
333
|
+
this.migrate();
|
|
334
|
+
this.pullQueue=new PullQueue(this);
|
|
335
|
+
this.initializeLeaseClock();
|
|
336
|
+
this.initializeSubscriptionStorage();
|
|
337
|
+
} catch(error) { this.db.close(); throw error; } finally { storage?.release(); }
|
|
338
|
+
if(options.markProfileModeSeen===true) this.markProfileModeSeen();
|
|
339
|
+
if(options.deferSubscriptionRetirement!==true) this.retireUnknownSubscriptions();
|
|
340
|
+
}
|
|
341
|
+
// Join the caller's transaction (touch runs inside claim admission) or open one, so check and write share one snapshot.
|
|
342
|
+
inTransaction(fn) { return this.db.isTransaction?fn():this.transaction(fn); }
|
|
343
|
+
transaction(fn) { this.db.exec('BEGIN IMMEDIATE'); try { const result=fn(); this.db.exec('COMMIT'); return result; } catch(error) { this.db.exec('ROLLBACK'); throw error; } }
|
|
344
|
+
profileModeSeen() { return this.db.prepare("SELECT 1 FROM bridge_state WHERE key='workers_profile_seen'").get()!==undefined; }
|
|
345
|
+
markProfileModeSeen() { this.db.prepare("INSERT INTO bridge_state(key,value) VALUES('workers_profile_seen','1') ON CONFLICT(key) DO NOTHING").run(); }
|
|
346
|
+
// Record one lifecycle event; callers run it inside the transaction of the state change it describes.
|
|
347
|
+
// claim defaults to the claim in force (the active row); an explicit claim_id without epoch resolves its epoch from history.
|
|
348
|
+
lifecycle(id,type,actor='system',reason=null,claim=this.db.prepare("SELECT claim_id,epoch FROM claims WHERE request_id=? AND state='active'").get(id)) {
|
|
349
|
+
const epoch=claim?.claim_id&&claim.epoch==null?this.db.prepare('SELECT epoch FROM claims WHERE claim_id=?').get(claim.claim_id)?.epoch??this.db.prepare('SELECT epoch FROM lifecycle_events WHERE claim_id=? AND epoch IS NOT NULL LIMIT 1').get(claim.claim_id)?.epoch??null:claim?.epoch??null;
|
|
350
|
+
const worker=claim?.worker??(claim?.claim_id?this.db.prepare('SELECT worker FROM claims WHERE claim_id=?').get(claim.claim_id)?.worker??this.db.prepare('SELECT worker FROM lifecycle_events WHERE claim_id=? LIMIT 1').get(claim.claim_id)?.worker:null)??'unknown';
|
|
351
|
+
this.db.prepare("INSERT INTO lifecycle_events(request_id,claim_id,epoch,type,at,actor,source,reason,worker) VALUES(?,?,?,?,?,?,'live',?,?)").run(id,claim?.claim_id??null,epoch,type,this.stamp(),actor,reason,worker);
|
|
352
|
+
}
|
|
353
|
+
migrate() {
|
|
354
|
+
this.transaction(() => {
|
|
355
|
+
const version = this.db.prepare('PRAGMA user_version').get().user_version;
|
|
356
|
+
if (version > SUPPORTED_SCHEMA_VERSION) throw unsupportedSchemaVersion(version);
|
|
357
|
+
if(version>=35&&(!this.db.prepare("SELECT 1 FROM sqlite_master WHERE name='schema_migrations'").get()||!this.db.prepare("SELECT 1 FROM schema_migrations WHERE identity='s1v2-worker-facts-20261022'").get()))
|
|
358
|
+
throw new Error('abandoned worker-isolation schema: missing s1v2-worker-facts-20261022; restore the pre-isolation backup');
|
|
359
|
+
if (version < 2) {
|
|
360
|
+
this.db.exec(`ALTER TABLE assignments ADD COLUMN owner_hash TEXT;
|
|
361
|
+
ALTER TABLE subscriptions ADD COLUMN state TEXT NOT NULL DEFAULT 'active';
|
|
362
|
+
ALTER TABLE subscriptions ADD COLUMN last_event_2xx_at TEXT;
|
|
363
|
+
ALTER TABLE subscriptions ADD COLUMN auth_failures INTEGER NOT NULL DEFAULT 0;
|
|
364
|
+
ALTER TABLE subscriptions ADD COLUMN rotation_blocked INTEGER NOT NULL DEFAULT 0;
|
|
365
|
+
ALTER TABLE notifications ADD COLUMN attempt_started_at TEXT;
|
|
366
|
+
ALTER TABLE notifications ADD COLUMN attempt_id TEXT;
|
|
367
|
+
ALTER TABLE notifications ADD COLUMN last_reconciled_at TEXT;
|
|
368
|
+
ALTER TABLE notifications ADD COLUMN uncertain_reason TEXT;
|
|
369
|
+
CREATE TABLE watches (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), deadline TEXT NOT NULL, state TEXT NOT NULL, updated_at TEXT NOT NULL, notification_id TEXT);
|
|
370
|
+
CREATE TABLE operator_state (id INTEGER PRIMARY KEY CHECK(id=1), paused_at TEXT, reason TEXT);
|
|
371
|
+
INSERT INTO operator_state(id) VALUES(1);
|
|
372
|
+
CREATE TABLE alert_episodes (condition TEXT PRIMARY KEY, active INTEGER NOT NULL, started_at TEXT, last_change_at TEXT NOT NULL);
|
|
373
|
+
PRAGMA user_version=2;`);
|
|
374
|
+
}
|
|
375
|
+
if (version < 3) {
|
|
376
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS workspaces (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), claim_id TEXT NOT NULL, base_sha TEXT NOT NULL, path TEXT NOT NULL UNIQUE, created_at TEXT NOT NULL);
|
|
377
|
+
CREATE TABLE IF NOT EXISTS check_runs (id TEXT PRIMARY KEY, request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, check_id TEXT NOT NULL, exit_code INTEGER, timed_out INTEGER NOT NULL, output_artifact_id TEXT NOT NULL, output_sha256 TEXT NOT NULL, duration_ms INTEGER NOT NULL, created_at TEXT NOT NULL);
|
|
378
|
+
CREATE TABLE IF NOT EXISTS artifacts (id TEXT PRIMARY KEY, request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, kind TEXT NOT NULL, path TEXT NOT NULL UNIQUE, size INTEGER NOT NULL, sha256 TEXT, sealed INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL);
|
|
379
|
+
ALTER TABLE claims ADD COLUMN subject TEXT NOT NULL DEFAULT 'local-principal';
|
|
380
|
+
ALTER TABLE reports ADD COLUMN workspace_evidence TEXT;
|
|
381
|
+
PRAGMA user_version=3;`);
|
|
382
|
+
}
|
|
383
|
+
if (version < 4) {
|
|
384
|
+
this.db.exec(`ALTER TABLE artifacts ADD COLUMN retention_until TEXT;
|
|
385
|
+
PRAGMA user_version=4;`);
|
|
386
|
+
}
|
|
387
|
+
if (version < 5) {
|
|
388
|
+
this.db.exec(`ALTER TABLE check_runs ADD COLUMN diff_sha256 TEXT;
|
|
389
|
+
PRAGMA user_version=5;`);
|
|
390
|
+
}
|
|
391
|
+
if (version < 6) {
|
|
392
|
+
this.db.exec(`ALTER TABLE workspaces ADD COLUMN initial_patch_applied INTEGER NOT NULL DEFAULT 0;
|
|
393
|
+
PRAGMA user_version=6;`);
|
|
394
|
+
}
|
|
395
|
+
if (version < 7) {
|
|
396
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS assignment_reannouncements (request_id TEXT NOT NULL REFERENCES assignments(request_id), subscription_id TEXT NOT NULL REFERENCES subscriptions(id), count INTEGER NOT NULL DEFAULT 0, last_announced_at TEXT NOT NULL, PRIMARY KEY(request_id, subscription_id));
|
|
397
|
+
PRAGMA user_version=7;`);
|
|
398
|
+
}
|
|
399
|
+
if (version < 8) {
|
|
400
|
+
this.db.exec(`ALTER TABLE check_runs ADD COLUMN phase TEXT NOT NULL DEFAULT 'check';
|
|
401
|
+
PRAGMA user_version=8;`);
|
|
402
|
+
}
|
|
403
|
+
if (version < 9) {
|
|
404
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS messages (message_id TEXT PRIMARY KEY, text TEXT NOT NULL, text_sha256 TEXT NOT NULL, preview TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', created_at TEXT NOT NULL, acknowledged_at TEXT);
|
|
405
|
+
CREATE INDEX IF NOT EXISTS messages_pending ON messages(status,created_at);
|
|
406
|
+
PRAGMA user_version=9;`);
|
|
407
|
+
}
|
|
408
|
+
if (version < 10) {
|
|
409
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS t3_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, call_id TEXT NOT NULL, subject TEXT NOT NULL, tool TEXT NOT NULL, args_summary TEXT NOT NULL, text_sha256 TEXT, text_preview TEXT, result_status TEXT NOT NULL, t3_ids TEXT NOT NULL DEFAULT '{}');
|
|
410
|
+
CREATE INDEX IF NOT EXISTS t3_audit_at ON t3_audit(at);
|
|
411
|
+
CREATE TRIGGER IF NOT EXISTS t3_audit_no_update BEFORE UPDATE ON t3_audit BEGIN SELECT RAISE(ABORT, 't3 audit is append-only'); END;
|
|
412
|
+
CREATE TRIGGER IF NOT EXISTS t3_audit_no_delete BEFORE DELETE ON t3_audit BEGIN SELECT RAISE(ABORT, 't3 audit is append-only'); END;
|
|
413
|
+
PRAGMA user_version=10;`);
|
|
414
|
+
}
|
|
415
|
+
if (version < 11) {
|
|
416
|
+
this.db.exec(`CREATE TABLE notifications_new (id TEXT PRIMARY KEY, kind TEXT NOT NULL, request_id TEXT REFERENCES assignments(request_id), subscription_id TEXT, body TEXT, state TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL DEFAULT 0, last_error TEXT, argv TEXT, created_at TEXT NOT NULL, attempt_started_at TEXT, attempt_id TEXT, last_reconciled_at TEXT, uncertain_reason TEXT, message_id TEXT REFERENCES messages(message_id));
|
|
417
|
+
INSERT INTO notifications_new(id,kind,request_id,subscription_id,body,state,attempts,next_at,last_error,argv,created_at,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason)
|
|
418
|
+
SELECT id,kind,request_id,subscription_id,body,state,attempts,next_at,last_error,argv,created_at,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason FROM notifications;
|
|
419
|
+
DROP TABLE notifications;
|
|
420
|
+
ALTER TABLE notifications_new RENAME TO notifications;
|
|
421
|
+
CREATE INDEX notifications_due ON notifications(state,next_at);
|
|
422
|
+
CREATE TABLE check_jobs (id TEXT PRIMARY KEY, request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, check_id TEXT NOT NULL, diff_sha256 TEXT NOT NULL, status TEXT NOT NULL, started_at TEXT NOT NULL, finished_at TEXT, error TEXT, output_preview TEXT);
|
|
423
|
+
CREATE INDEX check_jobs_request ON check_jobs(request_id,started_at);
|
|
424
|
+
INSERT INTO check_jobs(id,request_id,claim_id,check_id,diff_sha256,status,started_at,finished_at)
|
|
425
|
+
SELECT id,request_id,claim_id,check_id,COALESCE(diff_sha256,''),'completed',created_at,created_at FROM check_runs;
|
|
426
|
+
PRAGMA user_version=11;`);
|
|
427
|
+
}
|
|
428
|
+
if (version < 12) {
|
|
429
|
+
this.db.exec(`CREATE TABLE owner_notes (sequence INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL UNIQUE, request_id TEXT NOT NULL REFERENCES assignments(request_id), at TEXT NOT NULL, text TEXT NOT NULL);
|
|
430
|
+
CREATE INDEX owner_notes_request ON owner_notes(request_id,sequence);
|
|
431
|
+
CREATE TRIGGER owner_notes_no_update BEFORE UPDATE ON owner_notes BEGIN SELECT RAISE(ABORT, 'owner notes are append-only'); END;
|
|
432
|
+
CREATE TRIGGER owner_notes_no_delete BEFORE DELETE ON owner_notes BEGIN SELECT RAISE(ABORT, 'owner notes are append-only'); END;
|
|
433
|
+
PRAGMA user_version=12;`);
|
|
434
|
+
}
|
|
435
|
+
if (version < 13) {
|
|
436
|
+
this.db.exec(`ALTER TABLE assignments ADD COLUMN review INTEGER NOT NULL DEFAULT 0;
|
|
437
|
+
PRAGMA user_version=13;`);
|
|
438
|
+
}
|
|
439
|
+
if (version < 14) {
|
|
440
|
+
this.db.exec(`CREATE TABLE worker_activity (subject TEXT PRIMARY KEY, last_call_at TEXT NOT NULL, last_list_pending_at TEXT);
|
|
441
|
+
ALTER TABLE claims ADD COLUMN last_progress_at TEXT;
|
|
442
|
+
ALTER TABLE claims ADD COLUMN last_claim_activity_at TEXT;
|
|
443
|
+
ALTER TABLE claims ADD COLUMN last_seen_note_seq INTEGER NOT NULL DEFAULT 0;
|
|
444
|
+
UPDATE claims SET last_claim_activity_at=claimed_at, last_seen_note_seq=COALESCE((SELECT max(sequence) FROM owner_notes n WHERE n.request_id=claims.request_id),0);
|
|
445
|
+
ALTER TABLE assignment_reannouncements ADD COLUMN next_due_at INTEGER;
|
|
446
|
+
CREATE TABLE alert_cursors (name TEXT PRIMARY KEY, value INTEGER NOT NULL);
|
|
447
|
+
INSERT INTO alert_cursors(name,value) VALUES('denial_progress',COALESCE((SELECT max(id) FROM progress),0)),('denial_report',COALESCE((SELECT max(rowid) FROM reports),0));
|
|
448
|
+
PRAGMA user_version=14;`);
|
|
449
|
+
}
|
|
450
|
+
if (version < 15) {
|
|
451
|
+
// `waiting` is a durable reservation for one live owner long-poll. It is
|
|
452
|
+
// deliberately not a new delivery channel: a dropped connection releases
|
|
453
|
+
// the row back to the ordinary T3 queue.
|
|
454
|
+
this.db.exec(`PRAGMA user_version=15;`);
|
|
455
|
+
}
|
|
456
|
+
if (version < 16) {
|
|
457
|
+
this.db.exec(`ALTER TABLE assignments ADD COLUMN delivery TEXT;
|
|
458
|
+
UPDATE assignments SET delivery='t3:' || thread_id WHERE delivery IS NULL;
|
|
459
|
+
PRAGMA user_version=16;`);
|
|
460
|
+
}
|
|
461
|
+
if (version < 17) {
|
|
462
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS assignment_delivery_mutes (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), muted_at TEXT NOT NULL);
|
|
463
|
+
PRAGMA user_version=17;`);
|
|
464
|
+
}
|
|
465
|
+
if (version < 18) {
|
|
466
|
+
this.db.exec(`CREATE TABLE pr_preflights (request_id TEXT NOT NULL REFERENCES assignments(request_id), phase TEXT NOT NULL CHECK(phase IN ('submit','claim')), evidence TEXT NOT NULL, PRIMARY KEY(request_id,phase));
|
|
467
|
+
PRAGMA user_version=18;`);
|
|
468
|
+
}
|
|
469
|
+
if (version < 19) {
|
|
470
|
+
const hasPriority=this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='priority'").get();
|
|
471
|
+
if(!hasPriority) this.db.exec("ALTER TABLE assignments ADD COLUMN priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('normal','background'))");
|
|
472
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS assignments_pending_priority ON assignments(status,priority,created_at);
|
|
473
|
+
PRAGMA user_version=19;`);
|
|
474
|
+
}
|
|
475
|
+
if (version < 20) {
|
|
476
|
+
// Existing claims keep their claim_id at epoch 1 and stay active; the migration abandons nothing.
|
|
477
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('claims')").all().map(x=>x.name));
|
|
478
|
+
for(const [name,type] of [['epoch','INTEGER NOT NULL DEFAULT 1'],['state',"TEXT NOT NULL DEFAULT 'active' CHECK(state IN ('active','abandoned'))"],['abandoned_at','TEXT'],['abandon_reason','TEXT']])
|
|
479
|
+
if(!columns.has(name)) this.db.exec(`ALTER TABLE claims ADD COLUMN ${name} ${type}`);
|
|
480
|
+
this.db.exec('PRAGMA user_version=20;');
|
|
481
|
+
}
|
|
482
|
+
if (version < 21) {
|
|
483
|
+
// Backfill runs once, inside this startup transaction, so a serving process never sees a half-filled table.
|
|
484
|
+
this.db.exec(lifecycleSchema);
|
|
485
|
+
backfillLifecycle(this.db);
|
|
486
|
+
this.db.exec('PRAGMA user_version=21;');
|
|
487
|
+
}
|
|
488
|
+
if (version < 22) {
|
|
489
|
+
// Who submitted a row and for which objective/revision; nullable, outside the payload and its hash. Old rows stay null
|
|
490
|
+
// until `dalan backfill-objectives` posts a tuple the server can verify.
|
|
491
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('assignments')").all().map(x=>x.name));
|
|
492
|
+
for(const [name,type] of [['objective_key','TEXT'],['revision','TEXT'],['task_kind','TEXT'],['source',`TEXT CHECK(source IN (${objectiveSources.map(x=>`'${x}'`).join(',')}))`]])
|
|
493
|
+
if(!columns.has(name)) this.db.exec(`ALTER TABLE assignments ADD COLUMN ${name} ${type}`);
|
|
494
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS assignments_objective ON assignments(objective_key,created_at);
|
|
495
|
+
PRAGMA user_version=22;`);
|
|
496
|
+
}
|
|
497
|
+
if (version < 23) {
|
|
498
|
+
// covers: once the JSON list of items a per-item re-announce event charged, for refunds. Unused since the flat queue
|
|
499
|
+
// re-wake (nothing is charged); kept so existing databases need no new migration. Always NULL on new rows.
|
|
500
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('notifications') WHERE name='covers'").get()) this.db.exec('ALTER TABLE notifications ADD COLUMN covers TEXT');
|
|
501
|
+
this.db.exec('PRAGMA user_version=23;');
|
|
502
|
+
}
|
|
503
|
+
if (version < 24) {
|
|
504
|
+
// wake_kind classifies availability event rows so re-wake reads assignment wake traffic without parsing bodies:
|
|
505
|
+
// submit (an assignment's own event, also the old per-item re-announces), rewake, owner_note, message. NULL on
|
|
506
|
+
// non-event rows. Partial indexes keep the per-tick re-wake queries independent of notification history.
|
|
507
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('notifications') WHERE name='wake_kind'").get()) this.db.exec("ALTER TABLE notifications ADD COLUMN wake_kind TEXT CHECK(wake_kind IN ('submit','rewake','owner_note','message'))");
|
|
508
|
+
this.db.exec(`UPDATE notifications SET wake_kind=CASE WHEN message_id IS NOT NULL THEN 'message' WHEN body LIKE '%"title":"Owner note note\\_%' ESCAPE '\\' THEN 'owner_note' ELSE 'submit' END WHERE kind='event' AND wake_kind IS NULL;
|
|
509
|
+
CREATE INDEX IF NOT EXISTS notifications_request_state ON notifications(request_id,state);
|
|
510
|
+
CREATE INDEX IF NOT EXISTS notifications_wake_gate ON notifications(subscription_id,state) WHERE wake_kind IN ('submit','rewake');
|
|
511
|
+
CREATE INDEX IF NOT EXISTS notifications_wake_time ON notifications(subscription_id,state,COALESCE(attempt_started_at,created_at)) WHERE wake_kind IN ('submit','rewake','owner_note');
|
|
512
|
+
CREATE INDEX IF NOT EXISTS notifications_wake_latest ON notifications(request_id,subscription_id,created_at) WHERE wake_kind IN ('submit','rewake');
|
|
513
|
+
PRAGMA user_version=24;`);
|
|
514
|
+
}
|
|
515
|
+
if (version < 25) {
|
|
516
|
+
// Usage breaks (the worker stops calling tools, e.g. a platform usage limit): one row per break, the open row (until NULL)
|
|
517
|
+
// is the current one; usage is the JSON snapshot of the 1h/6h/24h before since. worker_calls counts tool calls per
|
|
518
|
+
// subject per minute (kept 48 h) for that snapshot and the throttle. break_notices makes the owner notice once per
|
|
519
|
+
// break per target (a t3 thread, or one delivery=none request). Nothing existing changes: claims stay valid.
|
|
520
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS dot_breaks (id INTEGER PRIMARY KEY AUTOINCREMENT, since TEXT NOT NULL, until TEXT, reason TEXT NOT NULL, source TEXT NOT NULL CHECK(source IN ('owner','inferred')), end_source TEXT CHECK(end_source IN ('tool_call','owner')), usage TEXT NOT NULL, last_probe_at TEXT, start_alerted_at TEXT, end_alerted_at TEXT, created_at TEXT NOT NULL);
|
|
521
|
+
CREATE UNIQUE INDEX IF NOT EXISTS dot_breaks_one_active ON dot_breaks(COALESCE(until,'')) WHERE until IS NULL;
|
|
522
|
+
CREATE TABLE IF NOT EXISTS worker_calls (subject TEXT NOT NULL, minute INTEGER NOT NULL, count INTEGER NOT NULL, PRIMARY KEY(subject,minute));
|
|
523
|
+
CREATE INDEX IF NOT EXISTS worker_calls_minute ON worker_calls(minute);
|
|
524
|
+
CREATE TABLE IF NOT EXISTS break_notices (break_id INTEGER NOT NULL REFERENCES dot_breaks(id), target TEXT NOT NULL, request_ids TEXT NOT NULL, notification_id TEXT, created_at TEXT NOT NULL, PRIMARY KEY(break_id,target));
|
|
525
|
+
PRAGMA user_version=25;`);
|
|
526
|
+
}
|
|
527
|
+
if (version < 26) {
|
|
528
|
+
// Response-byte accounting: worker_calls gains a tool dimension and the serialized MCP response bytes per subject,
|
|
529
|
+
// tool and minute (kept 48 h). Rows from before keep their counts under tool 'unrecorded' with bytes NULL (never
|
|
530
|
+
// measured); bytes is never NULL on a newer row. Nothing else changes: claims stay valid.
|
|
531
|
+
this.db.exec(`CREATE TABLE worker_calls_v26 (subject TEXT NOT NULL, minute INTEGER NOT NULL, tool TEXT NOT NULL, count INTEGER NOT NULL DEFAULT 0, bytes INTEGER, PRIMARY KEY(subject,minute,tool));
|
|
532
|
+
INSERT INTO worker_calls_v26(subject,minute,tool,count,bytes) SELECT subject,minute,'unrecorded',count,NULL FROM worker_calls;
|
|
533
|
+
DROP TABLE worker_calls;
|
|
534
|
+
ALTER TABLE worker_calls_v26 RENAME TO worker_calls;
|
|
535
|
+
CREATE INDEX IF NOT EXISTS worker_calls_minute ON worker_calls(minute);
|
|
536
|
+
PRAGMA user_version=26;`);
|
|
537
|
+
}
|
|
538
|
+
if (version < 27) {
|
|
539
|
+
// Preparation expiry: valid_until mirrors the payload's (normalized ISO, NULL when absent or unparsable) so the sweep
|
|
540
|
+
// reads an index; cancelled_reason says why a row was cancelled ('expired' by the sweep, NULL for an owner cancel).
|
|
541
|
+
// Only open rows are backfilled; claims stay valid and nothing is cancelled here.
|
|
542
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('assignments')").all().map(x=>x.name));
|
|
543
|
+
for(const name of ['valid_until','cancelled_reason']) if(!columns.has(name)) this.db.exec(`ALTER TABLE assignments ADD COLUMN ${name} TEXT`);
|
|
544
|
+
const set=this.db.prepare('UPDATE assignments SET valid_until=? WHERE request_id=?');
|
|
545
|
+
for(const row of this.db.prepare("SELECT request_id,payload FROM assignments WHERE status IN ('queued','claimed') AND valid_until IS NULL").all()) { let v=null; try { v=validUntilOf(JSON.parse(row.payload)); } catch {} if(v) set.run(v,row.request_id); }
|
|
546
|
+
this.db.exec(`CREATE INDEX IF NOT EXISTS assignments_expiry ON assignments(status,valid_until);
|
|
547
|
+
PRAGMA user_version=27;`);
|
|
548
|
+
}
|
|
549
|
+
if (version < 28) {
|
|
550
|
+
// Byte limits learned from a usage break: 70% of the bytes its ledger shows (1 h and 24 h before since). Only ever lower.
|
|
551
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS learned_limits (name TEXT PRIMARY KEY CHECK(name IN ('response_bytes_per_hour','response_bytes_per_24h')), value INTEGER NOT NULL, break_id INTEGER, ledger_bytes INTEGER NOT NULL, at TEXT NOT NULL);
|
|
552
|
+
PRAGMA user_version=28;`);
|
|
553
|
+
}
|
|
554
|
+
if (version < 29) {
|
|
555
|
+
// learned_limits covers tool calls too (1 h and 24 h); the CHECK list cannot be altered in place, so rebuild.
|
|
556
|
+
this.db.exec(`CREATE TABLE learned_limits_v29 (name TEXT PRIMARY KEY CHECK(name IN ('response_bytes_per_hour','response_bytes_per_24h','tool_calls_per_hour','tool_calls_per_24h')), value INTEGER NOT NULL, break_id INTEGER, ledger_bytes INTEGER NOT NULL, at TEXT NOT NULL);
|
|
557
|
+
INSERT INTO learned_limits_v29 SELECT name,value,break_id,ledger_bytes,at FROM learned_limits;
|
|
558
|
+
DROP TABLE learned_limits; ALTER TABLE learned_limits_v29 RENAME TO learned_limits;
|
|
559
|
+
PRAGMA user_version=29;`);
|
|
560
|
+
}
|
|
561
|
+
if (version < 30) {
|
|
562
|
+
// learned_limits covers claims too: 70% of the busiest rolling hour of claims in the 24 h before a break.
|
|
563
|
+
this.db.exec(`CREATE TABLE learned_limits_v30 (name TEXT PRIMARY KEY CHECK(name IN ('response_bytes_per_hour','response_bytes_per_24h','tool_calls_per_hour','tool_calls_per_24h','claims_per_hour')), value INTEGER NOT NULL, break_id INTEGER, ledger_bytes INTEGER NOT NULL, at TEXT NOT NULL);
|
|
564
|
+
INSERT INTO learned_limits_v30 SELECT name,value,break_id,ledger_bytes,at FROM learned_limits;
|
|
565
|
+
DROP TABLE learned_limits; ALTER TABLE learned_limits_v30 RENAME TO learned_limits;
|
|
566
|
+
PRAGMA user_version=30;`);
|
|
567
|
+
}
|
|
568
|
+
if (version < 31) {
|
|
569
|
+
// The owner read a terminal row (any /get or /wait, peek included). Separate from the 'consumed' lifecycle event, which
|
|
570
|
+
// consumers that count owner reads and peek reads must not create; only workspace eviction reads this column.
|
|
571
|
+
const wcols=new Set(this.db.prepare("SELECT name FROM pragma_table_info('workspaces')").all().map(x=>x.name));
|
|
572
|
+
if(!wcols.has('fetched_at')) this.db.exec('ALTER TABLE workspaces ADD COLUMN fetched_at TEXT');
|
|
573
|
+
this.db.exec('PRAGMA user_version=31;');
|
|
574
|
+
}
|
|
575
|
+
if (version < 32) {
|
|
576
|
+
// A queued request whose claim the worker's reviewer denied, as a worker note reported it (the denial never reaches the bridge).
|
|
577
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS claim_denials (request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), at TEXT NOT NULL, reported_in TEXT NOT NULL, capacity INTEGER NOT NULL, note TEXT NOT NULL);
|
|
578
|
+
PRAGMA user_version=32;`);
|
|
579
|
+
}
|
|
580
|
+
if (version < 33) {
|
|
581
|
+
// How often list_pending offered a claimable item without a claim, and when that made it skipped_by_worker.
|
|
582
|
+
const cols=new Set(this.db.prepare("SELECT name FROM pragma_table_info('assignments')").all().map(x=>x.name));
|
|
583
|
+
for(const [name,type] of [['listed_count','INTEGER NOT NULL DEFAULT 0'],['last_listed_at','TEXT'],['skipped_by_dot_at','TEXT']]) if(!cols.has(name)) this.db.exec(`ALTER TABLE assignments ADD COLUMN ${name} ${type}`);
|
|
584
|
+
this.db.exec('PRAGMA user_version=33;');
|
|
585
|
+
}
|
|
586
|
+
if (version < 34) {
|
|
587
|
+
// The signals behind skipped_by_worker: when an item last appeared in a list_pending answer, when it first sat in the
|
|
588
|
+
// claimable window, and how many claims of items listed after it the worker made meanwhile.
|
|
589
|
+
const cols=new Set(this.db.prepare("SELECT name FROM pragma_table_info('assignments')").all().map(x=>x.name));
|
|
590
|
+
for(const [name,type] of [['last_seen_listed_at','TEXT'],['eligible_since','TEXT'],['passed_over','INTEGER NOT NULL DEFAULT 0']]) if(!cols.has(name)) this.db.exec(`ALTER TABLE assignments ADD COLUMN ${name} ${type}`);
|
|
591
|
+
this.db.exec('PRAGMA user_version=34;');
|
|
592
|
+
}
|
|
593
|
+
if(version<35) {
|
|
594
|
+
// The base build supported exactly one worker, 'dot'. Owner-created targets therefore are 'dot'. A subject-bearing
|
|
595
|
+
// fact is 'dot' only when its persisted subject is allowed for this deployment; all other attribution is unknown.
|
|
596
|
+
// Never infer identity from the new connection map, or from whoever holds the claim today.
|
|
597
|
+
// The two target_worker columns are added with an empty default, then every row that exists at this point is set
|
|
598
|
+
// to worker. A fresh database has no rows here, so its schema text and its rows never name worker; only a database that
|
|
599
|
+
// held pre-35 rows gets 'dot', and only on those rows. Every insert names target_worker, so the default is never used.
|
|
600
|
+
// Databases that already reached version 35 under the older step keep DEFAULT 'dot' in their stored schema text:
|
|
601
|
+
// SQLite cannot change a column default without rebuilding the table. That is the only schema difference between
|
|
602
|
+
// a fresh and an upgraded database.
|
|
603
|
+
this.db.exec(`CREATE TABLE schema_migrations (identity TEXT PRIMARY KEY);
|
|
604
|
+
INSERT INTO schema_migrations VALUES('s1v2-worker-facts-20261022');
|
|
605
|
+
ALTER TABLE assignments ADD COLUMN target_worker TEXT NOT NULL DEFAULT '';
|
|
606
|
+
ALTER TABLE messages ADD COLUMN target_worker TEXT NOT NULL DEFAULT '';
|
|
607
|
+
UPDATE assignments SET target_worker='dot';
|
|
608
|
+
UPDATE messages SET target_worker='dot';
|
|
609
|
+
ALTER TABLE claims ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
610
|
+
ALTER TABLE claims ADD COLUMN lane_key TEXT NOT NULL DEFAULT 'unknown';
|
|
611
|
+
ALTER TABLE claims ADD COLUMN lane_scope TEXT NOT NULL DEFAULT 'subject';
|
|
612
|
+
ALTER TABLE subscriptions ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
613
|
+
ALTER TABLE subscriptions ADD COLUMN connection TEXT;
|
|
614
|
+
ALTER TABLE reports ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
615
|
+
ALTER TABLE progress ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
616
|
+
ALTER TABLE claim_denials ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
617
|
+
ALTER TABLE lifecycle_events ADD COLUMN worker TEXT NOT NULL DEFAULT 'unknown';
|
|
618
|
+
ALTER TABLE artifacts ADD COLUMN client_artifact_id TEXT;
|
|
619
|
+
UPDATE artifacts SET client_artifact_id=id WHERE kind='upload';
|
|
620
|
+
CREATE UNIQUE INDEX artifacts_alias ON artifacts(request_id,client_artifact_id);
|
|
621
|
+
DROP TRIGGER lifecycle_events_no_update;`);
|
|
622
|
+
const subjects=this.allowedDotSubjects??this.db.prepare('SELECT subject FROM claims UNION SELECT principal FROM subscriptions UNION SELECT subject FROM worker_activity UNION SELECT subject FROM worker_calls').all().map(r=>r.subject);
|
|
623
|
+
for(const subject of subjects) {
|
|
624
|
+
this.db.prepare("UPDATE claims SET worker='dot',lane_key=subject WHERE subject=?").run(subject);
|
|
625
|
+
this.db.prepare("UPDATE subscriptions SET worker='dot' WHERE principal=?").run(subject);
|
|
626
|
+
this.db.prepare("UPDATE lifecycle_events SET worker='dot' WHERE actor=? OR actor='system' AND claim_id IN (SELECT claim_id FROM claims WHERE worker='dot')").run(`dot:${subject}`);
|
|
627
|
+
}
|
|
628
|
+
this.db.exec(`UPDATE reports SET worker=COALESCE((SELECT worker FROM claims c WHERE c.claim_id=reports.claim_id),'unknown');
|
|
629
|
+
UPDATE progress SET worker=COALESCE((SELECT worker FROM claims c WHERE c.request_id=progress.request_id AND progress.created_at>=c.claimed_at),'unknown');
|
|
630
|
+
UPDATE claim_denials SET worker=COALESCE((SELECT worker FROM claims c WHERE c.request_id=claim_denials.reported_in AND claim_denials.at>=c.claimed_at),'unknown');
|
|
631
|
+
CREATE TRIGGER lifecycle_events_no_update BEFORE UPDATE ON lifecycle_events BEGIN SELECT RAISE(ABORT,'lifecycle events are append-only'); END;
|
|
632
|
+
CREATE TABLE worker_activity_v35 (worker TEXT NOT NULL DEFAULT 'unknown',subject TEXT NOT NULL,last_call_at TEXT NOT NULL,last_list_pending_at TEXT,PRIMARY KEY(worker,subject));
|
|
633
|
+
CREATE TABLE worker_calls_v35 (worker TEXT NOT NULL DEFAULT 'unknown',subject TEXT NOT NULL,minute INTEGER NOT NULL,tool TEXT NOT NULL,count INTEGER NOT NULL DEFAULT 0,bytes INTEGER,PRIMARY KEY(worker,subject,minute,tool));`);
|
|
634
|
+
const known=new Set(subjects);
|
|
635
|
+
for(const r of this.db.prepare('SELECT * FROM worker_activity').all()) this.db.prepare('INSERT INTO worker_activity_v35 VALUES(?,?,?,?)').run(known.has(r.subject)?'dot':'unknown',r.subject,r.last_call_at,r.last_list_pending_at);
|
|
636
|
+
for(const r of this.db.prepare('SELECT * FROM worker_calls').all()) this.db.prepare('INSERT INTO worker_calls_v35 VALUES(?,?,?,?,?,?)').run(known.has(r.subject)?'dot':'unknown',r.subject,r.minute,r.tool,r.count,r.bytes);
|
|
637
|
+
this.db.exec(`DROP TABLE worker_activity; ALTER TABLE worker_activity_v35 RENAME TO worker_activity;
|
|
638
|
+
DROP TABLE worker_calls; ALTER TABLE worker_calls_v35 RENAME TO worker_calls;
|
|
639
|
+
CREATE INDEX worker_calls_minute ON worker_calls(minute); PRAGMA user_version=35;`);
|
|
640
|
+
for(const [table,column] of [['assignments','target_worker'],['messages','target_worker'],['claims','worker'],['claims','lane_scope'],['subscriptions','worker'],['subscriptions','connection'],['reports','worker'],['progress','worker'],['claim_denials','worker'],['worker_calls','worker'],['worker_activity','worker']])
|
|
641
|
+
this.db.exec(`CREATE TRIGGER ${table}_${column}_immutable BEFORE UPDATE OF ${column} ON ${table} BEGIN SELECT RAISE(ABORT,'${table}.${column} is immutable'); END;`);
|
|
642
|
+
this.db.exec("CREATE TRIGGER claims_lane_key_epoch BEFORE UPDATE OF lane_key ON claims WHEN NEW.epoch<=OLD.epoch OR NEW.lane_key<>CASE NEW.lane_scope WHEN 'subject' THEN NEW.subject ELSE NEW.worker END BEGIN SELECT RAISE(ABORT,'claim lane key is recorded per epoch'); END;");
|
|
643
|
+
}
|
|
644
|
+
// Earlier review builds of this same, unreleased migration stored a subscription lane. It is derived state,
|
|
645
|
+
// not an attribution fact. Remove it on reopen too; the identity check above still rejects abandoned schemas.
|
|
646
|
+
if(this.db.prepare("SELECT 1 FROM pragma_table_info('subscriptions') WHERE name='lane_key'").get())
|
|
647
|
+
this.db.exec('DROP TRIGGER IF EXISTS subscriptions_lane_key_immutable; ALTER TABLE subscriptions DROP COLUMN lane_key;');
|
|
648
|
+
if (version < 37) {
|
|
649
|
+
// Per-job execution capability. Like target_worker it is a column, never payload, so payload hashes and retry identity do
|
|
650
|
+
// not change. Every older row ran checks on the host, so the default is 'host'; a rollback to older code ignores the columns.
|
|
651
|
+
// required_capabilities is a JSON list of capability names the host backend must declare verified, or NULL.
|
|
652
|
+
// check_runs.evidence is the bridge-observed record of one host check (workspace.mjs buildEvidence); older rows have none.
|
|
653
|
+
const has=(table,name)=>this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(name);
|
|
654
|
+
if(!has('assignments','execution')) this.db.exec("ALTER TABLE assignments ADD COLUMN execution TEXT NOT NULL DEFAULT 'host'");
|
|
655
|
+
if(!has('assignments','required_capabilities')) this.db.exec('ALTER TABLE assignments ADD COLUMN required_capabilities TEXT');
|
|
656
|
+
if(!has('check_runs','evidence')) this.db.exec('ALTER TABLE check_runs ADD COLUMN evidence TEXT');
|
|
657
|
+
this.db.exec('PRAGMA user_version=37;');
|
|
658
|
+
}
|
|
659
|
+
if (version < 38) {
|
|
660
|
+
// Supervisor-verified stop: after each sandbox phase the bridge scans for what is left of it and records the answer here.
|
|
661
|
+
// stop_verified is NULL until a phase ends, 1 while every ended phase was verified empty, 0 once any phase was not.
|
|
662
|
+
const has=(table,name)=>this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(name);
|
|
663
|
+
if(!has('check_jobs','stop_verified')) this.db.exec('ALTER TABLE check_jobs ADD COLUMN stop_verified INTEGER');
|
|
664
|
+
if(!has('check_jobs','stop_evidence')) this.db.exec('ALTER TABLE check_jobs ADD COLUMN stop_evidence TEXT');
|
|
665
|
+
this.db.exec('PRAGMA user_version=38;');
|
|
666
|
+
}
|
|
667
|
+
if (version < 39) {
|
|
668
|
+
// Per-claim record of what the worker did on this assignment, so a silent drop can be read from the claim.
|
|
669
|
+
const has=(table,name)=>this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(name);
|
|
670
|
+
for(const [name,type] of [['tool_calls','INTEGER NOT NULL DEFAULT 0'],['last_tool','TEXT'],['last_tool_at','TEXT'],['last_tool_error','TEXT'],['first_workspace_tool_at','TEXT']])
|
|
671
|
+
if(!has('claims',name)) this.db.exec(`ALTER TABLE claims ADD COLUMN ${name} ${type}`);
|
|
672
|
+
this.db.exec('PRAGMA user_version=39;');
|
|
673
|
+
}
|
|
674
|
+
if (version < 40) {
|
|
675
|
+
// When the owner read a cancelled row (get or wait, not a peek), so `dalan inbox` can list cancellations nobody has
|
|
676
|
+
// seen. Finished rows use the 'consumed' lifecycle event. Rows cancelled before this column existed count as read.
|
|
677
|
+
const has=(table,name)=>this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(name);
|
|
678
|
+
if(!has('assignments','owner_read_at')) this.db.exec('ALTER TABLE assignments ADD COLUMN owner_read_at TEXT');
|
|
679
|
+
this.db.exec("UPDATE assignments SET owner_read_at=cancelled_at WHERE status='cancelled' AND owner_read_at IS NULL; PRAGMA user_version=40;");
|
|
680
|
+
}
|
|
681
|
+
if (version < 41) {
|
|
682
|
+
// Where an upload first came from. rebindClaim moves claim_id on every new epoch; origin_* never moves, so the owner can see
|
|
683
|
+
// that a finish cites bytes an earlier epoch sealed. NULL on rows made before this column existed (origin unknown).
|
|
684
|
+
const has=(table,name)=>this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(name);
|
|
685
|
+
if(!has('artifacts','origin_claim_id')) this.db.exec('ALTER TABLE artifacts ADD COLUMN origin_claim_id TEXT');
|
|
686
|
+
if(!has('artifacts','origin_epoch')) this.db.exec('ALTER TABLE artifacts ADD COLUMN origin_epoch INTEGER');
|
|
687
|
+
this.db.exec('PRAGMA user_version=41;');
|
|
688
|
+
}
|
|
689
|
+
if (version < 42) {
|
|
690
|
+
// Output a worker files after cancel. Audit only: apart from reports (results), one row per claim, size-bounded.
|
|
691
|
+
// Reports with late=1 written before this table existed stay where they are.
|
|
692
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS late_evidence (request_id TEXT NOT NULL REFERENCES assignments(request_id), claim_id TEXT NOT NULL, epoch INTEGER, worker TEXT NOT NULL, outcome TEXT NOT NULL, summary TEXT NOT NULL, result TEXT NOT NULL, full_sha256 TEXT NOT NULL, truncated INTEGER NOT NULL, created_at TEXT NOT NULL, PRIMARY KEY(request_id,claim_id));
|
|
693
|
+
PRAGMA user_version=42;`);
|
|
694
|
+
}
|
|
695
|
+
if (version < 43) {
|
|
696
|
+
// A stable claimant can have overlapping runs. Only one acquisition may retry an active claim.
|
|
697
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='acquisition_id'").get()) this.db.exec('ALTER TABLE claims ADD COLUMN acquisition_id TEXT');
|
|
698
|
+
this.db.exec('PRAGMA user_version=43;');
|
|
699
|
+
}
|
|
700
|
+
if (version < 44) {
|
|
701
|
+
// What the owner decided about a finished result (accepted, applied, useful_no_change, useful_negative, not_useful) or the
|
|
702
|
+
// stale sweep decided for them ('stale', actor system). Append-only: the latest row is the decision, the rest stay as history.
|
|
703
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS decisions (id INTEGER PRIMARY KEY AUTOINCREMENT, request_id TEXT NOT NULL REFERENCES assignments(request_id), decision TEXT NOT NULL CHECK(decision IN ('accepted','applied','useful_no_change','useful_negative','not_useful','stale')), note TEXT, actor TEXT NOT NULL CHECK(actor IN ('owner','system')), via TEXT NOT NULL, at TEXT NOT NULL);
|
|
704
|
+
CREATE INDEX IF NOT EXISTS decisions_request ON decisions(request_id,id);
|
|
705
|
+
CREATE TRIGGER IF NOT EXISTS decisions_no_update BEFORE UPDATE ON decisions BEGIN SELECT RAISE(ABORT,'decisions are append-only'); END;
|
|
706
|
+
CREATE TRIGGER IF NOT EXISTS decisions_no_delete BEFORE DELETE ON decisions BEGIN SELECT RAISE(ABORT,'decisions are append-only'); END;
|
|
707
|
+
`);
|
|
708
|
+
// Persist the existing read projection, not newly verified owner authority.
|
|
709
|
+
// In particular, LIKE and actor='owner' deliberately match latestDecision;
|
|
710
|
+
// an accepted reason saying 'applied' is still only an accepted projection.
|
|
711
|
+
const explicit = new Set(this.db.prepare('SELECT DISTINCT request_id FROM decisions').all().map(r => r.request_id));
|
|
712
|
+
// Lifecycle history may outlive its assignment; leave such rows untouched.
|
|
713
|
+
// Only existing assignments can own durable decisions under the existing FK.
|
|
714
|
+
const legacy = this.db.prepare("SELECT e.request_id,e.type,e.at,e.reason FROM lifecycle_events e JOIN assignments a ON a.request_id=e.request_id WHERE e.type='accepted' OR e.type='consumed' AND e.reason LIKE 'rejected%' ORDER BY e.id").all();
|
|
715
|
+
const insert = this.db.prepare("INSERT INTO decisions(request_id,decision,note,actor,via,at) VALUES(?,?,?,'owner','legacy-projection',?)");
|
|
716
|
+
for (const row of legacy) {
|
|
717
|
+
if (!explicit.has(row.request_id)) insert.run(row.request_id, row.type === 'accepted' ? 'accepted' : 'not_useful', row.reason, row.at);
|
|
718
|
+
}
|
|
719
|
+
this.db.exec('PRAGMA user_version=44;');
|
|
720
|
+
}
|
|
721
|
+
if (version < 45) {
|
|
722
|
+
// Add nullable validity-window provenance. Historical rows stay NULL because their origin is unknown.
|
|
723
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='valid_until_source'").get()) this.db.exec('ALTER TABLE assignments ADD COLUMN valid_until_source TEXT');
|
|
724
|
+
this.db.exec('PRAGMA user_version=45;');
|
|
725
|
+
}
|
|
726
|
+
if(version<46) {
|
|
727
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('notifications')").all().map(x=>x.name));
|
|
728
|
+
for(const [name,type] of [['terminal_at','TEXT'],['terminal_reason','TEXT']]) if(!columns.has(name)) this.db.exec(`ALTER TABLE notifications ADD COLUMN ${name} ${type}`);
|
|
729
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS uncertain_delivery_alerts(notification_id TEXT PRIMARY KEY,request_id TEXT,created_at TEXT NOT NULL,logged_at TEXT,published_at TEXT,reason TEXT NOT NULL);
|
|
730
|
+
PRAGMA user_version=46;`);
|
|
731
|
+
}
|
|
732
|
+
if(version<47) {
|
|
733
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS integration_candidates (
|
|
734
|
+
candidate_id TEXT PRIMARY KEY,
|
|
735
|
+
request_id TEXT NOT NULL,
|
|
736
|
+
kind TEXT NOT NULL CHECK(kind IN ('patch','other')),
|
|
737
|
+
linked_from TEXT REFERENCES integration_candidates(candidate_id),
|
|
738
|
+
patch BLOB NOT NULL,
|
|
739
|
+
patch_digest TEXT NOT NULL,
|
|
740
|
+
patch_base_sha TEXT NOT NULL,
|
|
741
|
+
target_sha TEXT NOT NULL,
|
|
742
|
+
github_repo TEXT,
|
|
743
|
+
created_at TEXT NOT NULL,
|
|
744
|
+
CHECK(linked_from IS NULL OR linked_from<>candidate_id)
|
|
745
|
+
);
|
|
746
|
+
CREATE INDEX IF NOT EXISTS integration_candidates_request ON integration_candidates(request_id,created_at);
|
|
747
|
+
CREATE TABLE IF NOT EXISTS integration_verifications (
|
|
748
|
+
verification_id TEXT PRIMARY KEY,
|
|
749
|
+
candidate_id TEXT NOT NULL REFERENCES integration_candidates(candidate_id),
|
|
750
|
+
patch_digest TEXT NOT NULL,
|
|
751
|
+
patch_base_sha TEXT NOT NULL,
|
|
752
|
+
target_sha TEXT NOT NULL,
|
|
753
|
+
target_ref TEXT NOT NULL,
|
|
754
|
+
status TEXT NOT NULL CHECK(status IN ('verified','failed','conflict')),
|
|
755
|
+
checks_json TEXT NOT NULL,
|
|
756
|
+
error TEXT,
|
|
757
|
+
recorded_at TEXT NOT NULL
|
|
758
|
+
);
|
|
759
|
+
CREATE INDEX IF NOT EXISTS integration_verifications_candidate ON integration_verifications(candidate_id,recorded_at);
|
|
760
|
+
CREATE TRIGGER IF NOT EXISTS integration_candidates_no_update BEFORE UPDATE ON integration_candidates BEGIN SELECT RAISE(ABORT,'integration candidates are immutable'); END;
|
|
761
|
+
CREATE TRIGGER IF NOT EXISTS integration_candidates_no_delete BEFORE DELETE ON integration_candidates BEGIN SELECT RAISE(ABORT,'integration candidates are immutable'); END;
|
|
762
|
+
CREATE TRIGGER IF NOT EXISTS integration_verifications_no_update BEFORE UPDATE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
763
|
+
CREATE TRIGGER IF NOT EXISTS integration_verifications_no_delete BEFORE DELETE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
764
|
+
PRAGMA user_version=47;`);
|
|
765
|
+
}
|
|
766
|
+
if(version<48) {
|
|
767
|
+
this.db.exec(`DROP TRIGGER IF EXISTS integration_verifications_no_update;
|
|
768
|
+
DROP TRIGGER IF EXISTS integration_verifications_no_delete;
|
|
769
|
+
ALTER TABLE integration_verifications RENAME TO integration_verifications_old;
|
|
770
|
+
CREATE TABLE integration_verifications (
|
|
771
|
+
verification_id TEXT PRIMARY KEY,
|
|
772
|
+
candidate_id TEXT NOT NULL REFERENCES integration_candidates(candidate_id),
|
|
773
|
+
patch_digest TEXT NOT NULL, patch_base_sha TEXT NOT NULL, target_sha TEXT NOT NULL,
|
|
774
|
+
target_ref TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('verified','failed','conflict','skipped')),
|
|
775
|
+
checks_json TEXT NOT NULL, error TEXT, recorded_at TEXT NOT NULL
|
|
776
|
+
);
|
|
777
|
+
INSERT INTO integration_verifications SELECT * FROM integration_verifications_old;
|
|
778
|
+
DROP TABLE integration_verifications_old;
|
|
779
|
+
CREATE INDEX integration_verifications_candidate ON integration_verifications(candidate_id,recorded_at);
|
|
780
|
+
CREATE TRIGGER integration_verifications_no_update BEFORE UPDATE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
781
|
+
CREATE TRIGGER integration_verifications_no_delete BEFORE DELETE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
782
|
+
PRAGMA user_version=48;`);
|
|
783
|
+
}
|
|
784
|
+
if(version<49) {
|
|
785
|
+
this.db.exec(`DROP TRIGGER IF EXISTS integration_verifications_no_update;
|
|
786
|
+
DROP TRIGGER IF EXISTS integration_verifications_no_delete;
|
|
787
|
+
ALTER TABLE integration_verifications RENAME TO integration_verifications_old;
|
|
788
|
+
CREATE TABLE integration_verifications (
|
|
789
|
+
verification_id TEXT PRIMARY KEY,
|
|
790
|
+
candidate_id TEXT NOT NULL REFERENCES integration_candidates(candidate_id),
|
|
791
|
+
patch_digest TEXT NOT NULL, patch_base_sha TEXT NOT NULL, target_sha TEXT NOT NULL,
|
|
792
|
+
target_ref TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('verified','failed','conflict','skipped','owner_approval_required')),
|
|
793
|
+
checks_json TEXT NOT NULL, error TEXT, recorded_at TEXT NOT NULL
|
|
794
|
+
);
|
|
795
|
+
INSERT INTO integration_verifications SELECT * FROM integration_verifications_old;
|
|
796
|
+
DROP TABLE integration_verifications_old;
|
|
797
|
+
CREATE INDEX integration_verifications_candidate ON integration_verifications(candidate_id,recorded_at);
|
|
798
|
+
CREATE TRIGGER integration_verifications_no_update BEFORE UPDATE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
799
|
+
CREATE TRIGGER integration_verifications_no_delete BEFORE DELETE ON integration_verifications BEGIN SELECT RAISE(ABORT,'integration verifications are append-only'); END;
|
|
800
|
+
PRAGMA user_version=49;`);
|
|
801
|
+
}
|
|
802
|
+
if(version<50) {
|
|
803
|
+
// Legacy alert timestamps do not prove that a configured publisher accepted a notice.
|
|
804
|
+
for(const [table,column] of [['alert_episodes','attention_sent_at'],['dot_breaks','alert_first_observed_at'],['dot_breaks','attention_published_at']]) {
|
|
805
|
+
if(!this.db.prepare(`SELECT 1 FROM pragma_table_info('${table}') WHERE name=?`).get(column))this.db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} TEXT`);
|
|
806
|
+
}
|
|
807
|
+
this.db.exec('PRAGMA user_version=50;');
|
|
808
|
+
}
|
|
809
|
+
// Version 51 fences older servers before they can write plaintext to encrypted AS state.
|
|
810
|
+
if(version<51) this.db.exec('PRAGMA user_version=51;');
|
|
811
|
+
if(version<52 && !this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subscription_storage_meta'").get()) {
|
|
812
|
+
this.db.exec('CREATE TABLE subscription_storage_meta (id INTEGER PRIMARY KEY CHECK(id=1), state TEXT NOT NULL, verifier TEXT NOT NULL); DROP TRIGGER subscriptions_connection_immutable');
|
|
813
|
+
for (const sub of this.db.prepare('SELECT id,secret,connection FROM subscriptions').all()) {
|
|
814
|
+
if (sub.connection !== null) { try { JSON.parse(sub.connection); } catch { throw new Error('legacy subscription connection is invalid'); } }
|
|
815
|
+
this.db.prepare('UPDATE subscriptions SET secret=?,connection=? WHERE id=?').run(this.sealSubscription(sub.id, 'secret', sub.secret), sub.connection === null ? null : this.sealSubscription(sub.id, 'connection', sub.connection), sub.id);
|
|
816
|
+
}
|
|
817
|
+
this.db.exec("CREATE TRIGGER subscriptions_connection_immutable BEFORE UPDATE OF connection ON subscriptions BEGIN SELECT RAISE(ABORT,'subscriptions.connection is immutable'); END");
|
|
818
|
+
this.db.prepare("INSERT INTO subscription_storage_meta VALUES(1,'cleanup',?)").run(this.subscriptionCodec.seal('dot-bridge subscriptions v1', 'verifier'));
|
|
819
|
+
}
|
|
820
|
+
if(version<52) {
|
|
821
|
+
this.validateSubscriptionStorage();
|
|
822
|
+
this.db.exec('PRAGMA user_version=52;');
|
|
823
|
+
}
|
|
824
|
+
if(version<53) {
|
|
825
|
+
// Pre-migration grants inherit the configured duration once.
|
|
826
|
+
const columns=new Set(this.db.prepare("SELECT name FROM pragma_table_info('claims')").all().map(row=>row.name));
|
|
827
|
+
if(!columns.has('lease_ms')) this.db.exec('ALTER TABLE claims ADD COLUMN lease_ms INTEGER');
|
|
828
|
+
this.db.prepare('UPDATE claims SET lease_ms=? WHERE lease_ms IS NULL').run(this.limits.leaseMs);
|
|
829
|
+
this.db.exec('PRAGMA user_version=53;');
|
|
830
|
+
}
|
|
831
|
+
if(version<54) this.db.exec(`CREATE TABLE IF NOT EXISTS owner_submit_commands(request_id TEXT PRIMARY KEY REFERENCES assignments(request_id), key_digest TEXT NOT NULL, intent_digest TEXT NOT NULL, receipt TEXT NOT NULL, owner_hash TEXT NOT NULL);
|
|
832
|
+
PRAGMA user_version=54;`);
|
|
833
|
+
if(version<55) this.db.exec(`CREATE TABLE job_questions (
|
|
834
|
+
request_id TEXT NOT NULL REFERENCES assignments(request_id), question_id TEXT NOT NULL,
|
|
835
|
+
claim_id TEXT NOT NULL, epoch INTEGER NOT NULL, worker TEXT NOT NULL, subject TEXT NOT NULL,
|
|
836
|
+
text TEXT NOT NULL, asked_at TEXT NOT NULL, answer TEXT, answered_at TEXT, consumed_at TEXT,
|
|
837
|
+
PRIMARY KEY(request_id,question_id));
|
|
838
|
+
CREATE TABLE question_answer_wakes (
|
|
839
|
+
notification_id TEXT PRIMARY KEY REFERENCES notifications(id),
|
|
840
|
+
request_id TEXT NOT NULL, question_id TEXT NOT NULL, epoch INTEGER NOT NULL);
|
|
841
|
+
PRAGMA user_version=55;`);
|
|
842
|
+
if(version<56) {
|
|
843
|
+
migrateClaimCommands(this.db);
|
|
844
|
+
this.db.exec(`CREATE TABLE protocol_jobs(request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),settings TEXT NOT NULL);
|
|
845
|
+
CREATE TABLE protocol_events(request_id TEXT NOT NULL REFERENCES assignments(request_id),seq INTEGER NOT NULL,event_type TEXT NOT NULL,at TEXT NOT NULL,epoch INTEGER NOT NULL,revision INTEGER NOT NULL,state TEXT NOT NULL,details TEXT NOT NULL,PRIMARY KEY(request_id,seq));
|
|
846
|
+
ALTER TABLE claims ADD COLUMN lease_deadline_at TEXT;
|
|
847
|
+
PRAGMA user_version=56;`);
|
|
848
|
+
migrateArtifactJournal(this.db);
|
|
849
|
+
migrateResultBindings(this.db);
|
|
850
|
+
migrateJobRetention(this.db);
|
|
851
|
+
migrateProtocolOwnerWaiters(this.db);
|
|
852
|
+
}
|
|
853
|
+
if(version<57) {
|
|
854
|
+
migrateProtocolDelivery(this.db);
|
|
855
|
+
migrateProtocolStopObserver(this.db);
|
|
856
|
+
this.db.exec('PRAGMA user_version=57');
|
|
857
|
+
}
|
|
858
|
+
if(version<58) this.db.exec(`CREATE TABLE submit_supersedes(
|
|
859
|
+
request_id TEXT PRIMARY KEY REFERENCES assignments(request_id),
|
|
860
|
+
target_id TEXT NOT NULL UNIQUE REFERENCES assignments(request_id),
|
|
861
|
+
created_at TEXT NOT NULL,
|
|
862
|
+
CHECK(request_id<>target_id));
|
|
863
|
+
PRAGMA user_version=58;`);
|
|
864
|
+
if(version<59) {
|
|
865
|
+
// Preparation-expiry requeues: how many times a learned deadline was refreshed. Existing rows default to 0, i.e. a
|
|
866
|
+
// full retry budget; no deadline is retimed here and claims stay valid.
|
|
867
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='expiry_requeues'").get()) this.db.exec('ALTER TABLE assignments ADD COLUMN expiry_requeues INTEGER NOT NULL DEFAULT 0');
|
|
868
|
+
this.db.exec('PRAGMA user_version=59;');
|
|
869
|
+
}
|
|
870
|
+
if(version<60) {
|
|
871
|
+
this.db.exec(
|
|
872
|
+
"CREATE TABLE IF NOT EXISTS destination_approvals(request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,revision TEXT NOT NULL,snapshot TEXT NOT NULL,actor TEXT NOT NULL,approved_at TEXT NOT NULL);"+
|
|
873
|
+
"CREATE TRIGGER IF NOT EXISTS destination_approvals_immutable BEFORE UPDATE ON destination_approvals BEGIN SELECT RAISE(ABORT,'destination approval is immutable'); END;"+
|
|
874
|
+
"CREATE TRIGGER IF NOT EXISTS destination_approvals_no_delete BEFORE DELETE ON destination_approvals WHEN EXISTS(SELECT 1 FROM assignments WHERE request_id=OLD.request_id) BEGIN SELECT RAISE(ABORT,'destination approval is immutable'); END;"+
|
|
875
|
+
"CREATE TABLE IF NOT EXISTS destination_blocks(request_id TEXT PRIMARY KEY REFERENCES assignments(request_id) ON DELETE CASCADE,body TEXT NOT NULL);");
|
|
876
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='destination_revision'").get()) this.db.exec('ALTER TABLE claims ADD COLUMN destination_revision TEXT');
|
|
877
|
+
this.db.exec('PRAGMA user_version=60;');
|
|
878
|
+
}
|
|
879
|
+
if(version<61) {
|
|
880
|
+
// The built-in connection a grant was given to. NULL means unknown (older grants) or external OAuth; the
|
|
881
|
+
// column is never inferred from the current live set.
|
|
882
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='connection_id'").get()) this.db.exec('ALTER TABLE claims ADD COLUMN connection_id TEXT');
|
|
883
|
+
this.db.exec('PRAGMA user_version=61;');
|
|
884
|
+
}
|
|
885
|
+
if(version<62) {
|
|
886
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='lease_boot_id'").get()) this.db.exec('ALTER TABLE claims ADD COLUMN lease_boot_id TEXT');
|
|
887
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('claims') WHERE name='lease_deadline_monotonic_ms'").get()) this.db.exec('ALTER TABLE claims ADD COLUMN lease_deadline_monotonic_ms REAL');
|
|
888
|
+
this.db.exec('PRAGMA user_version=62;');
|
|
889
|
+
}
|
|
890
|
+
if(version<63) {
|
|
891
|
+
// The owner-managed tool registry: tools, per-worker grants, an argument-free audit log, and a durable outbox
|
|
892
|
+
// for messages a handler could not deliver yet.
|
|
893
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS registered_tools (name TEXT PRIMARY KEY, description TEXT NOT NULL, input_schema TEXT NOT NULL, class TEXT NOT NULL CHECK(class IN ('read','write')), handler TEXT NOT NULL, schema_hash TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1, created_at TEXT NOT NULL);
|
|
894
|
+
CREATE TABLE IF NOT EXISTS tool_grants (tool TEXT NOT NULL REFERENCES registered_tools(name) ON DELETE CASCADE, worker TEXT NOT NULL, granted_at TEXT NOT NULL, PRIMARY KEY(tool,worker));
|
|
895
|
+
CREATE TABLE IF NOT EXISTS tool_registry_log (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, kind TEXT NOT NULL, tool TEXT, worker TEXT, args_digest TEXT, outcome TEXT NOT NULL, schema_hash TEXT);
|
|
896
|
+
CREATE TABLE IF NOT EXISTS tool_outbox (id INTEGER PRIMARY KEY AUTOINCREMENT, tool TEXT NOT NULL, worker TEXT NOT NULL, kind TEXT NOT NULL, text TEXT NOT NULL, created_at TEXT NOT NULL, sent_at TEXT, thread_id TEXT NOT NULL DEFAULT '');
|
|
897
|
+
PRAGMA user_version=63;`);
|
|
898
|
+
}
|
|
899
|
+
// Registry hardening, still schema 63 (unreleased). Idempotent, so a database already at 63 gains the tables.
|
|
900
|
+
// tool_idempotency keeps one outcome per (worker, tool, key) for seven days, and a pending row holds a lease; tool_post_log is the argument-free
|
|
901
|
+
// record of every t3_post attempt (message kind and outcome, never text); tool_registry_meta holds the
|
|
902
|
+
// monotonic registry version.
|
|
903
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS tool_idempotency (worker TEXT NOT NULL, tool TEXT NOT NULL, key TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('pending','done')), outcome TEXT, created_at TEXT NOT NULL, lease_expires_at TEXT, completed_at TEXT, PRIMARY KEY(worker,tool,key));
|
|
904
|
+
CREATE TABLE IF NOT EXISTS tool_post_log (id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, tool TEXT NOT NULL, worker TEXT NOT NULL, message_kind TEXT NOT NULL, outcome TEXT NOT NULL);
|
|
905
|
+
CREATE INDEX IF NOT EXISTS tool_post_log_tool_at ON tool_post_log(tool, at);
|
|
906
|
+
CREATE TABLE IF NOT EXISTS tool_registry_meta (key TEXT PRIMARY KEY, value INTEGER NOT NULL);`);
|
|
907
|
+
// lease_expires_at: a pending row holds a lease; a NULL lease (older build) counts as expired.
|
|
908
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_idempotency') WHERE name='lease_expires_at'").get()) this.db.exec('ALTER TABLE tool_idempotency ADD COLUMN lease_expires_at TEXT');
|
|
909
|
+
// completed_at: when the result was stored; the seven-day retention counts from it (NULL falls back to created_at).
|
|
910
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_idempotency') WHERE name='completed_at'").get()) this.db.exec('ALTER TABLE tool_idempotency ADD COLUMN completed_at TEXT');
|
|
911
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_outbox') WHERE name='idempotency_key'").get()) this.db.exec('ALTER TABLE tool_outbox ADD COLUMN idempotency_key TEXT');
|
|
912
|
+
// args_digest: sha256 of kind+text, so a reused idempotency key with other content is refused (NULL on older rows).
|
|
913
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_outbox') WHERE name='args_digest'").get()) this.db.exec('ALTER TABLE tool_outbox ADD COLUMN args_digest TEXT');
|
|
914
|
+
// uncertain_at: a post failed in a way that may still have delivered it; the timer never retries such a row.
|
|
915
|
+
if(!this.db.prepare("SELECT 1 FROM pragma_table_info('tool_outbox') WHERE name='uncertain_at'").get()) this.db.exec('ALTER TABLE tool_outbox ADD COLUMN uncertain_at TEXT');
|
|
916
|
+
if(version<65) {
|
|
917
|
+
// Neutral names for the break table and the skip marker. They were named after the first worker. RENAME keeps the
|
|
918
|
+
// data, the index, and the break_notices foreign key (SQLite rewrites the reference in the child table).
|
|
919
|
+
// Roll back only from the backup taken before this upgrade: older code looks for the old names.
|
|
920
|
+
// Steps 63 and 64 are reserved for migrations that are merged before this one.
|
|
921
|
+
if(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='dot_breaks'").get()) this.db.exec('ALTER TABLE dot_breaks RENAME TO worker_breaks;');
|
|
922
|
+
if(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='index' AND name='dot_breaks_one_active'").get()) this.db.exec('DROP INDEX dot_breaks_one_active; CREATE UNIQUE INDEX IF NOT EXISTS worker_breaks_one_active ON worker_breaks(COALESCE(until,\'\')) WHERE until IS NULL;');
|
|
923
|
+
if(this.db.prepare("SELECT 1 FROM pragma_table_info('assignments') WHERE name='skipped_by_dot_at'").get()) this.db.exec('ALTER TABLE assignments RENAME COLUMN skipped_by_dot_at TO skipped_at;');
|
|
924
|
+
this.db.exec('PRAGMA user_version=65;');
|
|
925
|
+
}
|
|
926
|
+
if(version<66) { migratePullQueue(this.db); this.db.exec('PRAGMA user_version=66;'); }
|
|
927
|
+
// Which spelling of the fix-loop source this database stores. Schemas created before the rename list the earlier
|
|
928
|
+
// spelling in the CHECK constraint on assignments.source; newer schemas list only the neutral one.
|
|
929
|
+
this.legacyFixNames=!!this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='assignments' AND instr(sql,?)>0").get(`'${legacyFixLoopName}'`);
|
|
930
|
+
// An older Store already open before migration must not write plaintext afterward.
|
|
931
|
+
for (const [operation, columns] of [['INSERT', ''], ['UPDATE', ' OF secret,connection']]) {
|
|
932
|
+
this.db.exec(`CREATE TRIGGER IF NOT EXISTS subscriptions_encrypted_${operation.toLowerCase()} BEFORE ${operation}${columns} ON subscriptions
|
|
933
|
+
WHEN substr(NEW.secret,1,3) <> 'v1.' OR (NEW.connection IS NOT NULL AND substr(NEW.connection,1,3) <> 'v1.')
|
|
934
|
+
BEGIN SELECT RAISE(ABORT,'subscription storage requires encryption'); END`);
|
|
935
|
+
}
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
sealSubscription(id, field, value) { return this.subscriptionCodec.seal(value, `subscriptions:${id}:${field}`); }
|
|
939
|
+
openSubscription(id, field, value) { return this.subscriptionCodec.open(value, `subscriptions:${id}:${field}`); }
|
|
940
|
+
subscriptionConnection(sub) { return sub.connection === null ? null : JSON.parse(this.openSubscription(sub.id, 'connection', sub.connection)); }
|
|
941
|
+
subscriptionSecret(sub) { return this.openSubscription(sub.id, 'secret', sub.secret); }
|
|
942
|
+
validateSubscriptionStorage() {
|
|
943
|
+
try {
|
|
944
|
+
const marker = this.db.prepare('SELECT state,verifier FROM subscription_storage_meta WHERE id=1').get();
|
|
945
|
+
if (!marker || !['cleanup', 'ready'].includes(marker.state) || this.subscriptionCodec.open(marker.verifier, 'verifier') !== 'dot-bridge subscriptions v1') throw new Error();
|
|
946
|
+
for (const sub of this.db.prepare('SELECT id,secret,connection FROM subscriptions').all()) {
|
|
947
|
+
this.subscriptionSecret(sub);
|
|
948
|
+
this.subscriptionConnection(sub);
|
|
949
|
+
}
|
|
950
|
+
return marker;
|
|
951
|
+
} catch { throw new Error('subscription encrypted storage could not be opened'); }
|
|
952
|
+
}
|
|
953
|
+
initializeLeaseClock() {
|
|
954
|
+
// A claim in flight across the upgrade has no persisted deadline. Write the one its activity and lease imply, so a
|
|
955
|
+
// break extends it and every reader judges it by the same deadline.
|
|
956
|
+
// Only claims whose assignment is still claimed are in flight. A claim row keeps state 'active' after its job
|
|
957
|
+
// finishes or is cancelled, so a long-lived queue holds thousands of them; touching each one at startup, one commit
|
|
958
|
+
// per row, held the service before it listened. One transaction keeps the work proportional to the live claims.
|
|
959
|
+
const inFlight="state='active' AND request_id IN (SELECT request_id FROM assignments WHERE status='claimed')";
|
|
960
|
+
this.inTransaction(()=>{
|
|
961
|
+
for(const claim of this.db.prepare(`SELECT * FROM claims WHERE ${inFlight} AND lease_deadline_at IS NULL`).all()) {
|
|
962
|
+
const deadline=Date.parse(this.leaseExpiresAt(claim));
|
|
963
|
+
if(Number.isFinite(deadline)) this.db.prepare('UPDATE claims SET lease_deadline_at=? WHERE request_id=? AND lease_deadline_at IS NULL').run(iso(deadline),claim.request_id);
|
|
964
|
+
}
|
|
965
|
+
if(!this.leaseBootId) return;
|
|
966
|
+
const current=this.monotonicNow();
|
|
967
|
+
for(const claim of this.db.prepare(`SELECT * FROM claims WHERE ${inFlight} AND (lease_boot_id IS NULL OR lease_boot_id<>?)`).all(this.leaseBootId)) {
|
|
968
|
+
const deadline=Date.parse(this.leaseExpiresAt(claim));
|
|
969
|
+
const remaining=Number.isFinite(deadline)?Math.max(0,deadline-this.nowMs()):0;
|
|
970
|
+
this.db.prepare('UPDATE claims SET lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
|
|
971
|
+
.run(this.leaseBootId,current+remaining,claim.request_id);
|
|
972
|
+
}
|
|
973
|
+
});
|
|
974
|
+
}
|
|
975
|
+
initializeSubscriptionStorage() {
|
|
976
|
+
const marker = this.validateSubscriptionStorage();
|
|
977
|
+
if (marker.state !== 'cleanup') return;
|
|
978
|
+
try {
|
|
979
|
+
const checkpoint = () => { const result = this.db.prepare('PRAGMA wal_checkpoint(TRUNCATE)').get(); if (result.busy) throw new Error(); };
|
|
980
|
+
checkpoint(); this.db.exec('VACUUM'); checkpoint();
|
|
981
|
+
this.db.prepare("UPDATE subscription_storage_meta SET state='ready' WHERE id=1").run(); checkpoint();
|
|
982
|
+
} catch { throw new Error('subscription encrypted storage could not be opened'); }
|
|
983
|
+
}
|
|
984
|
+
putIntegrationCandidate(candidate) {
|
|
985
|
+
return this.transaction(()=>this.putIntegrationCandidateInTransaction(candidate));
|
|
986
|
+
}
|
|
987
|
+
putIntegrationCandidateInTransaction(candidate) {
|
|
988
|
+
const patch=Buffer.from(candidate.patch);
|
|
989
|
+
if(patch.length>MAX_INTEGRATION_PATCH_BYTES) throw new Error(`integration candidate patch too large (maximum ${MAX_INTEGRATION_PATCH_BYTES} bytes)`);
|
|
990
|
+
if(hash(patch)!==candidate.patch_digest) throw new Error('integration candidate patch digest does not match its bytes');
|
|
991
|
+
this.db.prepare('INSERT INTO integration_candidates(candidate_id,request_id,kind,linked_from,patch,patch_digest,patch_base_sha,target_sha,github_repo,created_at) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(candidate_id) DO NOTHING')
|
|
992
|
+
.run(candidate.candidate_id,candidate.request_id,candidate.kind,candidate.linked_from??null,patch,candidate.patch_digest,candidate.patch_base_sha,
|
|
993
|
+
candidate.target_sha,candidate.github_repo??null,this.stamp());
|
|
994
|
+
const existing=this.db.prepare('SELECT * FROM integration_candidates WHERE candidate_id=?').get(candidate.candidate_id);
|
|
995
|
+
if(!existing) throw new Error('integration candidate insert did not persist');
|
|
996
|
+
const same=existing.request_id===candidate.request_id&&existing.kind===candidate.kind&&(existing.linked_from??null)===(candidate.linked_from??null)
|
|
997
|
+
&&Buffer.from(existing.patch).equals(patch)&&existing.patch_digest===candidate.patch_digest&&existing.patch_base_sha===candidate.patch_base_sha
|
|
998
|
+
&&existing.target_sha===candidate.target_sha&&(existing.github_repo??null)===(candidate.github_repo??null);
|
|
999
|
+
if(!same) throw new Error('integration candidate identity is immutable');
|
|
1000
|
+
return {...existing,patch:Buffer.from(existing.patch)};
|
|
1001
|
+
}
|
|
1002
|
+
beginIntegrationVerification(candidates,verification) {
|
|
1003
|
+
if(!Array.isArray(candidates)||candidates.length<1) throw new Error('verification attempt needs at least one candidate');
|
|
1004
|
+
return this.transaction(()=>{
|
|
1005
|
+
const rows=candidates.map(candidate=>this.putIntegrationCandidateInTransaction(candidate));
|
|
1006
|
+
const attempt=this.recordIntegrationVerificationInTransaction(verification);
|
|
1007
|
+
return {candidates:rows,verification:attempt};
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
getIntegrationCandidate(candidateId) {
|
|
1011
|
+
const row=this.db.prepare('SELECT * FROM integration_candidates WHERE candidate_id=?').get(candidateId);
|
|
1012
|
+
return row?{...row,patch:Buffer.from(row.patch)}:null;
|
|
1013
|
+
}
|
|
1014
|
+
recordIntegrationVerification(verification) {
|
|
1015
|
+
return this.transaction(()=>this.recordIntegrationVerificationInTransaction(verification));
|
|
1016
|
+
}
|
|
1017
|
+
recordIntegrationVerificationInTransaction(verification) {
|
|
1018
|
+
const verificationId=`iver_${randomUUID()}`;
|
|
1019
|
+
const candidate=this.db.prepare('SELECT patch_digest,patch_base_sha,target_sha FROM integration_candidates WHERE candidate_id=?').get(verification.candidate_id);
|
|
1020
|
+
if(!candidate) throw new Error('integration candidate not found');
|
|
1021
|
+
if(verification.patch_digest!==candidate.patch_digest||verification.patch_base_sha!==candidate.patch_base_sha||verification.target_sha!==candidate.target_sha)
|
|
1022
|
+
throw new Error('integration verification does not match candidate');
|
|
1023
|
+
this.db.prepare('INSERT INTO integration_verifications(verification_id,candidate_id,patch_digest,patch_base_sha,target_sha,target_ref,status,checks_json,error,recorded_at) VALUES(?,?,?,?,?,?,?,?,?,?)')
|
|
1024
|
+
.run(verificationId,verification.candidate_id,candidate.patch_digest,candidate.patch_base_sha,candidate.target_sha,verification.target_ref,verification.status,JSON.stringify(redactOutput(verification.checks)),redactOutput(verification.error??null),this.stamp());
|
|
1025
|
+
const {checks_json,...row}=this.db.prepare('SELECT * FROM integration_verifications WHERE verification_id=?').get(verificationId);
|
|
1026
|
+
return {...row,checks:JSON.parse(checks_json)};
|
|
1027
|
+
}
|
|
1028
|
+
integrationVerifications(candidateId) {
|
|
1029
|
+
return this.db.prepare('SELECT * FROM integration_verifications WHERE candidate_id=? ORDER BY rowid').all(candidateId)
|
|
1030
|
+
.map(({checks_json,...row})=>({...row,checks:JSON.parse(checks_json)}));
|
|
1031
|
+
}
|
|
1032
|
+
recordSandboxStop(checkRunId,phase,stop) {
|
|
1033
|
+
const row=this.db.prepare('SELECT stop_verified,stop_evidence FROM check_jobs WHERE id=?').get(checkRunId);
|
|
1034
|
+
const phases={...(row?.stop_evidence?JSON.parse(row.stop_evidence):{}),[phase]:stop};
|
|
1035
|
+
this.db.prepare('UPDATE check_jobs SET stop_verified=?,stop_evidence=? WHERE id=?').run(Object.values(phases).every(x=>x.verified)?1:0,JSON.stringify(phases),checkRunId);
|
|
1036
|
+
}
|
|
1037
|
+
// "Cancel requested" and "compute stopped" are separate facts. compute_stopped is true only when the assignment is cancelled, a host
|
|
1038
|
+
// sandbox ran for it, no check is still running, and the bridge verified after every phase that nothing of that sandbox remained.
|
|
1039
|
+
// Anything else stays false and says why. The bridge cannot see a remote worker's own compute, so this speaks of the bridge host only.
|
|
1040
|
+
sandboxStop(id,cancelled) {
|
|
1041
|
+
const jobs=this.db.prepare('SELECT id,status,stop_verified,stop_evidence FROM check_jobs WHERE request_id=? ORDER BY started_at').all(id);
|
|
1042
|
+
const unverified=jobs.filter(j=>j.status==='running'||j.stop_verified!==1).map(j=>({check_run_id:j.id,status:j.status,reason:j.status==='running'?'check_still_running':j.stop_evidence?Object.values(JSON.parse(j.stop_evidence)).find(x=>!x.verified)?.reason:'stop_not_verified'}));
|
|
1043
|
+
const reason=!cancelled?'not_cancelled':!jobs.length?'no_host_sandbox_ran':unverified.length?'stop_not_verified':'verified';
|
|
1044
|
+
return {compute_stopped:reason==='verified',sandbox_stop:{reason,host_sandboxes:jobs.length,unverified}};
|
|
1045
|
+
}
|
|
1046
|
+
// First owner read of a terminal assignment; a no-op while it is live or has no workspace.
|
|
1047
|
+
recordFetched(id) { this.db.prepare("UPDATE workspaces SET fetched_at=? WHERE request_id=? AND fetched_at IS NULL AND EXISTS(SELECT 1 FROM assignments a WHERE a.request_id=workspaces.request_id AND a.status IN ('finished','cancelled'))").run(this.stamp(),id); }
|
|
1048
|
+
insertConfinedCheckAssignment(requestId,payload) {
|
|
1049
|
+
const body=JSON.stringify(payload);
|
|
1050
|
+
// "unknown" is a reserved name that no configured worker can have, so only the integrator ever touches this row.
|
|
1051
|
+
this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,target_worker) VALUES(?,?,?,?,?,?,?,?)')
|
|
1052
|
+
.run(requestId,body,hash(body),'integrator','integrator','running',this.stamp(),'unknown');
|
|
1053
|
+
return this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(requestId);
|
|
1054
|
+
}
|
|
1055
|
+
// Queue waits are scoped to the selected worker and task kind, one sample per job. The first persisted claim is the
|
|
1056
|
+
// endpoint; a later reclaim or resume must not make an old wait appear longer. A row never claimed is a censored lower
|
|
1057
|
+
// bound: its wait runs to the latest learned-deadline requeue or system expiry. A claimed row's earlier requeues add
|
|
1058
|
+
// nothing, because its exact wait already exceeds them.
|
|
1059
|
+
queueWaitEvidence(worker, kind, days=7) {
|
|
1060
|
+
kind=canonicalKindLabel(kind);
|
|
1061
|
+
const since=iso(this.nowMs()-days*86400000);
|
|
1062
|
+
const rows=this.db.prepare(`SELECT a.created_at created,a.cancelled_at cancelled,a.cancelled_reason reason,
|
|
1063
|
+
EXISTS(SELECT 1 FROM lifecycle_events e INDEXED BY lifecycle_events_request WHERE e.request_id=a.request_id AND e.type='cancelled' AND e.actor='system' AND e.reason='expired') system_expiry,
|
|
1064
|
+
(SELECT min(e.at) FROM lifecycle_events e INDEXED BY lifecycle_events_request WHERE e.request_id=a.request_id AND e.type='claimed' AND e.worker=a.target_worker) claimed,
|
|
1065
|
+
(SELECT group_concat(e.at) FROM lifecycle_events e INDEXED BY lifecycle_events_request WHERE e.request_id=a.request_id AND e.type='queued' AND e.actor='system' AND e.reason='expired_requeued') requeued
|
|
1066
|
+
FROM assignments a WHERE a.created_at>=? AND a.target_worker=? AND ${queueKindSql}=?`).all(since,worker,kind);
|
|
1067
|
+
const observed=[]; let expiredLowerBounds=0;
|
|
1068
|
+
for(const row of rows) {
|
|
1069
|
+
const created=Date.parse(row.created);
|
|
1070
|
+
let ms=NaN, censored=false;
|
|
1071
|
+
if(row.claimed) ms=Date.parse(row.claimed)-created;
|
|
1072
|
+
else {
|
|
1073
|
+
const bounds=(row.requeued?.split(',')??[]).map(Date.parse);
|
|
1074
|
+
if(row.reason==='expired'&&row.system_expiry) bounds.push(Date.parse(row.cancelled));
|
|
1075
|
+
const finite=bounds.filter(Number.isFinite);
|
|
1076
|
+
if(finite.length) { ms=Math.max(...finite)-created; censored=true; }
|
|
1077
|
+
}
|
|
1078
|
+
if(!Number.isFinite(ms)||ms<0) continue;
|
|
1079
|
+
observed.push(ms);
|
|
1080
|
+
if(censored) expiredLowerBounds++;
|
|
1081
|
+
}
|
|
1082
|
+
observed.sort((a,b)=>a-b);
|
|
1083
|
+
return {waits_ms:observed,expired_lower_bounds:expiredLowerBounds,samples:observed.length,window_days:days,worker,kind};
|
|
1084
|
+
}
|
|
1085
|
+
queueWaitsMs(worker,kind,days=7) { return this.queueWaitEvidence(worker,kind,days).waits_ms; }
|
|
1086
|
+
defaultValidUntil(worker,kind,days=7) {
|
|
1087
|
+
const evidence=this.queueWaitEvidence(worker,kind,days), waits=evidence.waits_ms;
|
|
1088
|
+
if(waits.length<QUEUE_WINDOW.minSamples) return {valid_until:null,source:'insufficient_history',p90_ms:null,samples:waits.length,
|
|
1089
|
+
expired_lower_bounds:evidence.expired_lower_bounds,window_days:days,factor:QUEUE_WINDOW.factor,floor_ms:QUEUE_WINDOW.minMs,cap_ms:QUEUE_WINDOW.maxMs,
|
|
1090
|
+
min_samples:QUEUE_WINDOW.minSamples,worker,kind};
|
|
1091
|
+
const p90=waits[Math.min(waits.length-1,Math.ceil(waits.length*0.9)-1)];
|
|
1092
|
+
const windowMs=Math.min(QUEUE_WINDOW.maxMs,Math.max(QUEUE_WINDOW.minMs,p90*QUEUE_WINDOW.factor));
|
|
1093
|
+
return {valid_until:iso(this.nowMs()+windowMs),source:'queue_p90',window_ms:Math.round(windowMs),p90_ms:p90,samples:waits.length,min_samples:QUEUE_WINDOW.minSamples,
|
|
1094
|
+
expired_lower_bounds:evidence.expired_lower_bounds,window_days:days,factor:QUEUE_WINDOW.factor,floor_ms:QUEUE_WINDOW.minMs,cap_ms:QUEUE_WINDOW.maxMs,worker,kind};
|
|
1095
|
+
}
|
|
1096
|
+
owner(id, token) {
|
|
1097
|
+
const row = this.db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(id)??this.pullQueue.ownerRow(id);
|
|
1098
|
+
if (!row) throw new Error('assignment not found');
|
|
1099
|
+
if (!row.owner_hash) throw new Error('legacy request requires operator adoption');
|
|
1100
|
+
const got = Buffer.from(hash(token || ''), 'hex'), expected = Buffer.from(row.owner_hash, 'hex');
|
|
1101
|
+
if (got.length !== expected.length || !timingSafeEqual(got, expected)) throw new Error('invalid owner capability');
|
|
1102
|
+
this.assertProtocolAvailable(id);
|
|
1103
|
+
}
|
|
1104
|
+
destinationConfigurationError(id,error) {
|
|
1105
|
+
// The hook must never change the public failure, whatever it throws.
|
|
1106
|
+
try { this.onConfigError?.(error); } catch { /* diagnostic only */ }
|
|
1107
|
+
// Never return parser fragments, filesystem paths or resolver exception text.
|
|
1108
|
+
const cause=error instanceof SyntaxError?'invalid JSON configuration':'configuration could not be loaded';
|
|
1109
|
+
return destinationError({error:'destination_configuration_invalid',request_id:id,
|
|
1110
|
+
message:'Current destination configuration is unavailable or invalid; restore it before a new admission. Cause: '+cause});
|
|
1111
|
+
}
|
|
1112
|
+
destinationSnapshot(worker,execution,payload,{required=false,resolve=()=>this.destinationProfile()}={}) {
|
|
1113
|
+
try {
|
|
1114
|
+
if(!required&&this.destinationProfile===null&&this.workers.workers.get(worker)?.destination===undefined)return null;
|
|
1115
|
+
if(typeof this.destinationProfile!=='function')throw new Error('destination resolver required');
|
|
1116
|
+
const profile=resolve();
|
|
1117
|
+
if(profile&&typeof profile.then==='function')throw new Error('destination resolver must be synchronous');
|
|
1118
|
+
return destinationDisclosure(profile,worker,execution,payload);
|
|
1119
|
+
} catch(error) {
|
|
1120
|
+
throw this.destinationConfigurationError(payload.request_id,error);
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
destinationApproval(id) {
|
|
1124
|
+
const row=this.db.prepare('SELECT * FROM destination_approvals WHERE request_id=?').get(id);
|
|
1125
|
+
return row?{revision:row.revision,snapshot:JSON.parse(row.snapshot),actor:JSON.parse(row.actor),approved_at:row.approved_at}:null;
|
|
1126
|
+
}
|
|
1127
|
+
destinationFields(id) {
|
|
1128
|
+
const approval=this.destinationApproval(id),block=this.db.prepare('SELECT body FROM destination_blocks WHERE request_id=?').get(id);
|
|
1129
|
+
return {...(approval?{destination_approval:approval}:{}),...(block?{destination_changed:JSON.parse(block.body)}:{})};
|
|
1130
|
+
}
|
|
1131
|
+
destinationClaimFields(id) {
|
|
1132
|
+
const revision=this.db.prepare('SELECT destination_revision FROM claims WHERE request_id=?').get(id)?.destination_revision;
|
|
1133
|
+
return revision?{destination_revision:revision}:{};
|
|
1134
|
+
}
|
|
1135
|
+
destinationGeneration(id) {
|
|
1136
|
+
const row=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
1137
|
+
if(!row)return null;
|
|
1138
|
+
const claim=this.db.prepare('SELECT claim_id,epoch FROM claims WHERE request_id=?').get(id);
|
|
1139
|
+
return {status:row.status,claim_id:claim?.claim_id??null,epoch:claim?.epoch??0,
|
|
1140
|
+
approved_revision:this.destinationApproval(id)?.revision??null,protocol_revision:this.isProtocolJob(id)?this.protocolRevision(id):null};
|
|
1141
|
+
}
|
|
1142
|
+
recordDestinationRefusalInTransaction(id,observed,details) {
|
|
1143
|
+
if(!this.db.isTransaction)throw new Error('destination refusal requires transaction');
|
|
1144
|
+
const current=this.destinationGeneration(id);
|
|
1145
|
+
if(!observed||!current||!['queued','claimed'].includes(current.status)||
|
|
1146
|
+
JSON.stringify(current)!==JSON.stringify(observed))return false;
|
|
1147
|
+
const body=JSON.stringify(details),old=this.db.prepare('SELECT body FROM destination_blocks WHERE request_id=?').get(id);
|
|
1148
|
+
if(old?.body===body)return true;
|
|
1149
|
+
this.db.prepare('INSERT INTO destination_blocks(request_id,body) VALUES(?,?) ON CONFLICT(request_id) DO UPDATE SET body=excluded.body').run(id,body);
|
|
1150
|
+
const comparison=(details.differences??[]).map(d=>d.field+': '+JSON.stringify(d.approved)+' -> '+JSON.stringify(d.current)).join('; ');
|
|
1151
|
+
const note='BLOCKED: '+details.error+'. '+details.message+(comparison?' '+comparison:'');
|
|
1152
|
+
this.db.prepare('INSERT INTO notifications(id,kind,request_id,body,created_at) VALUES(?,?,?,?,?)').run(
|
|
1153
|
+
'evt_'+randomUUID(),this.deliveryKind(id,'blocker'),id,
|
|
1154
|
+
JSON.stringify({note,destination_change:true,destination_generation:observed}),this.stamp());
|
|
1155
|
+
return true;
|
|
1156
|
+
}
|
|
1157
|
+
destinationAdmissionInTransaction(id) {
|
|
1158
|
+
if(!this.db.isTransaction)throw new Error('destination admission requires transaction');
|
|
1159
|
+
const approval=this.destinationApproval(id);
|
|
1160
|
+
// No migration invents approval; unbound jobs must check the current declaration.
|
|
1161
|
+
const observed=this.destinationGeneration(id);
|
|
1162
|
+
const row=this.db.prepare('SELECT payload,target_worker,execution FROM assignments WHERE request_id=?').get(id);
|
|
1163
|
+
let current=null,details;
|
|
1164
|
+
// This synchronous read is the destination snapshot linearization point. No await
|
|
1165
|
+
// or external publication lock is claimed; later file edits apply to later admissions.
|
|
1166
|
+
try {
|
|
1167
|
+
current=this.destinationSnapshot(row.target_worker,row.execution,JSON.parse(row.payload),{required:!!approval});
|
|
1168
|
+
}
|
|
1169
|
+
catch(error){details=error.destination;}
|
|
1170
|
+
if(!details&&(!approval&&!current||approval&¤t?.revision===approval.revision&¤t.policy.allowed))return null;
|
|
1171
|
+
const error=details?.error??(!approval?'destination_approval_required':current?.revision!==approval.revision?'destination_changed':'destination_policy_denied');
|
|
1172
|
+
details={error,request_id:id,approved_revision:approval?.revision??null,current_revision:current?.revision??null,
|
|
1173
|
+
approved:approval?.snapshot??null,current,differences:destinationDifferences(approval?.snapshot,current),
|
|
1174
|
+
message:error==='destination_approval_required'?'The current worker declares a destination but this job has no approval. Ask the owner to cancel and resubmit a new request ID after approving its current revision.':
|
|
1175
|
+
error==='destination_changed'?'The declared destination changed. Cancel and resubmit a new request ID after approving its current revision.':
|
|
1176
|
+
error==='destination_policy_denied'?'Current repository policy refuses this destination; approval does not override policy.':
|
|
1177
|
+
'Current destination configuration is unavailable or invalid. Restore it; this job cannot fall back to legacy admission.'};
|
|
1178
|
+
this.recordDestinationRefusalInTransaction(id,observed,details);
|
|
1179
|
+
return {destination_refusal:details};
|
|
1180
|
+
}
|
|
1181
|
+
destinationGrantedInTransaction(id) {
|
|
1182
|
+
const approval=this.destinationApproval(id);
|
|
1183
|
+
if(approval)this.db.prepare('UPDATE claims SET destination_revision=? WHERE request_id=?').run(approval.revision,id);
|
|
1184
|
+
this.db.prepare('DELETE FROM destination_blocks WHERE request_id=?').run(id);
|
|
1185
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='destination admission superseded refusal' WHERE request_id=? AND kind IN ('wait','blocker') AND state IN ('pending','failed') AND json_valid(body) AND json_extract(body,'$.destination_change')=1").run(id);
|
|
1186
|
+
return this.destinationClaimFields(id);
|
|
1187
|
+
}
|
|
1188
|
+
destinationOutcome(result) {
|
|
1189
|
+
// Throw only after the owning transaction committed its durable refusal.
|
|
1190
|
+
if(result?.destination_refusal)throw destinationError(result.destination_refusal);
|
|
1191
|
+
return result;
|
|
1192
|
+
}
|
|
1193
|
+
checkRetry(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, priority='normal', meta=null, identity=payload, targetWorker=undefined, execution=null, requiredCapabilities=null, commandKey=null, supersedes=null, destinationRevision=null) {
|
|
1194
|
+
validateSubmitKey(commandKey);
|
|
1195
|
+
const m=normalizeMeta(meta);
|
|
1196
|
+
const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
|
|
1197
|
+
if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
|
|
1198
|
+
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1199
|
+
const deliveryValue=delivery.mode==='t3'?`t3:${delivery.threadId}`:'none';
|
|
1200
|
+
const old=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(payload.request_id);
|
|
1201
|
+
if(supersedes!==null&&(!supersedes||typeof supersedes!=='object'||Array.isArray(supersedes)||
|
|
1202
|
+
Object.keys(supersedes).some(k=>!['target_id','target_token'].includes(k))||
|
|
1203
|
+
typeof supersedes.target_id!=='string'||!/^[-\w]{8,128}$/.test(supersedes.target_id))) throw new Error('invalid supersedes');
|
|
1204
|
+
const targetId=supersedes?.target_id??null;
|
|
1205
|
+
const previous=this.db.prepare('SELECT target_id FROM submit_supersedes WHERE request_id=?').get(payload.request_id);
|
|
1206
|
+
if(targetId===payload.request_id) throw new Error('supersede_cycle');
|
|
1207
|
+
// Both capabilities are required even when returning an already-committed receipt.
|
|
1208
|
+
if(old&&(supersedes||previous)) this.owner(payload.request_id,ownerToken);
|
|
1209
|
+
let target;
|
|
1210
|
+
if(supersedes) {
|
|
1211
|
+
target=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(targetId);
|
|
1212
|
+
if(!target) throw new Error('supersede_target_not_found');
|
|
1213
|
+
if(typeof supersedes.target_token!=='string') throw new Error('invalid owner capability');
|
|
1214
|
+
this.owner(targetId,supersedes.target_token);
|
|
1215
|
+
if(Object.hasOwn(payload,'protocol')||this.isProtocolJob(payload.request_id)||this.isProtocolJob(targetId))
|
|
1216
|
+
throw new Error('supersede_native_unsupported');
|
|
1217
|
+
}
|
|
1218
|
+
if(!old) {
|
|
1219
|
+
// A requeued claim is not proof that its remote compute stopped: refuse all claim history.
|
|
1220
|
+
if(supersedes&&(target.status!=='queued'||this.db.prepare('SELECT 1 FROM claims WHERE request_id=?').get(targetId)))
|
|
1221
|
+
throw new Error('supersede_target_not_queued');
|
|
1222
|
+
return null;
|
|
1223
|
+
}
|
|
1224
|
+
if(this.isProtocolJob(payload.request_id)) {
|
|
1225
|
+
this.owner(payload.request_id,ownerToken);
|
|
1226
|
+
this.assertProtocolAvailable(payload.request_id);
|
|
1227
|
+
identity={...identity,protocol:validateProtocol(payload.protocol)};
|
|
1228
|
+
}
|
|
1229
|
+
const payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=hash(ownerToken);
|
|
1230
|
+
const approval=this.destinationApproval(payload.request_id);
|
|
1231
|
+
// Authenticate before revealing or comparing the approval binding.
|
|
1232
|
+
if(approval)this.owner(payload.request_id,ownerToken);
|
|
1233
|
+
if((approval?.revision??null)!==destinationRevision)throw new Error('destination approval conflict: retry the original revision; cancel and resubmit to approve a change');
|
|
1234
|
+
const command=this.db.prepare('SELECT * FROM owner_submit_commands WHERE request_id=?').get(payload.request_id);
|
|
1235
|
+
// Authenticate before revealing key existence or replaying its receipt.
|
|
1236
|
+
if(commandKey!==null||command) this.owner(payload.request_id,ownerToken);
|
|
1237
|
+
if(commandKey!==null) {
|
|
1238
|
+
if(!command||command.key_digest!==hash(commandKey)) throw new Error('EXISTS: assignment already submitted under another command');
|
|
1239
|
+
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??old.target_worker,execution??old.execution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1240
|
+
if((previous?.target_id??null)!==targetId||command.owner_hash!==ownerHash||command.intent_digest!==intent) throw new Error('KEY_CONFLICT: command intent changed');
|
|
1241
|
+
return {...JSON.parse(command.receipt),duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1242
|
+
}
|
|
1243
|
+
if(command) throw new Error('EXISTS: command_key required to retry this assignment');
|
|
1244
|
+
if ((previous?.target_id??null)!==targetId || (targetWorker!==undefined&&old.target_worker!==targetWorker) || (execution!==null&&old.execution!==execution) || (requiredCapabilities!==null&&old.required_capabilities!==JSON.stringify(requiredCapabilities)) || old.payload_hash!==payloadHash || old.delivery!==deliveryValue || old.environment_id!==(environmentId??'') || old.owner_hash!==ownerHash || !!old.review!==!!review || old.priority!==priority || metaFields.some(k=>old[k]!=null&&m[k]!=null&&canonicalMetaValue(k,old[k])!==canonicalMetaValue(k,m[k]))) throw new Error('request_id conflict');
|
|
1245
|
+
return {request_id:payload.request_id,status:old.status,duplicate:true,...(approval?{destination_approval:approval}:{})};
|
|
1246
|
+
}
|
|
1247
|
+
// identity: the assignment as the submitter sent it, when the stored payload differs (scope narrowing); a retry then still matches.
|
|
1248
|
+
submit(...args) { return this.transaction(()=>this.submitInTransaction(...args)); }
|
|
1249
|
+
submitInTransaction(payload, deliveryOrThreadId, environmentId, ownerToken, review=false, preflight=null, priority='normal', meta=null, identity=payload, maxQueued=null, targetWorker=undefined, execution=null, defaultExecution='host', requiredCapabilities=null, defaultValidUntil=null, commandKey=null, supersedes=null, destinationRevision=null, inheritedOwnerHash=null) {
|
|
1250
|
+
if(!this.db.isTransaction) throw new Error('transaction_required');
|
|
1251
|
+
if(payload.request_id.startsWith(PULL_PAGE_PREFIX)||!inheritedOwnerHash&&this.pullQueue.row(payload.request_id)) throw new Error('request_id reserved for policy work');
|
|
1252
|
+
const protocol=!this.hasAssignment(payload.request_id)&&Object.hasOwn(payload,'protocol')?validateProtocol(payload.protocol):null;
|
|
1253
|
+
if(protocol)identity={...identity,protocol};
|
|
1254
|
+
if(targetWorker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
1255
|
+
const delivery=typeof deliveryOrThreadId==='string'?{mode:'t3',threadId:deliveryOrThreadId}:deliveryOrThreadId;
|
|
1256
|
+
if(!delivery||!['t3','none'].includes(delivery.mode)||delivery.mode==='t3'&&!delivery.threadId) throw new Error('invalid delivery');
|
|
1257
|
+
const m=normalizeMeta(meta),threadId=delivery.threadId??'',deliveryValue=delivery.mode==='t3'?`t3:${threadId}`:'none';
|
|
1258
|
+
if(!['normal','background'].includes(priority)) throw new Error('invalid priority');
|
|
1259
|
+
const retry=this.checkRetry(payload,delivery,environmentId,ownerToken,review,priority,meta,identity,targetWorker,execution,requiredCapabilities,commandKey,supersedes,destinationRevision);
|
|
1260
|
+
if(retry) return retry;
|
|
1261
|
+
const id=payload.request_id, body=JSON.stringify(payload),payloadHash=hash(JSON.stringify(canonical(identity))),ownerHash=inheritedOwnerHash??hash(ownerToken);
|
|
1262
|
+
// checkRetry validated this target in the same transaction; only counts containing it gain room.
|
|
1263
|
+
const supersededId=supersedes?.target_id??null;
|
|
1264
|
+
if(destinationRevision!==null&&(typeof destinationRevision!=='string'||!/^sha256:[a-f0-9]{64}$/.test(destinationRevision)))throw new Error('invalid destination_revision');
|
|
1265
|
+
const disclosure=this.destinationSnapshot(targetWorker??'dot',execution??defaultExecution,payload,{required:destinationRevision!==null});
|
|
1266
|
+
if(disclosure&&destinationRevision===null)throw destinationError({error:'destination_approval_required',request_id:id,current:disclosure,message:'Review the destination disclosure and submit its exact destination_revision.'});
|
|
1267
|
+
if((disclosure?.revision??null)!==destinationRevision)throw destinationError({error:'destination_changed',request_id:id,approved_revision:destinationRevision,current_revision:disclosure?.revision??null,current:disclosure,message:'The preview revision is stale; review the current disclosure before submission.'});
|
|
1268
|
+
if(disclosure&&!disclosure.policy.allowed)throw destinationError({error:'destination_policy_denied',request_id:id,current:disclosure,message:'Current repository policy refuses this destination.'});
|
|
1269
|
+
if(disclosure) {
|
|
1270
|
+
// Check the snapshot being approved, even if the live set changes before the next read.
|
|
1271
|
+
if(disclosure.connections_digest==='sha256:'+hash('[]'))throw destinationError({error:'destination_connection_required',request_id:id,current:disclosure,
|
|
1272
|
+
message:'Built-in mode requires a live connection before an approval can be recorded for this worker.'});
|
|
1273
|
+
// Built-in mode only: never record an approval that binds the empty
|
|
1274
|
+
// live-connection set. Such an approval would match again the next time
|
|
1275
|
+
// the set empties (pair, then revoke or expire), admitting claims from
|
|
1276
|
+
// a dead connection. External-OAuth profiles carry no live-set callback,
|
|
1277
|
+
// so this check does not apply to them.
|
|
1278
|
+
let profile=null;
|
|
1279
|
+
try {
|
|
1280
|
+
profile=typeof this.destinationProfile==='function'?this.destinationProfile():null;
|
|
1281
|
+
if(profile&&typeof profile.then==='function')throw new Error('destination resolver must be synchronous');
|
|
1282
|
+
} catch(error) {
|
|
1283
|
+
throw this.destinationConfigurationError(id,error);
|
|
1284
|
+
}
|
|
1285
|
+
const live=profile?.builtinConnectionIds;
|
|
1286
|
+
if(typeof live==='function') {
|
|
1287
|
+
let ids;
|
|
1288
|
+
try { ids=live(targetWorker??'dot'); }
|
|
1289
|
+
catch(error) { throw this.destinationConfigurationError(id,error); }
|
|
1290
|
+
if(!Array.isArray(ids)||ids.length===0)throw destinationError({error:'destination_connection_required',request_id:id,current:disclosure,
|
|
1291
|
+
message:'Built-in mode requires a live connection before an approval can be recorded for this worker.'});
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
if(maxQueued!==null) {
|
|
1295
|
+
if(!Number.isSafeInteger(maxQueued)||maxQueued<1) throw new Error('invalid max_queued');
|
|
1296
|
+
const queued=this.db.prepare(`SELECT count(*) n FROM assignments WHERE status='queued' AND target_worker=? AND request_id IS NOT ? AND ${live(this.nowMs())}`).get(targetWorker??'dot',supersededId).n;
|
|
1297
|
+
if(queued>=maxQueued) throw new Error(`worker queue is full (${queued} queued, in-flight cap ${maxQueued})`);
|
|
1298
|
+
}
|
|
1299
|
+
if(priority==='background'&&this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority='background' AND target_worker=? AND request_id IS NOT ? AND (status='claimed' OR status='queued' AND ${live(this.nowMs())})`).get(targetWorker??'dot',supersededId).n>=this.backgroundMaxInFlight) throw new Error('background_capacity_full');
|
|
1300
|
+
// The target is a column, not payload: an omitted worker means 'dot'.
|
|
1301
|
+
this.db.prepare('INSERT INTO assignments(request_id,payload,payload_hash,thread_id,environment_id,status,created_at,owner_hash,review,delivery,priority,objective_key,revision,task_kind,source,target_worker,execution,required_capabilities) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,body,payloadHash,threadId,environmentId??'','queued',this.stamp(),ownerHash,review?1:0,deliveryValue,priority,...metaFields.map(k=>k==='source'?toStoredSource(m[k],this.legacyFixNames):m[k]),targetWorker??'dot',execution??defaultExecution,requiredCapabilities?JSON.stringify(requiredCapabilities):null);
|
|
1302
|
+
if(disclosure)this.db.prepare('INSERT INTO destination_approvals(request_id,revision,snapshot,actor,approved_at) VALUES(?,?,?,?,?)').run(id,disclosure.revision,JSON.stringify(disclosure),JSON.stringify({kind:'owner_capability',id:ownerHash}),this.stamp());
|
|
1303
|
+
const requestedValidUntil=validUntilOf(payload);
|
|
1304
|
+
const mayUseDefault=priority==='normal'&&!this.paused()&&!((targetWorker??'dot')==='dot'&&this.holdingBreak());
|
|
1305
|
+
const effectiveValidUntil=requestedValidUntil??(mayUseDefault&&typeof defaultValidUntil==='string'?defaultValidUntil:null);
|
|
1306
|
+
this.db.prepare('UPDATE assignments SET valid_until=?,valid_until_source=? WHERE request_id=?').run(effectiveValidUntil,requestedValidUntil?'requester':effectiveValidUntil?'queue_p90':null,id);
|
|
1307
|
+
this.recordPrPreflight(id,'submit',payload,preflight);
|
|
1308
|
+
this.lifecycle(id,'queued','owner',null,null);
|
|
1309
|
+
if(protocol) {
|
|
1310
|
+
this.db.prepare('INSERT INTO protocol_jobs VALUES(?,?)').run(id,JSON.stringify(canonical(protocol)));
|
|
1311
|
+
defineProtocolRetentionInTransaction(this,id);
|
|
1312
|
+
this.protocolCommands().initialize(id,1);
|
|
1313
|
+
this.protocolEventInTransaction(id,'submitted',{},0);
|
|
1314
|
+
}
|
|
1315
|
+
if(supersedes) {
|
|
1316
|
+
// Source, immutable reference, cancellation facts and command receipt share this write transaction.
|
|
1317
|
+
this.db.prepare('INSERT INTO submit_supersedes(request_id,target_id,created_at) VALUES(?,?,?)').run(id,supersedes.target_id,this.stamp());
|
|
1318
|
+
this.cancelInTransaction(supersedes.target_id,'superseded');
|
|
1319
|
+
}
|
|
1320
|
+
for (const sub of this.activeSubscriptions()) this.submitWake(id,sub);
|
|
1321
|
+
const receipt={request_id:id,status:'queued',duplicate:false,...(protocol?{revision:1}:{}),...this.destinationFields(id)};
|
|
1322
|
+
if(commandKey!==null) {
|
|
1323
|
+
const intent=submitIntentDigest(identity,deliveryValue,environmentId,review,priority,m,targetWorker??'dot',execution??defaultExecution,requiredCapabilities,destinationRevision,this.legacyFixNames);
|
|
1324
|
+
this.db.prepare('INSERT INTO owner_submit_commands(request_id,key_digest,intent_digest,receipt,owner_hash) VALUES(?,?,?,?,?)').run(id,hash(commandKey),intent,JSON.stringify(receipt),ownerHash);
|
|
1325
|
+
}
|
|
1326
|
+
return receipt;
|
|
1327
|
+
}
|
|
1328
|
+
// Fills objective columns of rows that have none, only with tuples verifyObjective proves against the stored payload.
|
|
1329
|
+
// Idempotent: a row that already carries any objective column is never rewritten.
|
|
1330
|
+
backfillObjectives(tuples, {dryRun=false}={}) { return this.transaction(() => {
|
|
1331
|
+
if(!Array.isArray(tuples)||tuples.length>1000) throw new Error('tuples must be an array of at most 1000');
|
|
1332
|
+
const out={dry_run:dryRun,received:tuples.length,updated:0,already_set:0,conflict:0,not_found:0,rejected:0,by_source:{},rejected_examples:[]};
|
|
1333
|
+
const select=this.db.prepare('SELECT request_id,payload,objective_key,revision,task_kind,source FROM assignments WHERE request_id=?');
|
|
1334
|
+
const update=this.db.prepare('UPDATE assignments SET objective_key=?,revision=?,task_kind=?,source=? WHERE request_id=? AND objective_key IS NULL AND revision IS NULL AND task_kind IS NULL AND source IS NULL');
|
|
1335
|
+
for(const t of tuples) {
|
|
1336
|
+
const row=typeof t?.request_id==='string'?select.get(t.request_id):null;
|
|
1337
|
+
if(!row) { out.not_found++; continue; }
|
|
1338
|
+
const {request_id,...given}=t, why=verifyObjective(row,given);
|
|
1339
|
+
if(why) { out.rejected++; if(out.rejected_examples.length<20) out.rejected_examples.push({request_id,reason:why}); continue; }
|
|
1340
|
+
const tuple=normalizeMeta(given);
|
|
1341
|
+
if(metaFields.some(k=>row[k]!==null)) { out[metaFields.every(k=>canonicalMetaValue(k,row[k])===canonicalMetaValue(k,tuple[k]))?'already_set':'conflict']++; continue; }
|
|
1342
|
+
if(!dryRun) update.run(...metaFields.map(k=>k==='source'?toStoredSource(tuple[k],this.legacyFixNames):tuple[k]),request_id);
|
|
1343
|
+
out.updated++; out.by_source[tuple.source]=(out.by_source[tuple.source]??0)+1;
|
|
1344
|
+
}
|
|
1345
|
+
out.without_objective=this.db.prepare('SELECT count(*) n FROM assignments WHERE objective_key IS NULL').get().n-(dryRun?out.updated:0);
|
|
1346
|
+
out.total=this.db.prepare('SELECT count(*) n FROM assignments').get().n;
|
|
1347
|
+
return out;
|
|
1348
|
+
}); }
|
|
1349
|
+
isProtocolJob(id) { return !!this.db.prepare('SELECT 1 FROM protocol_jobs WHERE request_id=?').get(id); }
|
|
1350
|
+
assertProtocolAvailable(id) { return checkProtocolAvailable(this,id); }
|
|
1351
|
+
protocolListingLive(id) {
|
|
1352
|
+
const protocol=this.getProtocol(id);
|
|
1353
|
+
return !protocol||protocol.retain_until_ms>this.nowMs()&&!!this.db.prepare('SELECT 1 FROM job_retention_policy WHERE job=?').get(id)&&!this.db.prepare('SELECT 1 FROM job_retention_tombstones WHERE job=?').get(id);
|
|
1354
|
+
}
|
|
1355
|
+
getProtocol(id) { const r=this.db.prepare('SELECT settings FROM protocol_jobs WHERE request_id=?').get(id);return r?JSON.parse(r.settings):null; }
|
|
1356
|
+
protocolRevision(id) { return this.db.prepare('SELECT revision FROM claim_command_revisions WHERE job=?').get(id)?.revision??null; }
|
|
1357
|
+
protocolFacts(id) { return this.db.prepare('SELECT seq,event_type AS type,at,epoch,revision,state,details FROM protocol_events WHERE request_id=? ORDER BY seq').all(id).map(r=>({...r,details:JSON.parse(r.details)})); }
|
|
1358
|
+
protocolState(id) {
|
|
1359
|
+
const status=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status;
|
|
1360
|
+
if(status!=='claimed') return status;
|
|
1361
|
+
const claim=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
1362
|
+
if(this.db.prepare('SELECT 1 FROM job_questions WHERE request_id=? AND claim_id=? AND epoch=? AND consumed_at IS NULL').get(id,claim.claim_id,claim.epoch)) return 'awaiting_input';
|
|
1363
|
+
if(this.db.prepare("SELECT 1 FROM artifacts WHERE request_id=? AND claim_id=? AND kind='upload' AND sealed=1 AND origin_claim_id=? AND origin_epoch=?").get(id,claim.claim_id,claim.claim_id,claim.epoch)) return 'result_staged';
|
|
1364
|
+
return claim.last_progress_at?'running':'leased';
|
|
1365
|
+
}
|
|
1366
|
+
protocolEventInTransaction(id,type,details={},epoch=null) {
|
|
1367
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1368
|
+
if(!this.isProtocolJob(id)||typeof type!=='string'||!type||epoch!==null&&!protocolNat(epoch))protocolError('invalid_protocol_event');
|
|
1369
|
+
const seq=this.db.prepare('SELECT COALESCE(max(seq),0)+1 AS seq FROM protocol_events WHERE request_id=?').get(id).seq;
|
|
1370
|
+
epoch??=this.db.prepare('SELECT epoch FROM claims WHERE request_id=?').get(id)?.epoch??0;
|
|
1371
|
+
this.db.prepare('INSERT INTO protocol_events VALUES(?,?,?,?,?,?,?,?)').run(id,seq,type,this.stamp(),epoch,this.protocolRevision(id),this.protocolState(id),JSON.stringify(canonical(details)));
|
|
1372
|
+
materializeProtocolWaiters(this,id);
|
|
1373
|
+
return seq;
|
|
1374
|
+
}
|
|
1375
|
+
advanceProtocolRevisionInTransaction(id) {
|
|
1376
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1377
|
+
return this.protocolCommands().advance(id,this.protocolRevision(id));
|
|
1378
|
+
}
|
|
1379
|
+
protocolCommands() {
|
|
1380
|
+
return createClaimCommands({db:this.db,clock:()=>this.nowMs(),maxLeaseMs:this.limits.leaseMs,
|
|
1381
|
+
authorize:c=>{
|
|
1382
|
+
const row=this.assertClaim(c.job,c.claim,c.subject,c.worker);
|
|
1383
|
+
const status=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(c.job)?.status;
|
|
1384
|
+
return {job:row.request_id,subject:row.subject,worker:row.worker,claim:row.claim_id,epoch:row.epoch,
|
|
1385
|
+
active:row.state==='active'&&status==='claimed',leaseUntil:this.leaseDeadlineClockMs(row)};
|
|
1386
|
+
}});
|
|
1387
|
+
}
|
|
1388
|
+
// The one place a native worker command checks the connection. It runs after the claim lookup and before the command
|
|
1389
|
+
// ledger replays or runs anything, in the transaction that commits the effect. A caller that omits connectionId is refused
|
|
1390
|
+
// in built-in mode (fail closed); external OAuth passes null and is unchanged.
|
|
1391
|
+
protocolMutationInTransaction(id,claimId,subject,worker,ctx,mutate,connectionId=null) {
|
|
1392
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1393
|
+
if(!this.isProtocolJob(id))protocolError('protocol_required');
|
|
1394
|
+
const claim=this.assertClaim(id,claimId,subject,worker);
|
|
1395
|
+
this.assertMutationConnection(id,claim,connectionId);
|
|
1396
|
+
const status=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status;
|
|
1397
|
+
if(['finished','cancelled'].includes(status)) throw questionError('TERMINAL','assignment is terminal');
|
|
1398
|
+
if(!ctx||typeof ctx.key!=='string'||!ctx.key||!protocolNat(ctx.revision)||typeof mutate!=='function')protocolError('command_context_required');
|
|
1399
|
+
if(ctx.epoch!==undefined&&ctx.epoch!==claim.epoch)protocolError('stale_authority');
|
|
1400
|
+
return this.protocolCommands().execute({job:id,subject,worker,claim:claimId,epoch:claim.epoch,
|
|
1401
|
+
key:ctx.key,expectedRevision:ctx.revision,operation:ctx.operation,args:ctx.args},mutate);
|
|
1402
|
+
}
|
|
1403
|
+
setClaimDeadlineInTransaction(id,leaseMs) {
|
|
1404
|
+
const activity=this.db.prepare('SELECT last_claim_activity_at FROM claims WHERE request_id=?').get(id)?.last_claim_activity_at;
|
|
1405
|
+
const deadline=Date.parse(activity??this.stamp())+leaseMs;
|
|
1406
|
+
if(!protocolNat(deadline))protocolError('invalid_lease');
|
|
1407
|
+
this.db.prepare('UPDATE claims SET lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=?')
|
|
1408
|
+
.run(iso(deadline),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id);
|
|
1409
|
+
}
|
|
1410
|
+
renewClaim(id,claimId,leaseMs,ctx,subject='local-principal',worker='dot',connectionId=null) {
|
|
1411
|
+
return this.transaction(()=>{
|
|
1412
|
+
const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
|
|
1413
|
+
{...ctx,operation:'renew',args:{leaseMs}},({leaseUntil})=>{
|
|
1414
|
+
this.db.prepare('UPDATE claims SET lease_ms=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
|
|
1415
|
+
.run(leaseMs,iso(leaseUntil),this.leaseBootId,this.leaseBootId?this.monotonicNow()+leaseMs:null,id,claimId);
|
|
1416
|
+
const claim=this.assertClaim(id,claimId,subject,worker);
|
|
1417
|
+
this.protocolEventInTransaction(id,'renewed',{lease_ms:leaseMs,lease_deadline_at:iso(leaseUntil)},claim.epoch);
|
|
1418
|
+
return {request_id:id,claim_id:claimId,epoch:claim.epoch,lease_expires_at:iso(leaseUntil)};
|
|
1419
|
+
},connectionId);
|
|
1420
|
+
return {...receipt.value,revision:receipt.revision,leaseUntil:receipt.leaseUntil};
|
|
1421
|
+
});
|
|
1422
|
+
}
|
|
1423
|
+
protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx,connectionId=null) {
|
|
1424
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
1425
|
+
// HTTP authenticates the subject; native admission checks visibility before any receipt lookup.
|
|
1426
|
+
if(!this.mayAct(worker,id)||typeof subject!=='string'||!subject)throw new Error('assignment not found');
|
|
1427
|
+
this.assertProtocolAvailable(id);
|
|
1428
|
+
if(!ctx||typeof ctx.key!=='string'||!ctx.key||ctx.key.length>512||!protocolNat(ctx.revision))protocolError('command_context_required');
|
|
1429
|
+
const command={job:id,subject,worker,operation:'claim',key:ctx.key,expectedRevision:ctx.revision,
|
|
1430
|
+
args:{claimant,acquisitionId,leaseMs:Object.hasOwn(ctx,'requestedLeaseMs')?ctx.requestedLeaseMs:leaseMs}};
|
|
1431
|
+
const identity=JSON.stringify(canonical(command));
|
|
1432
|
+
const old=this.db.prepare('SELECT identity,result FROM claim_command_receipts WHERE job=? AND command_key=?').get(id,ctx.key);
|
|
1433
|
+
if(old) {
|
|
1434
|
+
const receipt=JSON.parse(old.result);
|
|
1435
|
+
const current=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
1436
|
+
if(!current||current.subject!==subject||current.worker!==worker)protocolError('stale_authority');
|
|
1437
|
+
const priorCommand=JSON.parse(old.identity);
|
|
1438
|
+
if(priorCommand.operation==='claim'&&(current.claim_id!==receipt.claim_id||current.epoch!==receipt.epoch))protocolError('stale_authority');
|
|
1439
|
+
this.assertClaim(id,current.claim_id,subject,worker);
|
|
1440
|
+
if(this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='claimed')protocolError('stale_authority');
|
|
1441
|
+
if(old.identity!==identity)protocolError('command_conflict');
|
|
1442
|
+
this.assertRetryConnection(id,current,worker,connectionId);
|
|
1443
|
+
return receipt;
|
|
1444
|
+
}
|
|
1445
|
+
if(this.protocolRevision(id)!==ctx.revision)protocolError('revision_conflict');
|
|
1446
|
+
const previous=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
1447
|
+
if(previous?.state==='active'&&!this.leaseExpired(previous))protocolError('claim_busy');
|
|
1448
|
+
const value=this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId);
|
|
1449
|
+
if(value?.destination_refusal)return value;
|
|
1450
|
+
// Same acquisition with a fresh key cannot renew or invent a native claimed fact.
|
|
1451
|
+
const revision=previous?.claim_id===value.claim_id?this.protocolRevision(id):this.advanceProtocolRevisionInTransaction(id);
|
|
1452
|
+
if(previous?.claim_id!==value.claim_id)this.protocolEventInTransaction(id,'claimed',{claim_id:value.claim_id},value.epoch);
|
|
1453
|
+
const receipt={...value,revision,lease_expires_at:this.leaseExpiresAt(this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id))};
|
|
1454
|
+
this.db.prepare('INSERT INTO claim_command_receipts VALUES(?,?,?,?)').run(id,ctx.key,identity,JSON.stringify(canonical(receipt)));
|
|
1455
|
+
return receipt;
|
|
1456
|
+
}
|
|
1457
|
+
mayAct(worker,id) {
|
|
1458
|
+
const row=this.db.prepare('SELECT target_worker FROM assignments WHERE request_id=? UNION ALL SELECT target_worker FROM messages WHERE message_id=?').get(id,id);
|
|
1459
|
+
return !!row&&canSee(this.workers,worker,row.target_worker);
|
|
1460
|
+
}
|
|
1461
|
+
subscriptionVisible(sub) {
|
|
1462
|
+
if(!canSee(this.workers,sub.worker,sub.worker)) return false;
|
|
1463
|
+
try {
|
|
1464
|
+
// A pre-profile row cannot prove which OAuth client created it. Keep it only in legacy mode.
|
|
1465
|
+
if(sub.connection===null) return this.workers.legacy===true;
|
|
1466
|
+
const connection=this.subscriptionConnection(sub);
|
|
1467
|
+
if(connection.builtin&&(!this.connectionIsLive||!this.connectionIsLive(connection.connection_id))) return false;
|
|
1468
|
+
return resolveWorker(this.workers,connection)===sub.worker;
|
|
1469
|
+
} catch {return false;}
|
|
1470
|
+
}
|
|
1471
|
+
subscriptionActive(sub) { return !!sub&&sub.state==='active'&&sub.expires_at>this.stamp()&&this.subscriptionVisible(sub); }
|
|
1472
|
+
suppressSubscriptionRows(ids,reason) {
|
|
1473
|
+
for(const id of ids) {
|
|
1474
|
+
this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
|
|
1475
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error=? WHERE subscription_id=? AND state IN ('pending','failed')").run(reason,id);
|
|
1476
|
+
}
|
|
1477
|
+
return ids;
|
|
1478
|
+
}
|
|
1479
|
+
retireSubscription(id,reason='subscription inactive') { return this.transaction(()=>this.suppressSubscriptionRows([id],reason)); }
|
|
1480
|
+
retireConnectionSubscriptions(connectionId,reason='connection inactive') {
|
|
1481
|
+
if(!connectionId) return [];
|
|
1482
|
+
const ids=this.db.prepare('SELECT * FROM subscriptions').all().filter(sub=>{
|
|
1483
|
+
try { const connection=this.subscriptionConnection(sub); return connection?.builtin&&connection.connection_id===connectionId; } catch { return false; }
|
|
1484
|
+
}).map(sub=>sub.id);
|
|
1485
|
+
if(!ids.length) return [];
|
|
1486
|
+
return this.transaction(()=>this.suppressSubscriptionRows(ids,reason));
|
|
1487
|
+
}
|
|
1488
|
+
retireUnusableSubscription(sub,reason='subscription inactive') {
|
|
1489
|
+
if(!sub) return [];
|
|
1490
|
+
try {
|
|
1491
|
+
const connection=this.subscriptionConnection(sub);
|
|
1492
|
+
if(connection?.builtin&&this.connectionIsLive&&!this.connectionIsLive(connection.connection_id))
|
|
1493
|
+
return this.retireConnectionSubscriptions(connection.connection_id,reason);
|
|
1494
|
+
} catch { /* Retire the malformed or non-built-in subscription below. */ }
|
|
1495
|
+
return this.retireSubscription(sub.id,reason);
|
|
1496
|
+
}
|
|
1497
|
+
retireUnknownSubscriptions() {
|
|
1498
|
+
const retired=this.db.prepare("SELECT * FROM subscriptions WHERE state='active'").all().filter(sub=>!this.subscriptionActive(sub));
|
|
1499
|
+
if(!retired.length) return [];
|
|
1500
|
+
return this.transaction(()=>this.suppressSubscriptionRows(retired.map(sub=>sub.id),'subscription inactive'));
|
|
1501
|
+
}
|
|
1502
|
+
// Admission and wakes count shared worker lanes plus this subject's historical lanes, using recorded scope/key.
|
|
1503
|
+
// A takeover excludes the claim being replaced; changing or removing the profile cannot hide other active work.
|
|
1504
|
+
activeClaims(subject,worker,exceptId=null) {
|
|
1505
|
+
return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=? AND (c.lane_scope='worker' OR c.lane_key=?) AND c.request_id IS NOT ?").all(worker,subject,exceptId);
|
|
1506
|
+
}
|
|
1507
|
+
subscriptionFreeLanes(sub,laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
|
|
1508
|
+
return this.freeLanes(sub.principal,sub.worker,laneCapacity,claimCapacity);
|
|
1509
|
+
}
|
|
1510
|
+
activeSubscriptions() { return this.db.prepare("SELECT * FROM subscriptions WHERE state='active' AND expires_at>?").all(this.stamp()).filter(sub=>this.subscriptionActive(sub)); }
|
|
1511
|
+
// Text of a wake that names the queue head when several items wait: the worker claims oldest first via list_pending.
|
|
1512
|
+
queueHeadTitle(eligible,free) { return eligible.length>1?`${eligible.length} assignments queued (${free} free ${free===1?'lane':'lanes'}); claim oldest first via list_pending: ${JSON.parse(eligible[0].payload).brief}`:null; }
|
|
1513
|
+
// Wake for a new submission. When older items that this subscription may act on are queued, the wake names the queue head, not the
|
|
1514
|
+
// new item, so a worker that follows wakes does not take newer work ahead of older work. Who may claim what is unchanged.
|
|
1515
|
+
submitWake(id,sub) {
|
|
1516
|
+
// Skip items list_pending marks blocked (for example waiting on a destination approval): the worker cannot claim them now.
|
|
1517
|
+
const blocked=this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?');
|
|
1518
|
+
const eligible=this.rewakeCandidates(sub.id).filter(x=>!blocked.get(x.request_id));
|
|
1519
|
+
if(eligible.length>1&&eligible[0].request_id!==id&&eligible.some(x=>x.request_id===id))
|
|
1520
|
+
return this.queueEvent(id,sub,false,this.queueHeadTitle(eligible,this.subscriptionFreeLanes(sub,this.limits.laneCapacity??6)),'submit',eligible[0].request_id);
|
|
1521
|
+
return this.queueEvent(id,sub);
|
|
1522
|
+
}
|
|
1523
|
+
queueEvent(id, sub, force=false, title=null, wakeKind='submit', names=id) {
|
|
1524
|
+
sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(sub.id);
|
|
1525
|
+
if(!this.subscriptionActive(sub)||!this.mayAct(sub.worker,id)) return null;
|
|
1526
|
+
// Only assignment wakes (submit, rewake) dedupe: an owner-note event for the item never stands in for one.
|
|
1527
|
+
const existing=this.db.prepare("SELECT id,state FROM notifications WHERE request_id=? AND subscription_id=? AND wake_kind IN ('submit','rewake') AND state IN ('pending','sending','failed','delivered') ORDER BY created_at DESC, rowid DESC LIMIT 1").get(id,sub.id);
|
|
1528
|
+
if (existing && (!force || existing.state!=='delivered')) return existing.id;
|
|
1529
|
+
const payload=JSON.parse(this.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(id).payload);
|
|
1530
|
+
const eventId=`evt_${randomUUID()}`, body=JSON.stringify({eventId,name:'assignment.available',timestamp:this.stamp(),data:{request_id:names,title:(title??payload.brief).slice(0,160)},cursor:null});
|
|
1531
|
+
this.db.prepare('INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,?)').run(eventId,'event',id,sub.id,body,this.stamp(),wakeKind);
|
|
1532
|
+
return eventId;
|
|
1533
|
+
}
|
|
1534
|
+
// Queued assignments in list_pending order (normal before background, then oldest) with queued_at (see queuedAt).
|
|
1535
|
+
queuedRows() {
|
|
1536
|
+
return this.db.prepare(`SELECT a.request_id,a.payload,a.priority,a.target_worker,${queuedAt} queued_at FROM assignments a WHERE a.status='queued' AND a.cancelled_at IS NULL AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all();
|
|
1537
|
+
}
|
|
1538
|
+
// Break intervals [since, until or open] in ms. Owner since never reaches back before the previous break's end, so they are disjoint.
|
|
1539
|
+
breakIntervals() { return this.db.prepare('SELECT since,until FROM worker_breaks ORDER BY since').all().map(b=>[Date.parse(b.since),b.until?Date.parse(b.until):Infinity]); }
|
|
1540
|
+
// How long a row has been queued, minus usage-break time: the re-wake window and the unclaimed clock stand still during a break.
|
|
1541
|
+
queuedAgeMs(queuedAtText,now=this.nowMs(),breaks=this.breakIntervals()) {
|
|
1542
|
+
const from=Date.parse(queuedAtText);
|
|
1543
|
+
return breaks.reduce((age,[since,until])=>age-Math.max(0,Math.min(until,now)-Math.max(since,from)),now-from);
|
|
1544
|
+
}
|
|
1545
|
+
// Queued assignments that waited longer than the re-wake window, so re-wake no longer names them. Items with an uncertain or
|
|
1546
|
+
// sending owner delivery are left out: they wait for reconcile, not for the worker. Derived only: a requeue restarts the clock.
|
|
1547
|
+
unclaimedAfterReannounce(limits=this.limits,worker='dot') {
|
|
1548
|
+
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, breaks=worker==='dot'?this.breakIntervals():[];
|
|
1549
|
+
const rows=this.db.prepare(`SELECT a.request_id,${queuedAt} queued_at FROM assignments a WHERE a.target_worker=? AND a.status='queued' AND ${live(now)} ORDER BY queued_at`).all(worker).filter(r=>this.queuedAgeMs(r.queued_at,now,breaks)>=windowMs&&!this.uncertainDeliveries(r.request_id));
|
|
1550
|
+
return {count:rows.length,oldest_age_ms:rows.length?now-Date.parse(rows[0].queued_at):null,request_ids:rows.slice(0,10).map(r=>r.request_id)};
|
|
1551
|
+
}
|
|
1552
|
+
// Honest classification of queued work after its first event 2xx. Observations only: nothing here reclaims or cancels a claim.
|
|
1553
|
+
liveness(limits=this.limits, capacity=this.capacity, worker='dot') {
|
|
1554
|
+
const now=this.nowMs(), age=text=>now-Date.parse(text);
|
|
1555
|
+
const calls=this.db.prepare('SELECT max(last_call_at) call, max(last_list_pending_at) list FROM worker_activity WHERE worker=?').get(worker);
|
|
1556
|
+
const lastCall=calls.call??null, lastList=calls.list??null;
|
|
1557
|
+
const silence=lastCall?age(lastCall):Infinity;
|
|
1558
|
+
const claims=this.db.prepare("SELECT c.subject,c.worker,c.lane_key,c.lane_scope,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,c.last_progress_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' AND c.worker=?").all(worker);
|
|
1559
|
+
const staleClaims=claims.filter(c=>this.leaseExpired(c)&&!this.heldAfterStart(c));
|
|
1560
|
+
const liveSubs=this.activeSubscriptions().filter(sub=>sub.worker===worker);
|
|
1561
|
+
const liveClaims=liveSubs.flatMap(sub=>this.activeClaims(sub.principal,sub.worker));
|
|
1562
|
+
const hasLiveClaim=liveClaims.some(c=>now-Date.parse(c.last_claim_activity_at??c.claimed_at)<this.claimLeaseMs(c));
|
|
1563
|
+
const atCapacity=liveSubs.length>0&&liveSubs.every(sub=>this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity)===0);
|
|
1564
|
+
const hasSubscription=liveSubs.length>0;
|
|
1565
|
+
const items=this.db.prepare(`SELECT request_id,created_at,NOT (${live(now)}) expired FROM assignments WHERE target_worker=? AND status='queued' AND cancelled_at IS NULL ORDER BY created_at`).all(worker).map(row=>{
|
|
1566
|
+
// A queued row past its preparation's valid_until, or a protocol row past its retention, is 'expired', never alive_not_claiming: the worker cannot claim it.
|
|
1567
|
+
if(row.expired) return {request_id:row.request_id,class:'expired',event_2xx_age_ms:null};
|
|
1568
|
+
const first=this.db.prepare("SELECT min(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE kind='event' AND request_id=? AND state='delivered'").get(row.request_id).at;
|
|
1569
|
+
const eventAge=first?age(first):null;
|
|
1570
|
+
let cls=null;
|
|
1571
|
+
if(!hasSubscription) cls=null;
|
|
1572
|
+
else if(first===null) cls=age(row.created_at)>=limits.silenceMs?'transport_failing':null;
|
|
1573
|
+
else if(atCapacity&&hasLiveClaim) cls='at_capacity_healthy';
|
|
1574
|
+
else if(silence>=limits.silenceMs&&eventAge>=limits.silenceMs) cls='pause_suspected';
|
|
1575
|
+
else if(!atCapacity&&silence<limits.silenceMs&&eventAge>=2*limits.intervalMs) cls='alive_not_claiming';
|
|
1576
|
+
return {request_id:row.request_id,class:cls,event_2xx_age_ms:eventAge};
|
|
1577
|
+
});
|
|
1578
|
+
const queueClasses=Object.fromEntries(['pause_suspected','at_capacity_healthy','alive_not_claiming','transport_failing','expired'].map(name=>[name,items.filter(i=>i.class===name).length]));
|
|
1579
|
+
const ages=items.map(i=>i.event_2xx_age_ms).filter(x=>x!==null);
|
|
1580
|
+
return {
|
|
1581
|
+
claimed_outer_count:claims.length,max_claimed_outer_assignments:capacity,
|
|
1582
|
+
oldest_claim_age_ms:claims.length?Math.max(...claims.map(c=>age(c.claimed_at))):null,
|
|
1583
|
+
oldest_claim_progress_age_ms:claims.length?Math.max(...claims.map(c=>age(c.last_progress_at??c.claimed_at))):null,
|
|
1584
|
+
last_worker_call_at:lastCall,last_list_pending_at:lastList,
|
|
1585
|
+
oldest_unclaimed_event_2xx_age_ms:ages.length?Math.max(...ages):null,
|
|
1586
|
+
queue_classes:queueClasses,stale_claims:{count:staleClaims.length,max_idle_ms:staleClaims.length?Math.max(...staleClaims.map(c=>age(c.activity))):null},
|
|
1587
|
+
worker_silence_ms:Number.isFinite(silence)?silence:null,unclaimed_after_reannounce:this.unclaimedAfterReannounce(limits,worker),items
|
|
1588
|
+
};
|
|
1589
|
+
}
|
|
1590
|
+
recordWorkerCall(subject,tool,worker='dot') { return this.transaction(() => {
|
|
1591
|
+
const at=this.stamp();
|
|
1592
|
+
this.db.prepare(`INSERT INTO worker_activity(worker,subject,last_call_at,last_list_pending_at) VALUES(?,?,?,?)
|
|
1593
|
+
ON CONFLICT(worker,subject) DO UPDATE SET last_call_at=excluded.last_call_at,last_list_pending_at=COALESCE(excluded.last_list_pending_at,last_list_pending_at)`).run(worker,subject,at,tool==='list_pending'?at:null);
|
|
1594
|
+
this.db.prepare('INSERT INTO worker_calls(worker,subject,minute,tool,count,bytes) VALUES(?,?,?,?,1,0) ON CONFLICT(worker,subject,minute,tool) DO UPDATE SET count=count+1').run(worker,subject,Math.floor(this.nowMs()/60000),tool);
|
|
1595
|
+
// The worker's next authenticated tool call ends an active usage break.
|
|
1596
|
+
if(worker==='dot') { const active=this.activeBreak(); if(active) this.endBreak(active,'tool_call'); }
|
|
1597
|
+
}); }
|
|
1598
|
+
// Bytes of the serialized MCP response to one tool call, added once the response is written (the minute it was written).
|
|
1599
|
+
recordResponseBytes(subject,tool,bytes,worker='dot') {
|
|
1600
|
+
if(!Number.isInteger(bytes)||bytes<0) throw new Error('invalid response bytes');
|
|
1601
|
+
this.db.prepare('INSERT INTO worker_calls(worker,subject,minute,tool,count,bytes) VALUES(?,?,?,?,0,?) ON CONFLICT(worker,subject,minute,tool) DO UPDATE SET bytes=COALESCE(bytes,0)+excluded.bytes').run(worker,subject,Math.floor(this.nowMs()/60000),tool,bytes);
|
|
1602
|
+
}
|
|
1603
|
+
pruneWorkerCalls() { return this.db.prepare("DELETE FROM worker_calls WHERE minute<?").run(Math.floor((this.nowMs()-48*HOUR)/60000)).changes; }
|
|
1604
|
+
// Rolling-hour usage and the throttle verdicts. Claims are new claim epochs (lifecycle 'claimed', not 'resume').
|
|
1605
|
+
// Effective byte limits: the configured value, lowered by anything learned from a break ledger.
|
|
1606
|
+
byteLimits(limits=this.limits) {
|
|
1607
|
+
const learned=Object.fromEntries(this.db.prepare('SELECT name,value,break_id FROM learned_limits').all().map(r=>[r.name,r]));
|
|
1608
|
+
const lower=(configured,name)=>Math.min(configured,Math.max(learned[name]?.value??Infinity,Math.ceil(configured*learnedFloorFraction)));
|
|
1609
|
+
const hour=limits.maxResponseBytesPerHour??defaultRedeliveryLimits.maxResponseBytesPerHour, day=limits.maxResponseBytesPer24h??defaultRedeliveryLimits.maxResponseBytesPer24h;
|
|
1610
|
+
const callsHour=limits.maxToolCallsPerHour??defaultRedeliveryLimits.maxToolCallsPerHour, callsDay=limits.maxToolCallsPer24h??defaultRedeliveryLimits.maxToolCallsPer24h, claimsHour=limits.maxClaimsPerHour??defaultRedeliveryLimits.maxClaimsPerHour;
|
|
1611
|
+
return {hour:lower(hour,'response_bytes_per_hour'),day:lower(day,'response_bytes_per_24h'),callsHour:lower(callsHour,'tool_calls_per_hour'),callsDay:lower(callsDay,'tool_calls_per_24h'),claimsHour:lower(claimsHour,'claims_per_hour'),configuredClaims:claimsHour,
|
|
1612
|
+
configured:{hour,day},configuredCalls:{hour:callsHour,day:callsDay},learned};
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
rollingUsage(limits=this.limits) {
|
|
1616
|
+
const now=this.nowMs(), bl=this.byteLimits(limits), maxClaims=bl.claimsHour, maxCalls=bl.callsHour, maxCallsDay=bl.callsDay;
|
|
1617
|
+
const claims=this.db.prepare("SELECT count(*) n FROM lifecycle_events WHERE worker='dot' AND type='claimed' AND at>? AND COALESCE(reason,'')<>'resume'").get(iso(now-HOUR)).n;
|
|
1618
|
+
const minute=Math.floor(now/60000), {calls,bytes}=this.db.prepare("SELECT COALESCE(sum(count),0) calls,COALESCE(sum(bytes),0) bytes FROM worker_calls WHERE worker='dot' AND minute>?").get(minute-60);
|
|
1619
|
+
const {bytesDay,callsDay}=this.db.prepare("SELECT COALESCE(sum(bytes),0) bytesDay,COALESCE(sum(count),0) callsDay FROM worker_calls WHERE worker='dot' AND minute>?").get(minute-1440);
|
|
1620
|
+
const queued=this.db.prepare(`SELECT count(*) n FROM assignments WHERE status='queued' AND ${live(now)}`).get().n;
|
|
1621
|
+
// Estimates, not gates: the bridge holds work only on evidence (an owner-confirmed break, or a pause). Configured and
|
|
1622
|
+
// learned limits estimate usage; over_estimate names the limits reached for status and the usage_over_estimate alert.
|
|
1623
|
+
const overEstimate=[...(claims>=maxClaims?['claims_per_hour']:[]),...(calls>=maxCalls?['tool_calls_per_hour']:[]),...(callsDay>=maxCallsDay?['tool_calls_per_24h']:[]),...(bytes>=bl.hour?['response_bytes_per_hour']:[]),...(bytesDay>=bl.day?['response_bytes_per_24h']:[])];
|
|
1624
|
+
return {claims_last_hour:claims,tool_calls_last_hour:calls,tool_calls_last_24h:callsDay,response_bytes_last_hour:bytes,response_bytes_last_24h:bytesDay,queued,max_claims_per_hour:maxClaims,max_tool_calls_per_hour:maxCalls,max_tool_calls_per_24h:maxCallsDay,configured_tool_calls:bl.configuredCalls,configured_claims_per_hour:bl.configuredClaims,
|
|
1625
|
+
max_response_bytes_per_hour:bl.hour,max_response_bytes_per_24h:bl.day,configured_response_bytes:bl.configured,
|
|
1626
|
+
learned_response_bytes:Object.fromEntries(Object.entries(bl.learned).filter(([k])=>k.startsWith('response_bytes')).map(([k,r])=>[k,{value:r.value,break_id:r.break_id}])),
|
|
1627
|
+
learned_tool_calls:Object.fromEntries(Object.entries(bl.learned).filter(([k])=>k.startsWith('tool_calls')).map(([k,r])=>[k,{value:r.value,break_id:r.break_id}])),
|
|
1628
|
+
learned_claims_per_hour:bl.learned.claims_per_hour?{value:bl.learned.claims_per_hour.value,break_id:bl.learned.claims_per_hour.break_id}:null,
|
|
1629
|
+
over_estimate:overEstimate,
|
|
1630
|
+
// Kept for older readers: nothing is throttled by an estimate any more.
|
|
1631
|
+
rewake_throttled:false,submit_throttled:false,normal_rewake_throttled:false,holding:{rewake:[],submit:[]}};
|
|
1632
|
+
}
|
|
1633
|
+
// After a break is recorded, cut each byte and tool-call limit to 70% of what its ledger shows (DB-sourced, complete windows only).
|
|
1634
|
+
learnFromBreak(id,usage) {
|
|
1635
|
+
const put=this.db.prepare(`INSERT INTO learned_limits(name,value,break_id,ledger_bytes,at) VALUES(?,?,?,?,?)
|
|
1636
|
+
ON CONFLICT(name) DO UPDATE SET value=excluded.value,break_id=excluded.break_id,ledger_bytes=excluded.ledger_bytes,at=excluded.at WHERE excluded.value<learned_limits.value`);
|
|
1637
|
+
for(const [name,window,field,partial] of [['response_bytes_per_hour','1h','response_bytes','response_bytes_partial'],['response_bytes_per_24h','24h','response_bytes','response_bytes_partial'],
|
|
1638
|
+
['tool_calls_per_hour','1h','tool_calls','tool_calls_partial'],['tool_calls_per_24h','24h','tool_calls','tool_calls_partial']]) {
|
|
1639
|
+
const w=usage?.[window];
|
|
1640
|
+
if(!w||!Number.isInteger(w[field])||w[field]<=0||w[partial]) continue;
|
|
1641
|
+
put.run(name,Math.max(1,Math.floor(0.7*w[field])),id,w[field],this.stamp());
|
|
1642
|
+
}
|
|
1643
|
+
// Claims: the hour right before a break can be quiet, so learn from the busiest rolling hour of the 24 h.
|
|
1644
|
+
const peak=usage?.['24h']?.peak_claims_per_hour;
|
|
1645
|
+
if(Number.isInteger(peak)&&peak>0) put.run('claims_per_hour',Math.max(1,Math.floor(0.7*peak)),id,peak,this.stamp());
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
// Usage in the 1h/6h/24h before a break's since. tool_calls is null when worker_calls holds nothing older than since (the
|
|
1649
|
+
// counter did not exist yet), and tool_calls_partial marks a window that starts before the counter's first minute.
|
|
1650
|
+
// response_bytes (total and by tool) follows the same rule for byte accounting (migration 26). request_log holds what
|
|
1651
|
+
// break-usage-backfill merged from the request log; nothing here overwrites it except a new since (setBreak).
|
|
1652
|
+
usageBefore(sinceMs) {
|
|
1653
|
+
const first=this.db.prepare("SELECT min(minute) m FROM worker_calls WHERE worker='dot'").get().m, toMinute=Math.floor(sinceMs/60000);
|
|
1654
|
+
const firstBytes=this.db.prepare("SELECT min(minute) m FROM worker_calls WHERE worker='dot' AND bytes IS NOT NULL").get().m;
|
|
1655
|
+
return Object.fromEntries([['1h',HOUR],['6h',6*HOUR],['24h',24*HOUR]].map(([name,ms])=>{
|
|
1656
|
+
const from=iso(sinceMs-ms), to=iso(sinceMs), fromMinute=Math.floor((sinceMs-ms)/60000);
|
|
1657
|
+
const count=(type,extra='')=>this.db.prepare(`SELECT count(*) n FROM lifecycle_events WHERE worker='dot' AND type=? AND at>=? AND at<? ${extra}`).get(type,from,to).n;
|
|
1658
|
+
const calls=first===null||first>=toMinute?null:this.db.prepare("SELECT COALESCE(sum(count),0) n FROM worker_calls WHERE worker='dot' AND minute>=? AND minute<?").get(fromMinute,toMinute).n;
|
|
1659
|
+
const byTool=firstBytes===null||firstBytes>=toMinute?null:Object.fromEntries(this.db.prepare("SELECT tool,sum(bytes) bytes FROM worker_calls WHERE worker='dot' AND bytes>0 AND minute>=? AND minute<? GROUP BY tool ORDER BY sum(bytes) DESC,tool").all(fromMinute,toMinute).map(r=>[r.tool,r.bytes]));
|
|
1660
|
+
const peak=name==='24h'?(()=>{const t=this.db.prepare("SELECT at FROM lifecycle_events WHERE worker='dot' AND type='claimed' AND at>=? AND at<? AND COALESCE(reason,'')<>'resume' ORDER BY at").all(from,to).map(r=>Date.parse(r.at));let best=0,j=0;for(let i=0;i<t.length;i++){while(t[i]-t[j]>=HOUR)j++;best=Math.max(best,i-j+1);}return best;})():undefined;
|
|
1661
|
+
return [name,{claims:count('claimed',"AND COALESCE(reason,'')<>'resume'"),...(peak!==undefined?{peak_claims_per_hour:peak}:{}),finishes:count('completed'),tool_calls:calls,...(calls!==null&&first>fromMinute?{tool_calls_partial:true}:{}),
|
|
1662
|
+
checks_over_60s:this.db.prepare("SELECT count(*) n FROM check_runs r WHERE EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.claim_id=r.claim_id AND e.worker='dot') AND duration_ms>60000 AND created_at>=? AND created_at<?").get(from,to).n,
|
|
1663
|
+
response_bytes:byTool&&Object.values(byTool).reduce((n,b)=>n+b,0),...(byTool?{response_bytes_by_tool:byTool}:{}),...(byTool&&firstBytes>fromMinute?{response_bytes_partial:true}:{})}];
|
|
1664
|
+
}));
|
|
1665
|
+
}
|
|
1666
|
+
// Operator backfill from the request log for a break whose snapshot predates byte accounting (or to add the log's view).
|
|
1667
|
+
// Each window gets a request_log entry (source 'request_log'); DB-sourced claims, finishes, checks, tool calls and bytes
|
|
1668
|
+
// are never touched. since must match the break's since, so a moved break is not filled with another window's numbers.
|
|
1669
|
+
mergeBreakUsage(id,since,windows) { return this.transaction(() => {
|
|
1670
|
+
const row=Number.isInteger(id)&&id>0?this.db.prepare('SELECT * FROM worker_breaks WHERE id=?').get(id):null;
|
|
1671
|
+
if(!row) throw new Error('break not found');
|
|
1672
|
+
if(since!==row.since) throw new Error(`since mismatch: break ${id} since is ${row.since}`);
|
|
1673
|
+
const count=v=>Number.isInteger(v)&&v>=0, names=['1h','6h','24h'];
|
|
1674
|
+
if(!windows||typeof windows!=='object'||Array.isArray(windows)||Object.keys(windows).sort().join()!==[...names].sort().join()) throw new Error('windows must have exactly 1h, 6h and 24h');
|
|
1675
|
+
const usage=JSON.parse(row.usage);
|
|
1676
|
+
for(const name of names) {
|
|
1677
|
+
const w=windows[name], tools=w?.by_tool&&typeof w.by_tool==='object'&&!Array.isArray(w.by_tool)?Object.entries(w.by_tool):null;
|
|
1678
|
+
if(!w||typeof w!=='object'||Object.keys(w).some(k=>!['response_bytes','calls','by_tool','partial'].includes(k))||!count(w.response_bytes)||!count(w.calls)||!tools||tools.length>64||
|
|
1679
|
+
w.partial!==undefined&&typeof w.partial!=='boolean'||tools.some(([tool,v])=>!/^[a-z0-9_]{1,64}$/.test(tool)||!v||typeof v!=='object'||Object.keys(v).sort().join()!=='bytes,calls'||!count(v.bytes)||!count(v.calls))||
|
|
1680
|
+
tools.reduce((n,[,v])=>n+v.bytes,0)!==w.response_bytes||tools.reduce((n,[,v])=>n+v.calls,0)!==w.calls) throw new Error(`invalid ${name} window`);
|
|
1681
|
+
const byTool=Object.fromEntries(tools.sort((a,b)=>b[1].bytes-a[1].bytes||a[0].localeCompare(b[0])).map(([tool,v])=>[tool,{calls:v.calls,bytes:v.bytes}]));
|
|
1682
|
+
usage[name]={...usage[name],request_log:{source:'request_log',response_bytes:w.response_bytes,calls:w.calls,by_tool:byTool,...(w.partial?{partial:true}:{})}};
|
|
1683
|
+
}
|
|
1684
|
+
const next=JSON.stringify(usage), updated=next!==row.usage;
|
|
1685
|
+
if(updated) this.db.prepare('UPDATE worker_breaks SET usage=? WHERE id=?').run(next,id);
|
|
1686
|
+
return {id,since:row.since,updated,usage_before:usage};
|
|
1687
|
+
}); }
|
|
1688
|
+
// Limitation: usage breaks are tracked only for the default worker (`dot`). Break evidence and probe budgets are not per worker.
|
|
1689
|
+
activeBreak() { return this.db.prepare('SELECT * FROM worker_breaks WHERE until IS NULL').get()??null; }
|
|
1690
|
+
// The break that holds work: only an owner-confirmed one. An inferred break (silence) is reported and alerted, not held on.
|
|
1691
|
+
holdingBreak() { const b=this.activeBreak(); return b?.source==='owner'?b:null; }
|
|
1692
|
+
breakState() {
|
|
1693
|
+
const b=this.activeBreak();
|
|
1694
|
+
return b?{active:true,id:b.id,since:b.since,reason:b.reason,source:b.source,duration_ms:this.nowMs()-Date.parse(b.since),last_probe_at:b.last_probe_at}:{active:false,since:null,reason:null,source:null,duration_ms:null};
|
|
1695
|
+
}
|
|
1696
|
+
breaks() {
|
|
1697
|
+
return this.db.prepare('SELECT * FROM worker_breaks ORDER BY id').all().map(b=>({id:b.id,since:b.since,until:b.until,reason:b.reason,source:b.source,end_source:b.end_source,
|
|
1698
|
+
duration_ms:(b.until?Date.parse(b.until):this.nowMs())-Date.parse(b.since),usage_before:JSON.parse(b.usage),last_probe_at:b.last_probe_at}));
|
|
1699
|
+
}
|
|
1700
|
+
startBreak({since,reason,source}) {
|
|
1701
|
+
const usage=this.usageBefore(Date.parse(since));
|
|
1702
|
+
const {lastInsertRowid}=this.db.prepare('INSERT INTO worker_breaks(since,reason,source,usage,created_at) VALUES(?,?,?,?,?)').run(since,reason,source,JSON.stringify(usage),this.stamp());
|
|
1703
|
+
// Only an owner-confirmed break teaches limits. An inferred break starts at the worker's last call, so the hour before it
|
|
1704
|
+
// is quiet by construction and 70% of it is no limit at all. An owner mark over an inferred break learns then.
|
|
1705
|
+
if(source==='owner') this.learnFromBreak(Number(lastInsertRowid),usage);
|
|
1706
|
+
return this.breakState();
|
|
1707
|
+
}
|
|
1708
|
+
learnedLimits() { return this.db.prepare('SELECT name,value,break_id,ledger_bytes ledger_value,at FROM learned_limits ORDER BY name').all(); }
|
|
1709
|
+
clearLearnedLimits() { return this.transaction(()=>{ const removed=this.learnedLimits(); this.db.prepare('DELETE FROM learned_limits').run(); return {cleared:removed.length,removed}; }); }
|
|
1710
|
+
// Estimated limits that usage has reached, with the configured value and, where a break lowered it, the learned one.
|
|
1711
|
+
overEstimate(limits=this.limits) {
|
|
1712
|
+
const u=this.rollingUsage(limits), learned=Object.fromEntries(this.learnedLimits().map(r=>[r.name,r]));
|
|
1713
|
+
const configured={response_bytes_per_hour:u.configured_response_bytes.hour,response_bytes_per_24h:u.configured_response_bytes.day,
|
|
1714
|
+
tool_calls_per_hour:u.configured_tool_calls.hour,tool_calls_per_24h:u.configured_tool_calls.day,claims_per_hour:u.configured_claims_per_hour};
|
|
1715
|
+
const effective={response_bytes_per_hour:u.max_response_bytes_per_hour,response_bytes_per_24h:u.max_response_bytes_per_24h,
|
|
1716
|
+
tool_calls_per_hour:u.max_tool_calls_per_hour,tool_calls_per_24h:u.max_tool_calls_per_24h,claims_per_hour:u.max_claims_per_hour};
|
|
1717
|
+
const used={response_bytes_per_hour:u.response_bytes_last_hour,response_bytes_per_24h:u.response_bytes_last_24h,
|
|
1718
|
+
tool_calls_per_hour:u.tool_calls_last_hour,tool_calls_per_24h:u.tool_calls_last_24h,claims_per_hour:u.claims_last_hour};
|
|
1719
|
+
return u.over_estimate.map(name=>({name,used:used[name],limit:effective[name],configured:configured[name],
|
|
1720
|
+
...(learned[name]&&effective[name]<configured[name]?{learned:learned[name].value,break_id:learned[name].break_id}:{})}));
|
|
1721
|
+
}
|
|
1722
|
+
// Owner mark. Over an active break (e.g. an inferred one) it takes over: source owner, new reason, since if given, fresh snapshot.
|
|
1723
|
+
setBreak(reason,since=null) { return this.transaction(() => {
|
|
1724
|
+
if(typeof reason!=='string'||!reason.trim()||reason.length>512) throw new Error('invalid reason');
|
|
1725
|
+
const active=this.activeBreak(), at=since??active?.since??this.stamp();
|
|
1726
|
+
if(!Number.isFinite(Date.parse(at))||Date.parse(at)>this.nowMs()) throw new Error('since must not be in the future');
|
|
1727
|
+
const ended=this.db.prepare('SELECT max(until) u FROM worker_breaks WHERE until IS NOT NULL').get().u;
|
|
1728
|
+
if(ended&&Date.parse(at)<Date.parse(ended)) throw new Error(`since must not be before the end of the previous break (${ended})`);
|
|
1729
|
+
if(!active) return this.startBreak({since:at,reason,source:'owner'});
|
|
1730
|
+
const usage=this.usageBefore(Date.parse(at));
|
|
1731
|
+
this.db.prepare("UPDATE worker_breaks SET reason=?,source='owner',since=?,usage=? WHERE id=?").run(reason,at,JSON.stringify(usage),active.id);
|
|
1732
|
+
// Confirming an inferred break without --since keeps its since (the worker's last call), so its last hour is still quiet:
|
|
1733
|
+
// learn the 24 h budgets and the claims peak, not the hourly limits.
|
|
1734
|
+
this.learnFromBreak(active.id,active.source==='inferred'&&!since?{...usage,'1h':undefined}:usage);
|
|
1735
|
+
return this.breakState();
|
|
1736
|
+
}); }
|
|
1737
|
+
clearBreak() { return this.transaction(() => {
|
|
1738
|
+
const active=this.activeBreak();
|
|
1739
|
+
if(active) this.endBreak(active,'owner');
|
|
1740
|
+
return {cleared:!!active,...(active?{id:active.id,since:active.since}:{}),worker_break:this.breakState()};
|
|
1741
|
+
}); }
|
|
1742
|
+
// End a usage break, by owner clear or by the worker's next tool call. A break never moves a claim's lease deadline: only the
|
|
1743
|
+
// claimant's own progress extends a lease, so a claim with no progress for one lease period is released even across a break.
|
|
1744
|
+
// Call inside a transaction.
|
|
1745
|
+
endBreak(active,endSource) {
|
|
1746
|
+
this.db.prepare('UPDATE worker_breaks SET until=?,end_source=? WHERE id=?').run(this.stamp(),endSource,active.id);
|
|
1747
|
+
}
|
|
1748
|
+
// Inferred start: no worker tool call (any subject) for breakSilenceMs, an availability event got a 2xx after the last call,
|
|
1749
|
+
// and work is queued. since is the last call. A worker that never called is not inferred (no known silence start), and a break
|
|
1750
|
+
// that ended after the last call (an owner clear) is not re-inferred until the worker calls again.
|
|
1751
|
+
inferBreak(limits=this.limits) { return this.transaction(() => {
|
|
1752
|
+
if(this.activeBreak()) return null;
|
|
1753
|
+
const now=this.nowMs(), silenceMs=limits.breakSilenceMs??defaultRedeliveryLimits.breakSilenceMs;
|
|
1754
|
+
const last=this.db.prepare("SELECT max(last_call_at) at FROM worker_activity WHERE worker='dot'").get().at;
|
|
1755
|
+
if(!last||now-Date.parse(last)<silenceMs) return null;
|
|
1756
|
+
const event=this.db.prepare("SELECT max(last_event_2xx_at) at FROM subscriptions WHERE worker='dot'").get().at;
|
|
1757
|
+
if(!event||Date.parse(event)<=Date.parse(last)) return null;
|
|
1758
|
+
if(!this.db.prepare("SELECT 1 FROM assignments WHERE status='queued' AND target_worker='dot'").get()) return null;
|
|
1759
|
+
if(this.db.prepare('SELECT 1 FROM worker_breaks WHERE until>=?').get(last)) return null;
|
|
1760
|
+
return this.startBreak({since:last,reason:`inferred: no worker tool call for ${Math.round(silenceMs/60000)} min after an availability event was delivered, with work queued`,source:'inferred'});
|
|
1761
|
+
}); }
|
|
1762
|
+
// Breaks whose start or end alert has not gone out yet; the caller marks each after it publishes.
|
|
1763
|
+
breakAlertsDue() { return this.db.prepare('SELECT * FROM worker_breaks WHERE (until IS NULL AND attention_published_at IS NULL) OR (until IS NOT NULL AND attention_published_at IS NOT NULL AND end_alerted_at IS NULL) ORDER BY id').all(); }
|
|
1764
|
+
observeBreakAlert(id,at) { this.db.prepare('UPDATE worker_breaks SET alert_first_observed_at=? WHERE id=? AND attention_published_at IS NULL').run(at,id); }
|
|
1765
|
+
markBreakAlert(id,edge) {
|
|
1766
|
+
const now=this.stamp();
|
|
1767
|
+
if(edge==='start')this.db.prepare('UPDATE worker_breaks SET start_alerted_at=?,attention_published_at=? WHERE id=?').run(now,now,id);
|
|
1768
|
+
else this.db.prepare('UPDATE worker_breaks SET end_alerted_at=? WHERE id=?').run(now,id);
|
|
1769
|
+
}
|
|
1770
|
+
// A break notice is moot once its break ended or none of its requests is still queued.
|
|
1771
|
+
breakNoticeMoot(item) {
|
|
1772
|
+
const {break_id,request_ids=[]}=JSON.parse(item.body??'{}');
|
|
1773
|
+
if(this.db.prepare('SELECT until FROM worker_breaks WHERE id=?').get(break_id)?.until!==null) return true;
|
|
1774
|
+
return !request_ids.some(id=>this.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='queued'").get(id));
|
|
1775
|
+
}
|
|
1776
|
+
breakNotices(id) { return this.db.prepare('SELECT b.break_id,b.created_at at,b.request_ids FROM break_notices b, json_each(b.request_ids) j WHERE j.value=? ORDER BY b.created_at').all(id).map(r=>({break_id:r.break_id,at:r.at,text:breakNoticeText(JSON.parse(r.request_ids))})); }
|
|
1777
|
+
// Lease expiry only makes a claim eligible for takeover; it does not revoke the current holder. A takeover changes the active claim_id.
|
|
1778
|
+
// Only the active holder's claim_id extends the lease, so a stale holder cannot keep a new holder's claim alive.
|
|
1779
|
+
// A claim past its deadline is never refreshed (Store.assertClaim refuses it); only the sweep or a new claim moves it on.
|
|
1780
|
+
touchClaim(id,claimId,subject,worker='dot',connectionId=null) { return this.inTransaction(()=>
|
|
1781
|
+
this.touchHeldClaim(id,claimId,subject,worker,c=>this.assertMutationConnection(id,c,connectionId))); }
|
|
1782
|
+
// `authorize` runs on the live claim row before the write. An exact claim retry passes none: assertRetryConnection already proved the holder.
|
|
1783
|
+
touchHeldClaim(id,claimId,subject,worker,authorize=null) {
|
|
1784
|
+
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
1785
|
+
if(!c)return;
|
|
1786
|
+
authorize?.(c);
|
|
1787
|
+
this.refreshClaimActivity(id,claimId);
|
|
1788
|
+
}
|
|
1789
|
+
refreshClaimActivity(id,claimId) {
|
|
1790
|
+
const at=this.stamp(), claim=this.db.prepare('SELECT lease_ms FROM claims WHERE request_id=? AND claim_id=?').get(id,claimId);
|
|
1791
|
+
if(this.isProtocolJob(id)) this.db.prepare('UPDATE claims SET last_claim_activity_at=? WHERE request_id=? AND claim_id=?').run(at,id,claimId);
|
|
1792
|
+
else this.db.prepare('UPDATE claims SET last_claim_activity_at=?,lease_deadline_at=?,lease_boot_id=?,lease_deadline_monotonic_ms=? WHERE request_id=? AND claim_id=?')
|
|
1793
|
+
.run(at,iso(Date.parse(at)+(claim?.lease_ms??this.limits.leaseMs)),this.leaseBootId,this.leaseBootId?this.monotonicNow()+(claim?.lease_ms??this.limits.leaseMs):null,id,claimId);
|
|
1794
|
+
}
|
|
1795
|
+
// The active, unexpired claim this worker holds under claimId, or null. A missing or expired claim is left to the caller's own error.
|
|
1796
|
+
liveHeldClaim(id,claimId,subject,worker) {
|
|
1797
|
+
if(!this.mayAct(worker,id))return null;
|
|
1798
|
+
const c=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND state='active'").get(id,claimId);
|
|
1799
|
+
return !c||c.subject!==subject||c.worker!==worker||this.leaseExpired(c)?null:c;
|
|
1800
|
+
}
|
|
1801
|
+
// Read-only connection check for a workspace tool, run synchronously right before the tool body (after its last await).
|
|
1802
|
+
// It writes nothing, so a refusal leaves the worktree, the workspace rows and the activity counters as they were.
|
|
1803
|
+
assertWorkerConnection(id,claimId,subject,worker='dot',connectionId=null) {
|
|
1804
|
+
const c=this.liveHeldClaim(id,claimId,subject,worker);
|
|
1805
|
+
if(c)this.assertMutationConnection(id,c,connectionId);
|
|
1806
|
+
}
|
|
1807
|
+
// The `get` cursor. Only the live holding connection moves it; any other caller (revoked, replaced, a different
|
|
1808
|
+
// connection of the same worker) reads and changes nothing. Check and write share one transaction. Returns whether it moved.
|
|
1809
|
+
markNotesSeenByHolder(id,subject,worker='dot',connectionId=null) { return this.inTransaction(()=>{
|
|
1810
|
+
if(!this.mayAct(worker,id))return false;
|
|
1811
|
+
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND subject=? AND worker=? AND state='active'").get(id,subject,worker);
|
|
1812
|
+
if(!claim)return false;
|
|
1813
|
+
try { this.assertMutationConnection(id,claim,connectionId); }
|
|
1814
|
+
catch(error) { if(error.destination?.error==='connection_not_live')return false; throw error; }
|
|
1815
|
+
this.markNotesSeen(id,subject,worker);
|
|
1816
|
+
return true;
|
|
1817
|
+
}); }
|
|
1818
|
+
// Unfenced: for callers that already proved the holder inside their own claim transaction (exact retry, resume). `get` uses markNotesSeenByHolder.
|
|
1819
|
+
markNotesSeen(id,subject,worker='dot') { if(!this.mayAct(worker,id)) return; this.db.prepare("UPDATE claims SET last_seen_note_seq=COALESCE((SELECT max(sequence) FROM owner_notes n WHERE n.request_id=claims.request_id),0) WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(id,subject,worker); }
|
|
1820
|
+
// One UPDATE per tool call that names an assignment; it matches only that worker's active claim, so a denied or foreign call counts nowhere.
|
|
1821
|
+
recordToolActivity(id,subject,worker,tool,{workspace=false,error=null,connectionId=null}={}) { return this.inTransaction(()=>{
|
|
1822
|
+
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND subject=? AND worker=? AND state='active'").get(id,subject,worker);
|
|
1823
|
+
if(!claim)return;
|
|
1824
|
+
this.assertMutationConnection(id,claim,connectionId);
|
|
1825
|
+
const at=this.stamp();
|
|
1826
|
+
this.db.prepare("UPDATE claims SET tool_calls=tool_calls+1,last_tool=?,last_tool_at=?,last_tool_error=?,first_workspace_tool_at=CASE WHEN ? THEN COALESCE(first_workspace_tool_at,?) ELSE first_workspace_tool_at END WHERE request_id=? AND subject=? AND worker=? AND state='active'").run(tool,at,error===null?null:String(error).slice(0,200),workspace?1:0,at,id,subject,worker);
|
|
1827
|
+
}); }
|
|
1828
|
+
static toolActivity(c) { return {acquisition_id:c.acquisition_id??null,tool_calls:c.tool_calls??0,last_tool:c.last_tool??null,last_tool_at:c.last_tool_at??null,last_tool_error:c.last_tool_error??null,first_workspace_tool_at:c.first_workspace_tool_at??null}; }
|
|
1829
|
+
// For example: "lease_expired: <calls>, last <tool> at <time>, no workspace tool".
|
|
1830
|
+
static expirySummary(c) {
|
|
1831
|
+
const a=Store.toolActivity(c), t=x=>x.slice(11,19)+'Z';
|
|
1832
|
+
return `lease_expired: ${a.tool_calls} call${a.tool_calls===1?'':'s'}${a.last_tool?`, last ${a.last_tool} at ${t(a.last_tool_at)}`:''}${a.first_workspace_tool_at?`, first workspace tool at ${t(a.first_workspace_tool_at)}`:', no workspace tool'}${a.last_tool_error?`, last error: ${a.last_tool_error.slice(0,80)}`:''}`;
|
|
1833
|
+
}
|
|
1834
|
+
failureFields(id) {
|
|
1835
|
+
const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
|
|
1836
|
+
if(!a) {const policy=this.pullQueue.inbox(id);return policy?{failure_type:policy.failure_type,failure_type_source:policy.failure_type_source}:{failure_type:'unknown',failure_type_source:'unknown'};}
|
|
1837
|
+
const report=this.db.prepare('SELECT outcome,summary,result FROM reports WHERE request_id=?').get(id);
|
|
1838
|
+
const failedReport=!!report&&report.outcome!=='completed';
|
|
1839
|
+
const checkFailedObserved=!!this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='check_failed' LIMIT 1").get(id);
|
|
1840
|
+
if(a.status!=='cancelled'&&!failedReport) return {failure_type:null,failure_type_source:null,check_failed_observed:checkFailedObserved};
|
|
1841
|
+
const cancelActor=a.status==='cancelled'?this.db.prepare("SELECT actor FROM lifecycle_events WHERE request_id=? AND type='cancelled' ORDER BY id DESC LIMIT 1").get(id)?.actor:null;
|
|
1842
|
+
const observed=observeTransition({status:a.status,reason:a.cancelled_reason,cancelActor,
|
|
1843
|
+
leaseExpired:a.status==='cancelled'&&!!this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='abandoned' AND actor='system' AND reason LIKE 'lease_expired%' LIMIT 1").get(id)});
|
|
1844
|
+
const inferred=report?inferWorkerReport(report):null;
|
|
1845
|
+
const result=observed??inferred;
|
|
1846
|
+
return result?{failure_type:result.type,failure_type_source:result.source,check_failed_observed:checkFailedObserved}:{failure_type:'unknown',failure_type_source:'unknown',check_failed_observed:checkFailedObserved};
|
|
1847
|
+
}
|
|
1848
|
+
claimLeaseMs(claim) { return claim.lease_ms??this.limits.leaseMs; }
|
|
1849
|
+
leaseMonotonicDeadline(claim) {
|
|
1850
|
+
const deadline=Number(claim.lease_deadline_monotonic_ms);
|
|
1851
|
+
return this.leaseBootId&&claim.lease_boot_id===this.leaseBootId&&Number.isFinite(deadline)?deadline:null;
|
|
1852
|
+
}
|
|
1853
|
+
leaseDeadlineClockMs(claim) {
|
|
1854
|
+
const deadline=this.leaseMonotonicDeadline(claim);
|
|
1855
|
+
return deadline===null?Date.parse(this.leaseExpiresAt(claim)):Math.floor(this.nowMs()+deadline-this.monotonicNow());
|
|
1856
|
+
}
|
|
1857
|
+
leaseExpiresAt(claim) { return claim.lease_deadline_at??new Date(Date.parse(claim.last_claim_activity_at??claim.claimed_at)+this.claimLeaseMs(claim)).toISOString(); }
|
|
1858
|
+
// True while a claim idle since before this process started is inside its post-start window (start + its own lease).
|
|
1859
|
+
heldAfterStart(claim) {
|
|
1860
|
+
const activity=Date.parse(claim.activity??claim.last_claim_activity_at??claim.claimed_at);
|
|
1861
|
+
return activity<this.startedMs&&this.nowMs()<this.startedMs+this.claimLeaseMs(claim);
|
|
1862
|
+
}
|
|
1863
|
+
leaseExpired(claim) {
|
|
1864
|
+
const deadline=this.leaseMonotonicDeadline(claim);
|
|
1865
|
+
return deadline===null?this.nowMs()>=Date.parse(this.leaseExpiresAt(claim)):this.monotonicNow()>=deadline;
|
|
1866
|
+
}
|
|
1867
|
+
// A revoked grant cannot authorize a successor until its deadline and all
|
|
1868
|
+
// host effect channels have stopped. Unknown stop evidence fails closed.
|
|
1869
|
+
assertRegrantReady(claim) {
|
|
1870
|
+
if(!this.leaseExpired(claim)) throw new Error('claim_busy: prior lease has not expired');
|
|
1871
|
+
if(this.db.prepare("SELECT 1 FROM check_jobs WHERE request_id=? AND (status='running' OR stop_verified IS NOT 1) LIMIT 1").get(claim.request_id)) {
|
|
1872
|
+
throw new Error('claim_effects_unverified: prior host work has not verifiably stopped');
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
// Deliveries that may already have reached a destination. Reclaim and abandon wait while this notice is uncertain or sending.
|
|
1876
|
+
// Aging ends automatic retries, not the authority fence: a terminal unknown can still land late.
|
|
1877
|
+
// Owner-facing deliveries only: a webhook availability event in flight is not a result that may have reached the owner.
|
|
1878
|
+
// A break notice is no result and never holds a claim or a re-wake back.
|
|
1879
|
+
uncertainDeliveries(id) {
|
|
1880
|
+
const notices=this.db.prepare("SELECT count(*) n FROM notifications WHERE request_id=? AND kind NOT IN ('event','break') AND state IN ('uncertain','sending','uncertain_terminal','waiting')").get(id).n;
|
|
1881
|
+
const questions=this.db.prepare(`SELECT count(*) n FROM protocol_delivery_attempts p
|
|
1882
|
+
JOIN durable_waiter_deliveries d USING(delivery_id)
|
|
1883
|
+
WHERE d.job=? AND d.acknowledged_at IS NULL AND p.state IN ('sending','unknown')
|
|
1884
|
+
AND json_extract(d.fact,'$.type')='questioned'`).get(id).n;
|
|
1885
|
+
return notices+questions;
|
|
1886
|
+
}
|
|
1887
|
+
assertNoUncertainDelivery(id) { if(this.uncertainDeliveries(id)) throw new Error('uncertain_delivery: reconcile first'); }
|
|
1888
|
+
// A new claim_id carries the worktree and the SEALED uploads over (artifacts keep origin_claim_id and origin_epoch); check jobs, check runs and their outputs keep the claim_id they ran under.
|
|
1889
|
+
// Unsealed staging stays bound to the old claim: it cannot be continued, cited or sealed. Its client alias is released (client_artifact_id NULL)
|
|
1890
|
+
// so the new epoch can upload a fresh artifact under the same alias. The old row and its bytes stay as evidence until retention cleanup removes them.
|
|
1891
|
+
rebindClaim(id,claimId) {
|
|
1892
|
+
// Called only after an actual epoch change, inside the claim transaction.
|
|
1893
|
+
// Retire only typed worker questions, not owner wait messages, result receipts,
|
|
1894
|
+
// watches or break notices. Generation fields, never timestamps, fence them.
|
|
1895
|
+
this.db.prepare(`UPDATE notifications SET state='suppressed',last_error='claim epoch superseded question'
|
|
1896
|
+
WHERE request_id=? AND kind IN ('blocker','wait') AND state IN ('pending','failed')
|
|
1897
|
+
AND CASE WHEN json_valid(body) THEN
|
|
1898
|
+
json_type(body,'$.note')='text' AND json_type(body,'$.epoch')='integer'
|
|
1899
|
+
AND json_type(body,'$.owner_note_seq')='integer'
|
|
1900
|
+
AND json_extract(body,'$.epoch')>=1
|
|
1901
|
+
AND json_extract(body,'$.epoch')<(SELECT epoch FROM claims WHERE request_id=? AND claim_id=?)
|
|
1902
|
+
ELSE 0 END`).run(id,id,claimId);
|
|
1903
|
+
// The worktree is not an artifact: it is mutable working state the new epoch is meant to continue, so it moves with the claim.
|
|
1904
|
+
this.db.prepare('UPDATE workspaces SET claim_id=? WHERE request_id=?').run(claimId,id);
|
|
1905
|
+
// Release only mutable alias heads; immutable upload history and old bytes stay.
|
|
1906
|
+
this.db.prepare('DELETE FROM artifact_journal_heads WHERE job=? AND sealed=0 AND origin_claim<>?').run(id,claimId);
|
|
1907
|
+
this.db.prepare("UPDATE artifacts SET client_artifact_id=NULL WHERE request_id=? AND kind='upload' AND claim_id<>? AND NOT (sealed=1 AND sha256 IS NOT NULL)").run(id,claimId);
|
|
1908
|
+
this.db.prepare("UPDATE artifacts SET claim_id=? WHERE request_id=? AND kind='upload' AND sealed=1 AND sha256 IS NOT NULL").run(claimId,id);
|
|
1909
|
+
}
|
|
1910
|
+
// Sealed uploads of an assignment. inherited is true when an earlier epoch created the upload and a later claim now holds it.
|
|
1911
|
+
sealedUploads(id,{clientIds=false}={}) {
|
|
1912
|
+
const epoch=this.db.prepare('SELECT epoch FROM claims WHERE request_id=?').get(id)?.epoch??null;
|
|
1913
|
+
return this.db.prepare(`SELECT ${clientIds?'COALESCE(client_artifact_id,id)':'id'} id,size,sha256,origin_claim_id,origin_epoch FROM artifacts WHERE request_id=? AND kind='upload' AND sealed=1`).all(id)
|
|
1914
|
+
.map(r=>({...r,inherited:r.origin_epoch!==null&&epoch!==null&&r.origin_epoch<epoch}));
|
|
1915
|
+
}
|
|
1916
|
+
// Claimed assignments of this subject with owner notes the claimant has not yet read through get or claim.
|
|
1917
|
+
attention(subject,worker='dot') {
|
|
1918
|
+
return this.db.prepare(`SELECT c.request_id,count(n.sequence) note_count FROM claims c JOIN assignments a USING(request_id) JOIN owner_notes n ON n.request_id=c.request_id AND n.sequence>c.last_seen_note_seq
|
|
1919
|
+
WHERE c.subject=? AND c.worker=? AND a.status='claimed' AND c.state='active' GROUP BY c.request_id ORDER BY min(n.sequence)`).all(subject,worker).filter(x=>this.mayAct(worker,x.request_id)).map(x=>({request_id:x.request_id,note_count:Number(x.note_count)}));
|
|
1920
|
+
}
|
|
1921
|
+
denialNotes() {
|
|
1922
|
+
const cursor=name=>this.db.prepare('SELECT value FROM alert_cursors WHERE name=?').get(name).value;
|
|
1923
|
+
const progress=this.db.prepare('SELECT id,note text FROM progress WHERE id>? ORDER BY id').all(cursor('denial_progress'));
|
|
1924
|
+
const reports=this.db.prepare('SELECT rowid id,summary text FROM reports WHERE rowid>? ORDER BY rowid').all(cursor('denial_report'));
|
|
1925
|
+
return {matches:[...progress,...reports].filter(x=>denialPattern.test(x.text)).map(x=>x.text),progressMax:progress.at(-1)?.id,reportMax:reports.at(-1)?.id};
|
|
1926
|
+
}
|
|
1927
|
+
ackDenialNotes({progressMax,reportMax}) {
|
|
1928
|
+
const set=this.db.prepare('UPDATE alert_cursors SET value=? WHERE name=?');
|
|
1929
|
+
if(progressMax!==undefined) set.run(progressMax,'denial_progress');
|
|
1930
|
+
if(reportMax!==undefined) set.run(reportMax,'denial_report');
|
|
1931
|
+
}
|
|
1932
|
+
// Flat queue re-wake. Per active subscription, each tick queues at most one ordinary availability event (wake_kind
|
|
1933
|
+
// 'rewake'), and only when the subscription's principal has a free lane, no assignment wake (submit or rewake) for the
|
|
1934
|
+
// subscription is pending, sending or failed (a failed one is being retried, at most a minute apart, and that retry is the
|
|
1935
|
+
// wake), the last wake that went out to it (submit, rewake or owner note; delivered or sending; a suppressed one woke
|
|
1936
|
+
// nobody) is at least rewakeMs old, and some queued item is eligible (rewakeCandidates). Message events and owner notes
|
|
1937
|
+
// never hold it back through pending or failed rows. The event names the first eligible item in list_pending order (the
|
|
1938
|
+
// oldest, normal work first) and says how many lanes are free; it marks nothing else delivered and touches no other row. startAttempt checks it again before it is sent.
|
|
1939
|
+
reannounceQueued(limits=this.limits) { return this.transaction(() => {
|
|
1940
|
+
// A lane freed since the last tick (laneFreed) waives the rewakeMs cadence once; every other gate below still applies.
|
|
1941
|
+
const dispatchNow=this.dispatchWake; this.dispatchWake=false;
|
|
1942
|
+
if (this.paused()||!this.db.prepare("SELECT 1 FROM assignments WHERE status='queued'").get()) return {announced:0};
|
|
1943
|
+
const now=this.nowMs(), rewakeMs=dispatchNow?0:limits.rewakeMs??defaultRedeliveryLimits.rewakeMs;
|
|
1944
|
+
// During an owner-confirmed usage break the only re-wake is one probe every breakProbeMs (first one breakProbeMs after
|
|
1945
|
+
// since). An inferred break is silence, not evidence, so it does not pace re-wakes.
|
|
1946
|
+
const brk=this.holdingBreak();
|
|
1947
|
+
let probe=false,heldBreak=false,heldCapacity=false;
|
|
1948
|
+
const outstanding=this.db.prepare("SELECT 1 FROM notifications WHERE subscription_id=? AND state IN ('pending','sending','failed') AND wake_kind IN ('submit','rewake') LIMIT 1");
|
|
1949
|
+
const lastWake=this.db.prepare(`SELECT max(at) at FROM (SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE subscription_id=?1 AND state='delivered' AND wake_kind IN ('submit','rewake','owner_note')
|
|
1950
|
+
UNION ALL SELECT max(COALESCE(attempt_started_at,created_at)) FROM notifications WHERE subscription_id=?1 AND state='sending' AND wake_kind IN ('submit','rewake','owner_note'))`);
|
|
1951
|
+
let announced=0;
|
|
1952
|
+
for (const sub of this.activeSubscriptions()) {
|
|
1953
|
+
if(this.capacityHoldUntil(sub.worker)) {heldCapacity=true;continue;}
|
|
1954
|
+
if(sub.worker==='dot'&&brk&&(probe||now-Date.parse(brk.last_probe_at??brk.since)<(limits.breakProbeMs??defaultRedeliveryLimits.breakProbeMs))) {heldBreak=true;continue;}
|
|
1955
|
+
if(this.subscriptionFreeLanes(sub,limits.laneCapacity??6)<=0||outstanding.get(sub.id)) continue;
|
|
1956
|
+
const last=lastWake.get(sub.id).at;
|
|
1957
|
+
if(last&&rewakeMs&&now-Date.parse(last)<rewakeMs) continue;
|
|
1958
|
+
const eligible=this.rewakeCandidates(sub.id,limits);
|
|
1959
|
+
if(!eligible.length) continue;
|
|
1960
|
+
this.queueEvent(eligible[0].request_id,sub,true,this.queueHeadTitle(eligible,this.subscriptionFreeLanes(sub,limits.laneCapacity??6)),'rewake');
|
|
1961
|
+
announced++;
|
|
1962
|
+
if(brk&&sub.worker==='dot') { this.db.prepare('UPDATE worker_breaks SET last_probe_at=? WHERE id=?').run(this.stamp(),brk.id); probe=true; }
|
|
1963
|
+
}
|
|
1964
|
+
return {announced,...(probe?{probe:true}:{}),...(!announced&&heldBreak?{worker_break:true}:{}),...(!announced&&heldCapacity?{capacity_denied:true}:{})};
|
|
1965
|
+
}); }
|
|
1966
|
+
// Queued items a re-wake may name, in list_pending order: no uncertain or sending owner delivery (never re-wake those),
|
|
1967
|
+
// the latest assignment wake (submit or rewake; owner notes and messages do not count) for this subscription not rejected
|
|
1968
|
+
// by the callback with HTTP 410 or 413 (terminal), and, once queued rewakeWindowMs or longer, no wake delivered or sending
|
|
1969
|
+
// for the item in the last rewakeStaleMs (a backoff: a stale item stays eligible but is re-woken rarely).
|
|
1970
|
+
rewakeCandidates(subscriptionId,limits=this.limits) {
|
|
1971
|
+
const now=this.nowMs(), windowMs=limits.rewakeWindowMs??defaultRedeliveryLimits.rewakeWindowMs, staleMs=limits.rewakeStaleMs??defaultRedeliveryLimits.rewakeStaleMs, breaks=this.breakIntervals();
|
|
1972
|
+
const latest=this.db.prepare("SELECT state,last_error FROM notifications WHERE request_id=? AND subscription_id=? AND wake_kind IN ('submit','rewake') ORDER BY created_at DESC, rowid DESC LIMIT 1");
|
|
1973
|
+
const lastSent=this.db.prepare("SELECT max(COALESCE(attempt_started_at,created_at)) at FROM notifications WHERE request_id=? AND subscription_id=? AND state IN ('delivered','sending') AND wake_kind IN ('submit','rewake')");
|
|
1974
|
+
const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(subscriptionId);
|
|
1975
|
+
if(!sub||!this.subscriptionVisible(sub)) return [];
|
|
1976
|
+
const denied=new Set(this.deniedQueued(sub.worker).map(d=>d.request_id));
|
|
1977
|
+
return this.queuedRows().filter(row=>{
|
|
1978
|
+
if(!this.mayAct(sub.worker,row.request_id)||denied.has(row.request_id)||this.uncertainDeliveries(row.request_id)) return false;
|
|
1979
|
+
const event=latest.get(row.request_id,subscriptionId);
|
|
1980
|
+
if(event?.state==='suppressed'&&/^HTTP 41[03]$/.test(event.last_error??'')) return false;
|
|
1981
|
+
if(this.queuedAgeMs(row.queued_at,now,sub.worker==='dot'?breaks:[])<windowMs) return true;
|
|
1982
|
+
const sent=lastSent.get(row.request_id,subscriptionId).at;
|
|
1983
|
+
return !sent||now-Date.parse(sent)>=staleMs;
|
|
1984
|
+
});
|
|
1985
|
+
}
|
|
1986
|
+
// Why a queued re-wake must not be sent now, or null. Its eligibility was decided when it was queued; drain may send it
|
|
1987
|
+
// later, after the head was claimed, a delivery for it turned uncertain or the last free lane filled.
|
|
1988
|
+
rewakeStale(row) {
|
|
1989
|
+
const sub=this.db.prepare("SELECT * FROM subscriptions WHERE id=? AND state='active' AND expires_at>?").get(row.subscription_id,this.stamp());
|
|
1990
|
+
if(!sub||!this.subscriptionVisible(sub)) return 'subscription inactive';
|
|
1991
|
+
if(this.subscriptionFreeLanes(sub)<=0) return 'no free lane';
|
|
1992
|
+
if(this.capacityHoldUntil(sub.worker)) return 'the worker reported a capacity denial; waiting for a slot';
|
|
1993
|
+
if(!this.rewakeCandidates(row.subscription_id).some(x=>x.request_id===row.request_id)) return 'head no longer eligible';
|
|
1994
|
+
return null;
|
|
1995
|
+
}
|
|
1996
|
+
subscribe(id, url, secret, expires, principal='local-principal',worker='dot',connection=null) {
|
|
1997
|
+
const old=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(id);
|
|
1998
|
+
if(old&&old.worker!==worker) throw new Error('subscription worker conflict');
|
|
1999
|
+
if(connection&&resolveWorker(this.workers,connection)!==worker) throw new Error('subscription connection conflict');
|
|
2000
|
+
if(connection?.builtin&&(!this.connectionIsLive||!this.connectionIsLive(connection.connection_id))) throw new Error('subscription connection inactive');
|
|
2001
|
+
const recordedConnection=connection?JSON.stringify(canonical(connection)):null;
|
|
2002
|
+
const replacing=old&&(old.connection?JSON.stringify(canonical(this.subscriptionConnection(old))):null)!==recordedConnection;
|
|
2003
|
+
if(replacing&&(!connection||old.principal!==principal||old.url!==url)) throw new Error('subscription identity conflict');
|
|
2004
|
+
if (old && this.subscriptionSecret(old)!==secret) {
|
|
2005
|
+
const pending=this.db.prepare("SELECT count(*) n FROM notifications WHERE subscription_id=? AND state IN ('pending','sending','failed')").get(id).n;
|
|
2006
|
+
if (pending) {
|
|
2007
|
+
this.db.prepare('UPDATE subscriptions SET rotation_blocked=1 WHERE id=?').run(id);
|
|
2008
|
+
throw Object.assign(new Error('signing_key_rotation_blocked'), { pending });
|
|
2009
|
+
}
|
|
2010
|
+
}
|
|
2011
|
+
return this.transaction(() => {
|
|
2012
|
+
if(replacing) {
|
|
2013
|
+
// A verified re-subscribe creates a new row for the same worker, never updates an immutable connection.
|
|
2014
|
+
// Retire unsent events before replaying the queue for the new connection under the stable subscription ID.
|
|
2015
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='subscription connection replaced' WHERE subscription_id=? AND state IN ('pending','sending','failed')").run(id);
|
|
2016
|
+
this.db.prepare('DELETE FROM assignment_reannouncements WHERE subscription_id=?').run(id);
|
|
2017
|
+
this.db.prepare('DELETE FROM subscriptions WHERE id=?').run(id);
|
|
2018
|
+
}
|
|
2019
|
+
this.db.prepare(`INSERT INTO subscriptions(id,principal,url,args,secret,expires_at,verified_at,state,rotation_blocked,worker,connection) VALUES(?,? ,?,'{}',?,?,?,'active',0,?,?)
|
|
2020
|
+
ON CONFLICT(id) DO UPDATE SET secret=excluded.secret,expires_at=excluded.expires_at,verified_at=excluded.verified_at,state='active',auth_failures=0,rotation_blocked=0`).run(id,principal,url,this.sealSubscription(id, 'secret', secret),expires,this.stamp(),worker,recordedConnection === null ? null : this.sealSubscription(id, 'connection', recordedConnection));
|
|
2021
|
+
const queued=this.db.prepare("SELECT request_id FROM assignments WHERE status='queued' ORDER BY created_at").all();
|
|
2022
|
+
for (const row of queued) if(!this.uncertainDeliveries(row.request_id)) this.queueEvent(row.request_id,{id},true);
|
|
2023
|
+
for (const row of this.db.prepare("SELECT message_id,preview FROM messages WHERE status='pending' ORDER BY created_at").all()) {
|
|
2024
|
+
const existing=this.db.prepare("SELECT 1 FROM notifications WHERE message_id=? AND subscription_id=? AND state IN ('pending','sending','failed','delivered')").get(row.message_id,id);
|
|
2025
|
+
if(!existing) this.queueMessageEvent(row.message_id,row.preview,{id});
|
|
2026
|
+
}
|
|
2027
|
+
}); }
|
|
2028
|
+
unsubscribe(id) { return this.transaction(() => {
|
|
2029
|
+
this.db.prepare("UPDATE subscriptions SET state='revoked' WHERE id=?").run(id);
|
|
2030
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='subscription revoked' WHERE subscription_id=? AND state IN ('pending','failed')").run(id);
|
|
2031
|
+
}); }
|
|
2032
|
+
get(id) {
|
|
2033
|
+
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) { const work=this.pullQueue.row(id);if(work)return this.pullQueue.project(work);throw new Error('assignment not found'); }
|
|
2034
|
+
this.assertProtocolAvailable(id);
|
|
2035
|
+
const claimRow=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
2036
|
+
const claim=claimRow&&(({acquisition_id,tool_calls,last_tool,last_tool_at,last_tool_error,first_workspace_tool_at,destination_revision,...rest})=>({...rest,...(destination_revision?{destination_revision}:{}),lease_expires_at:this.leaseExpiresAt(claimRow),activity:Store.toolActivity(claimRow)}))(claimRow);
|
|
2037
|
+
const report=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
|
|
2038
|
+
if(report?.workspace_evidence) report.workspace_evidence=JSON.parse(report.workspace_evidence);
|
|
2039
|
+
// Everything in a report is the worker's own statement. Only a check row carries bridge_verified, and only when the bridge ran it.
|
|
2040
|
+
if(report) { report.trust=TRUST.worker; Object.assign(report,Store.resultAuthority(!!report.late)); }
|
|
2041
|
+
const lateRow=this.db.prepare('SELECT summary,truncated,full_sha256,created_at FROM late_evidence WHERE request_id=? ORDER BY created_at LIMIT 1').get(id);
|
|
2042
|
+
const late_evidence=lateRow?{...lateRow,truncated:!!lateRow.truncated}:null;
|
|
2043
|
+
const progress=this.db.prepare('SELECT note,created_at FROM progress WHERE request_id=? ORDER BY id').all(id);
|
|
2044
|
+
const delivery=this.db.prepare('SELECT id,kind,state,attempts,last_error,argv,attempt_started_at,attempt_id,last_reconciled_at,uncertain_reason,terminal_at,terminal_reason FROM notifications WHERE request_id=? ORDER BY created_at').all(id).map(n=>({...n,argv:n.argv?JSON.parse(n.argv):null}));
|
|
2045
|
+
const watch=this.db.prepare('SELECT deadline,state,updated_at,notification_id FROM watches WHERE request_id=?').get(id) || null;
|
|
2046
|
+
const supersedes=this.db.prepare('SELECT target_id AS request_id,created_at FROM submit_supersedes WHERE request_id=?').get(id)??null;
|
|
2047
|
+
const superseded_by=this.db.prepare('SELECT request_id,created_at FROM submit_supersedes WHERE target_id=?').get(id)??null;
|
|
2048
|
+
const authorityRevoked=!!a.cancelled_at||this.isProtocolJob(id)&&a.status==='finished';
|
|
2049
|
+
return {...this.destinationFields(id),...(this.pullQueue.row(id)?{work_order_id:this.pullQueue.row(id).work_order_id,child_request_id:id}:{}),request_id:id,supersedes,superseded_by,target_worker:a.target_worker,assignment:JSON.parse(a.payload),delivery_mode:a.delivery,t3_muted:this.deliveryMuted(id),thread_id:a.thread_id||null,environment_id:a.environment_id||null,status:a.status,execution:a.execution,required_capabilities:a.required_capabilities?JSON.parse(a.required_capabilities):[],review:!!a.review,created_at:a.created_at,valid_until:a.valid_until??null,valid_until_source:a.valid_until_source??null,expiry_requeues:a.expiry_requeues??0,...this.failureFields(id),cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancellation_requested:!!a.cancelled_at,authority_revoked:authorityRevoked,...this.sandboxStop(id,authorityRevoked),claim,progress,lifecycle_events:this.db.prepare("SELECT type,at,actor,reason FROM lifecycle_events WHERE request_id=? ORDER BY id").all(id),report:report??null,late_evidence,delivery,watch,owner_notes:this.ownerNotes(id),worker_break_notices:this.breakNotices(id),claim_denied:this.claimDenial(id),skipped_by_worker:a.skipped_at?{at:a.skipped_at,listed_count:a.listed_count,passed_over:a.passed_over}:null,pr_preflights:this.db.prepare("SELECT phase,evidence FROM pr_preflights WHERE request_id=? ORDER BY CASE phase WHEN 'submit' THEN 0 ELSE 1 END").all(id).map(row=>({phase:row.phase,...JSON.parse(row.evidence)}))};
|
|
2050
|
+
}
|
|
2051
|
+
recordPrPreflight(id,phase,assignment,evidence,replace=false) {
|
|
2052
|
+
assertPreflight(assignment,evidence,this.nowMs());
|
|
2053
|
+
if(evidence) this.db.prepare(`INSERT ${replace?'OR REPLACE ':''}INTO pr_preflights(request_id,phase,evidence) VALUES(?,?,?)`).run(id,phase,JSON.stringify(evidence));
|
|
2054
|
+
}
|
|
2055
|
+
hasAssignment(id) { return !!this.db.prepare('SELECT 1 FROM assignments WHERE request_id=?').get(id); }
|
|
2056
|
+
ownerNotes(id) { return this.db.prepare('SELECT id,at,text FROM owner_notes WHERE request_id=? ORDER BY sequence').all(id); }
|
|
2057
|
+
questions(id) { this.assertProtocolAvailable(id);return this.db.prepare('SELECT * FROM job_questions WHERE request_id=? ORDER BY rowid').all(id); }
|
|
2058
|
+
askQuestion(id,claimId,questionId,text,subject='local-principal',worker='dot',ctx=null,connectionId=null) {
|
|
2059
|
+
validateQuestion(questionId,text);
|
|
2060
|
+
return this.progress(id,claimId,`QUESTION: ${text}`,subject,false,worker,{questionId,text},ctx,connectionId);
|
|
2061
|
+
}
|
|
2062
|
+
assertQuestionGrant(id,question) {
|
|
2063
|
+
const claim=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
2064
|
+
if(!claim||claim.state!=='active'||claim.claim_id!==question.claim_id||claim.epoch!==question.epoch) throw questionError('STALE_EPOCH','question belongs to an earlier grant. Ask the worker to claim or continue this assignment and ask a new question with a new ID; then answer that new question.');
|
|
2065
|
+
try { return this.assertClaim(id,question.claim_id,question.subject,question.worker); }
|
|
2066
|
+
catch(error) {
|
|
2067
|
+
let refusal;try{refusal=JSON.parse(error.message);}catch{throw error;}
|
|
2068
|
+
if(refusal.error!=='lease_expired') throw error;
|
|
2069
|
+
throw new Error(JSON.stringify({...refusal,message:`The lease for question ${question.question_id} on ${id} expired. Ask the worker to reclaim this assignment and ask a new question with a new ID; then answer that new question. This unanswered question remains an audit fact and grants no authority.`}));
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
answerQuestion(id,questionId,text,ctx=null,ownerToken=null) {
|
|
2073
|
+
return this.isProtocolJob(id)?answerProtocolQuestion(this,id,questionId,text,ownerToken,ctx):this.transaction(()=>this.answerQuestionInTransaction(id,questionId,text));
|
|
2074
|
+
}
|
|
2075
|
+
answerQuestionInTransaction(id,questionId,text) {
|
|
2076
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
2077
|
+
validateQuestion(questionId,text);
|
|
2078
|
+
const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
2079
|
+
if(!assignment) throw new Error('assignment not found');
|
|
2080
|
+
if(['finished','cancelled'].includes(assignment.status)) throw questionError('TERMINAL','assignment is terminal');
|
|
2081
|
+
const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId);
|
|
2082
|
+
if(!question) throw questionError('NO_QUESTION','question does not exist');
|
|
2083
|
+
const claim=this.assertQuestionGrant(id,question);
|
|
2084
|
+
if(question.answered_at!==null) throw questionError('ALREADY_ANSWERED','question already has an answer');
|
|
2085
|
+
this.db.prepare('UPDATE job_questions SET answer=?,answered_at=? WHERE request_id=? AND question_id=?').run(text,this.stamp(),id,questionId);
|
|
2086
|
+
this.lifecycle(id,'waiting','owner',`question:answer:${questionId}`,claim);
|
|
2087
|
+
this.db.prepare(`UPDATE notifications SET state='suppressed',last_error='structured question answered'
|
|
2088
|
+
WHERE request_id=? AND kind IN ('blocker','wait') AND state IN ('pending','failed','waiting')
|
|
2089
|
+
AND CASE WHEN json_valid(body) THEN json_extract(body,'$.question_id') END=?
|
|
2090
|
+
AND CASE WHEN json_valid(body) THEN json_extract(body,'$.epoch') END=?`).run(id,questionId,claim.epoch);
|
|
2091
|
+
for(const sub of this.activeSubscriptions().filter(sub=>sub.worker===claim.worker&&this.mayAct(sub.worker,id))) {
|
|
2092
|
+
const eventId=`evt_${randomUUID()}`;
|
|
2093
|
+
const body=JSON.stringify({eventId,name:'assignment.available',timestamp:this.stamp(),data:{request_id:id,title:`Answer available for question ${questionId}`},cursor:null});
|
|
2094
|
+
this.db.prepare("INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,'event',?,?,?,?,'owner_note')").run(eventId,id,sub.id,body,this.stamp());
|
|
2095
|
+
this.db.prepare('INSERT INTO question_answer_wakes(notification_id,request_id,question_id,epoch) VALUES(?,?,?,?)').run(eventId,id,questionId,claim.epoch);
|
|
2096
|
+
}
|
|
2097
|
+
return {request_id:id,question_id:questionId,answered:true};
|
|
2098
|
+
}
|
|
2099
|
+
consumeAnswer(id,claimId,questionId,subject='local-principal',worker='dot',ctx=null,connectionId=null) { return this.transaction(()=>{
|
|
2100
|
+
if(!this.isProtocolJob(id)) {
|
|
2101
|
+
this.assertMutationConnection(id,this.assertClaim(id,claimId,subject,worker),connectionId);
|
|
2102
|
+
return this.consumeAnswerInTransaction(id,claimId,questionId,subject,worker);
|
|
2103
|
+
}
|
|
2104
|
+
const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,{...ctx,operation:'consume',args:{question_id:questionId}},()=>{
|
|
2105
|
+
const result=this.consumeAnswerInTransaction(id,claimId,questionId,subject,worker);
|
|
2106
|
+
if(result.duplicate) protocolError('answer_already_consumed');
|
|
2107
|
+
this.protocolEventInTransaction(id,'consumed',{question_id:questionId},this.assertClaim(id,claimId,subject,worker).epoch);
|
|
2108
|
+
return result;
|
|
2109
|
+
},connectionId);
|
|
2110
|
+
return {...receipt.value,revision:receipt.revision};
|
|
2111
|
+
}); }
|
|
2112
|
+
consumeAnswerInTransaction(id,claimId,questionId,subject='local-principal',worker='dot') {
|
|
2113
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
2114
|
+
validateQuestion(questionId);
|
|
2115
|
+
const claim=this.assertClaim(id,claimId,subject,worker);
|
|
2116
|
+
const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
2117
|
+
if(['finished','cancelled'].includes(assignment?.status)) throw questionError('TERMINAL','assignment is terminal');
|
|
2118
|
+
const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(id,questionId);
|
|
2119
|
+
if(!question) throw questionError('NO_QUESTION','question does not exist');
|
|
2120
|
+
if(question.claim_id!==claim.claim_id||question.epoch!==claim.epoch) throw questionError('STALE_EPOCH','question belongs to an earlier grant');
|
|
2121
|
+
if(question.answered_at===null) throw questionError('NO_ANSWER','question has not been answered');
|
|
2122
|
+
const duplicate=question.consumed_at!==null;
|
|
2123
|
+
if(!duplicate) {
|
|
2124
|
+
this.db.prepare('UPDATE job_questions SET consumed_at=? WHERE request_id=? AND question_id=?').run(this.stamp(),id,questionId);
|
|
2125
|
+
this.lifecycle(id,'working',`worker:${subject}`,`question:consume:${questionId}`,claim);
|
|
2126
|
+
}
|
|
2127
|
+
return {question_id:questionId,answer:question.answer,duplicate};
|
|
2128
|
+
}
|
|
2129
|
+
assertQuestionsResolved(id,claimId,outcome='completed') {
|
|
2130
|
+
if(['blocked','failed'].includes(outcome)) return true;
|
|
2131
|
+
const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
2132
|
+
if(assignment?.status==='cancelled') return true; // Preserve late evidence after cancellation.
|
|
2133
|
+
if(this.db.prepare('SELECT 1 FROM job_questions WHERE request_id=? AND claim_id=? AND consumed_at IS NULL').get(id,claimId)) throw questionError('QUESTION_OPEN','consume the current grant\'s outstanding answers before finishing');
|
|
2134
|
+
return true;
|
|
2135
|
+
}
|
|
2136
|
+
questionWakeCurrent(row) {
|
|
2137
|
+
if(row.kind!=='event'||row.wake_kind!=='owner_note') return true;
|
|
2138
|
+
const wake=this.db.prepare('SELECT * FROM question_answer_wakes WHERE notification_id=?').get(row.id);
|
|
2139
|
+
if(!wake) return true;
|
|
2140
|
+
const assignment=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(wake.request_id);
|
|
2141
|
+
if(assignment?.status!=='claimed') return false;
|
|
2142
|
+
const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(wake.request_id,wake.question_id);
|
|
2143
|
+
if(!question||question.answered_at===null||question.consumed_at!==null||question.epoch!==wake.epoch) return false;
|
|
2144
|
+
try { this.assertQuestionGrant(row.request_id,question);return true; } catch { return false; }
|
|
2145
|
+
}
|
|
2146
|
+
note(id,text) { return this.transaction(() => {
|
|
2147
|
+
this.assertProtocolAvailable(id);
|
|
2148
|
+
validateOwnerNote(text,this.ownerNotes(id));
|
|
2149
|
+
const assignment=this.db.prepare('SELECT payload FROM assignments WHERE request_id=?').get(id);
|
|
2150
|
+
if(!assignment) throw new Error('assignment not found');
|
|
2151
|
+
const note={id:`note_${randomUUID()}`,at:this.stamp(),text};
|
|
2152
|
+
this.db.prepare('INSERT INTO owner_notes(id,request_id,at,text) VALUES(?,?,?,?)').run(note.id,id,note.at,note.text);
|
|
2153
|
+
for(const sub of this.activeSubscriptions().filter(sub=>this.mayAct(sub.worker,id))) {
|
|
2154
|
+
const eventId=`evt_${randomUUID()}`;
|
|
2155
|
+
const body=JSON.stringify({eventId,name:'assignment.available',timestamp:this.stamp(),data:{request_id:id,title:`Owner note ${note.id}: `+JSON.parse(assignment.payload).brief.slice(0,120)},cursor:null});
|
|
2156
|
+
this.db.prepare("INSERT INTO notifications(id,kind,request_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,'owner_note')").run(eventId,'event',id,sub.id,body,this.stamp());
|
|
2157
|
+
}
|
|
2158
|
+
return {request_id:id,...note};
|
|
2159
|
+
}); }
|
|
2160
|
+
tell(text,worker='dot') { return this.transaction(() => {
|
|
2161
|
+
if(worker==='pool') throw new Error('worker \"pool\" is not supported');
|
|
2162
|
+
const messageId=`msg_${randomUUID()}`, preview=text.slice(0,200), createdAt=this.stamp();
|
|
2163
|
+
this.db.prepare('INSERT INTO messages(message_id,text,text_sha256,preview,created_at,target_worker) VALUES(?,?,?,?,?,?)').run(messageId,text,hash(text),preview,createdAt,worker);
|
|
2164
|
+
for(const sub of this.activeSubscriptions()) this.queueMessageEvent(messageId,preview,sub);
|
|
2165
|
+
return {message_id:messageId,status:'pending',created_at:createdAt,text_sha256:hash(text),preview};
|
|
2166
|
+
}); }
|
|
2167
|
+
queueMessageEvent(messageId,title,sub) {
|
|
2168
|
+
sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(sub.id);
|
|
2169
|
+
if(!this.subscriptionActive(sub)||!this.mayAct(sub.worker,messageId)) return null;
|
|
2170
|
+
const eventId=`evt_${randomUUID()}`;
|
|
2171
|
+
const body=JSON.stringify({eventId,name:'assignment.available',timestamp:this.stamp(),data:{message_id:messageId,title},cursor:null});
|
|
2172
|
+
this.db.prepare("INSERT INTO notifications(id,kind,request_id,message_id,subscription_id,body,created_at,wake_kind) VALUES(?,?,?,?,?,?,?,'message')").run(eventId,'event',null,messageId,sub.id,body,this.stamp());
|
|
2173
|
+
return eventId;
|
|
2174
|
+
}
|
|
2175
|
+
untell(id,worker=null) { return this.transaction(() => {
|
|
2176
|
+
const row=this.getMessage(id,worker);
|
|
2177
|
+
if(row.status==='acknowledged') throw new Error('message already acknowledged');
|
|
2178
|
+
if(row.status!=='withdrawn') {
|
|
2179
|
+
this.db.prepare("UPDATE messages SET status='withdrawn' WHERE message_id=?").run(id);
|
|
2180
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='message withdrawn' WHERE message_id=? AND state IN ('pending','failed')").run(id);
|
|
2181
|
+
}
|
|
2182
|
+
return this.getMessage(id);
|
|
2183
|
+
}); }
|
|
2184
|
+
listMessages(worker='dot') { return this.db.prepare("SELECT message_id,preview,created_at FROM messages WHERE status='pending' ORDER BY created_at").all().filter(r=>this.mayAct(worker,r.message_id)).slice(0,50); }
|
|
2185
|
+
getMessage(id,worker=null) {
|
|
2186
|
+
if(worker!==null&&!this.mayAct(worker,id)) throw new Error('message not found');
|
|
2187
|
+
const row=this.db.prepare('SELECT message_id,text,text_sha256,preview,status,created_at,acknowledged_at FROM messages WHERE message_id=?').get(id);
|
|
2188
|
+
if(!row) throw new Error('message not found');
|
|
2189
|
+
return row;
|
|
2190
|
+
}
|
|
2191
|
+
ackMessage(id,worker='dot') { return this.transaction(() => {
|
|
2192
|
+
if(!this.mayAct(worker,id)) throw new Error('message not found');
|
|
2193
|
+
const row=this.db.prepare('SELECT status FROM messages WHERE message_id=?').get(id);
|
|
2194
|
+
if(!row) throw new Error('message not found');
|
|
2195
|
+
if(row.status==='withdrawn') throw new Error('message withdrawn');
|
|
2196
|
+
if(row.status!=='acknowledged') this.db.prepare("UPDATE messages SET status='acknowledged',acknowledged_at=? WHERE message_id=?").run(this.stamp(),id);
|
|
2197
|
+
return this.getMessage(id);
|
|
2198
|
+
}); }
|
|
2199
|
+
// Resume wake. DALAN_RESUME_IDLE_MS (default 120000; 0 disables everything below). A claim is idle when its holder made no
|
|
2200
|
+
// claim-bearing call (progress, workspace tools, finish, a repeated claim) for that long. last_claim_activity_at is the clock, not
|
|
2201
|
+
// last_tool_at: a read-only get names no claim_id and must not end the idle state before the resuming run calls claim.
|
|
2202
|
+
resumeIdleMs() {
|
|
2203
|
+
if(this.resumeIdleOption!==undefined) return this.resumeIdleOption;
|
|
2204
|
+
const raw=readEnv('DALAN_RESUME_IDLE_MS');
|
|
2205
|
+
if(raw===undefined||raw==='') return defaultResumeIdleMs;
|
|
2206
|
+
const n=Number(raw);
|
|
2207
|
+
return Number.isInteger(n)&&n>=0?n:defaultResumeIdleMs;
|
|
2208
|
+
}
|
|
2209
|
+
claimIdleMs(c) { return this.nowMs()-Date.parse(c.last_claim_activity_at??c.claimed_at); }
|
|
2210
|
+
// A running check is one long tool call: the claim is busy while it runs, so it is never idle (a resume would fence it).
|
|
2211
|
+
isIdleClaim(c) { const limit=this.resumeIdleMs(); return limit>0&&this.leaseExpired(c)&&this.claimIdleMs(c)>=limit&&!this.db.prepare("SELECT 1 FROM check_jobs WHERE request_id=? AND status='running' LIMIT 1").get(c.request_id); }
|
|
2212
|
+
// This worker's expired claims, eligible only after verified host cessation.
|
|
2213
|
+
idleClaims(worker) {
|
|
2214
|
+
if(this.resumeIdleMs()<=0) return [];
|
|
2215
|
+
return this.db.prepare("SELECT c.* FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND a.cancelled_at IS NULL AND c.state='active' AND c.worker=? ORDER BY c.last_claim_activity_at").all(worker).filter(c=>this.isIdleClaim(c));
|
|
2216
|
+
}
|
|
2217
|
+
guidanceFor(worker) { return this.workers.workers.get(worker)?.guidance==='resume'?`${workerGuidance} ${resumeNudge(this.resumeIdleMs()||defaultResumeIdleMs)}`:workerGuidance; }
|
|
2218
|
+
// Owner messages first (oldest first), then assignments in LIST_ORDER: normal before background, items the worker skipped last.
|
|
2219
|
+
// One bit for the public wake signal: a queued, live, uncancelled assignment targets one of these workers.
|
|
2220
|
+
hasQueuedFor(workerNames) {
|
|
2221
|
+
if(!workerNames.length) return false;
|
|
2222
|
+
return !!this.db.prepare(`SELECT 1 FROM assignments WHERE status='queued' AND cancelled_at IS NULL AND ${live(this.nowMs())} AND target_worker IN (${workerNames.map(()=>'?').join(',')}) LIMIT 1`).get(...workerNames);
|
|
2223
|
+
}
|
|
2224
|
+
// Wake bit: queued work, or an expired own claim ready for regrant.
|
|
2225
|
+
hasWakeFor(worker) { return this.hasQueuedFor([worker])||this.idleClaims(worker).length>0; }
|
|
2226
|
+
listPending(worker='dot') {
|
|
2227
|
+
// Recheck historical refusals against one lazily loaded configuration per listing.
|
|
2228
|
+
// Listing is read-only: it neither deletes audit evidence nor grants approval.
|
|
2229
|
+
let loaded=false,failed=false,profile,loadError;
|
|
2230
|
+
const fail=error=>{ failed=true; loadError=error??new Error('destination configuration could not be loaded'); };
|
|
2231
|
+
const resolve=()=>{
|
|
2232
|
+
if(!loaded) {
|
|
2233
|
+
loaded=true;
|
|
2234
|
+
try {
|
|
2235
|
+
profile=this.destinationProfile();
|
|
2236
|
+
// An asynchronous resolver is invalid; its rejection must not surface as an unhandled one.
|
|
2237
|
+
if(profile&&typeof profile.then==='function') { Promise.resolve(profile).catch(()=>{}); fail(new Error('destination resolver must be synchronous')); }
|
|
2238
|
+
} catch(error) { fail(error); }
|
|
2239
|
+
}
|
|
2240
|
+
if(failed)throw loadError;
|
|
2241
|
+
return profile;
|
|
2242
|
+
};
|
|
2243
|
+
const blocked=id=>{
|
|
2244
|
+
if(failed)return true; // a failed load is reported once per listing, whatever it threw or returned
|
|
2245
|
+
const row=this.db.prepare('SELECT payload,target_worker,execution FROM assignments WHERE request_id=?').get(id);
|
|
2246
|
+
const approval=this.destinationApproval(id);
|
|
2247
|
+
try {
|
|
2248
|
+
const current=this.destinationSnapshot(row.target_worker,row.execution,JSON.parse(row.payload),{required:!!approval,resolve});
|
|
2249
|
+
return !(!approval&&!current||approval&¤t?.revision===approval.revision&¤t.policy.allowed);
|
|
2250
|
+
} catch { return true; }
|
|
2251
|
+
};
|
|
2252
|
+
const assignments=this.db.prepare(`SELECT request_id,payload,created_at,EXISTS(SELECT 1 FROM destination_blocks b WHERE b.request_id=assignments.request_id) blocked FROM assignments WHERE status='queued' AND ${live(this.nowMs())} ORDER BY ${LIST_ORDER}`).all().filter(a=>this.mayAct(worker,a.request_id)&&this.protocolListingLive(a.request_id)).map(a=>({...a,blocked:!!a.blocked&&blocked(a.request_id)})).sort((a,b)=>Number(a.blocked)-Number(b.blocked)).slice(0,50).map(a=>({kind:'assignment',request_id:a.request_id,title:JSON.parse(a.payload).brief.slice(0,160),created_at:a.created_at,...(a.blocked?{blocked:true}:{})}));
|
|
2253
|
+
const messages=this.listMessages(worker).map(m=>({kind:'message',request_id:m.message_id,message_id:m.message_id,title:m.preview,created_at:m.created_at})).sort((a,b)=>a.created_at.localeCompare(b.created_at));
|
|
2254
|
+
const resumes=this.idleClaims(worker).filter(c=>this.protocolListingLive(c.request_id)).map(c=>({kind:'assignment',request_id:c.request_id,resume:true,idle_seconds:Math.floor(this.claimIdleMs(c)/1000),previous_epoch:c.epoch,
|
|
2255
|
+
...(this.db.prepare('SELECT 1 FROM destination_blocks WHERE request_id=?').get(c.request_id)&&blocked(c.request_id)?{blocked:true}:{}),
|
|
2256
|
+
note:'The prior lease expired. Call claim(request_id, claimant, acquisition_id) to request a new epoch after old host work has verifiably stopped. Read progress and owner notes with get first.'}));
|
|
2257
|
+
return [...resumes,...messages,...assignments].sort((a,b)=>Number(!!a.blocked)-Number(!!b.blocked)).slice(0,50);
|
|
2258
|
+
}
|
|
2259
|
+
// Called for each list_pending answer to the worker: the first freeLanes assignments are the ones it could claim now. One that
|
|
2260
|
+
// is still there SKIP_AFTER_ELIGIBLE_MS after it first was, with no claim, is marked skipped_by_worker (and goes behind its
|
|
2261
|
+
// peers in LIST_ORDER). Every listed assignment is stamped as seen, which claim() uses to tell a pass-over from news.
|
|
2262
|
+
recordListed(listed,freeLanes,worker='dot') { return this.transaction(() => {
|
|
2263
|
+
const now=this.nowMs(), at=iso(now), cutoff=iso(now-LISTED_POLL_GAP_MS), due=iso(now-SKIP_AFTER_ELIGIBLE_MS);
|
|
2264
|
+
const assignments=listed.filter(x=>x.kind==='assignment'&&!x.blocked);
|
|
2265
|
+
const seen=this.db.prepare("UPDATE assignments SET last_seen_listed_at=? WHERE request_id=? AND status='queued'");
|
|
2266
|
+
for(const item of assignments) seen.run(at,item.request_id);
|
|
2267
|
+
if(freeLanes<=0) { for(const item of assignments) this.db.prepare("UPDATE assignments SET eligible_since=NULL WHERE request_id=?").run(item.request_id); return; }
|
|
2268
|
+
const touch=this.db.prepare("UPDATE assignments SET eligible_since=COALESCE(eligible_since,?1),listed_count=listed_count+(last_listed_at IS NULL OR last_listed_at<=?3),last_listed_at=CASE WHEN last_listed_at IS NULL OR last_listed_at<=?3 THEN ?1 ELSE last_listed_at END,skipped_at=CASE WHEN skipped_at IS NULL AND eligible_since IS NOT NULL AND eligible_since<=?4 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued'");
|
|
2269
|
+
for(const item of assignments.slice(0,freeLanes)) touch.run(at,item.request_id,cutoff,due);
|
|
2270
|
+
}); }
|
|
2271
|
+
// A claim of one assignment passes over every queued one listed before it that the worker saw a moment ago.
|
|
2272
|
+
recordPassedOver(claimedId,worker='dot') {
|
|
2273
|
+
const now=this.nowMs(), at=iso(now), seenAfter=iso(now-PASSED_SEEN_MS);
|
|
2274
|
+
const order=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked).map(x=>x.request_id);
|
|
2275
|
+
const ahead=order.slice(0,Math.max(0,order.indexOf(claimedId)));
|
|
2276
|
+
const pass=this.db.prepare("UPDATE assignments SET passed_over=passed_over+1,skipped_at=CASE WHEN skipped_at IS NULL AND passed_over+1>=?3 THEN ?1 ELSE skipped_at END WHERE request_id=?2 AND status='queued' AND last_seen_listed_at>=?4");
|
|
2277
|
+
for(const id of ahead) pass.run(at,id,SKIP_AFTER_PASSED,seenAfter);
|
|
2278
|
+
}
|
|
2279
|
+
skippedByDot() { return this.db.prepare("SELECT request_id,skipped_at at,listed_count,passed_over FROM assignments WHERE status='queued' AND skipped_at IS NOT NULL ORDER BY skipped_at").all(); }
|
|
2280
|
+
// Built-in mode only: a fresh epoch is admitted only while the claimant's own
|
|
2281
|
+
// connection is in the worker's live set. The check runs synchronously inside
|
|
2282
|
+
// the admission transaction, after the server's awaited preflight/quiesce, so
|
|
2283
|
+
// a revoke that lands between token verification and admission is caught
|
|
2284
|
+
// here. Only stores without built-in liveness permit an omitted connection.
|
|
2285
|
+
// A legacy worker profile has no live-set callback; its authoritative
|
|
2286
|
+
// connectionIsLive callback still fences revoked built-in connections.
|
|
2287
|
+
assertLiveConnection(id,worker,connectionId) {
|
|
2288
|
+
if((connectionId===null||connectionId===undefined)&&typeof this.connectionIsLive!=='function')return;
|
|
2289
|
+
if(typeof connectionId!=='string'||!connectionId.trim())throw destinationError({error:'connection_not_live',request_id:id,
|
|
2290
|
+
message:'Claim refused: the claimant connection is not live.'});
|
|
2291
|
+
let profile=null;
|
|
2292
|
+
try {
|
|
2293
|
+
profile=typeof this.destinationProfile==='function'?this.destinationProfile():null;
|
|
2294
|
+
if(profile&&typeof profile.then==='function')throw new Error('destination resolver must be synchronous');
|
|
2295
|
+
} catch(error) {
|
|
2296
|
+
throw this.destinationConfigurationError(id,error);
|
|
2297
|
+
}
|
|
2298
|
+
if(typeof this.connectionIsLive==='function') {
|
|
2299
|
+
let active;
|
|
2300
|
+
try { active=this.connectionIsLive(connectionId); }
|
|
2301
|
+
catch(error) { throw this.destinationConfigurationError(id,error); }
|
|
2302
|
+
if(active!==true)throw destinationError({error:'connection_not_live',request_id:id,
|
|
2303
|
+
message:'Claim refused: the claimant connection is not live.'});
|
|
2304
|
+
if(profile?.legacy===true)return;
|
|
2305
|
+
}
|
|
2306
|
+
const live=profile?.builtinConnectionIds;
|
|
2307
|
+
if(typeof live!=='function')throw destinationError({error:'connection_not_live',request_id:id,
|
|
2308
|
+
message:'Claim refused: the worker live-connection set is unavailable.'});
|
|
2309
|
+
let ids;
|
|
2310
|
+
try { ids=live(worker); }
|
|
2311
|
+
catch(error) { throw this.destinationConfigurationError(id,error); }
|
|
2312
|
+
if(!Array.isArray(ids)||!ids.includes(connectionId))throw destinationError({error:'connection_not_live',request_id:id,
|
|
2313
|
+
message:'Claim refused: the claimant connection is not live.'});
|
|
2314
|
+
}
|
|
2315
|
+
// The live holder asking again with the claimant, subject and acquisition of its own grant.
|
|
2316
|
+
isExactClaimRetry(claim,claimant,subject,acquisitionId=null) {
|
|
2317
|
+
return claim?.state==='active'&&claim.claimant===claimant&&claim.subject===subject&&
|
|
2318
|
+
!this.leaseExpired(claim)&&claim.acquisition_id===acquisitionId;
|
|
2319
|
+
}
|
|
2320
|
+
// An exact retry (duplicate or native receipt replay) returns the grant the connection already holds. It is not a
|
|
2321
|
+
// new admission, so it does not re-run destination or repository policy; an owner edit between a lost reply and
|
|
2322
|
+
// its retry must not strand the holder. It needs the connection the grant was given to and, when the owner
|
|
2323
|
+
// approved a destination, the connection set that approval covered. Both checks use fixed text and write nothing:
|
|
2324
|
+
// a refusal here is not a destination-policy event. External OAuth presents no connection and records none.
|
|
2325
|
+
assertRetryConnection(id,claim,worker,connectionId) {
|
|
2326
|
+
this.assertLiveConnection(id,worker,connectionId);
|
|
2327
|
+
const refuse=message=>destinationError({error:'destination_changed',request_id:id,message});
|
|
2328
|
+
if(connectionId===null||connectionId===undefined) {
|
|
2329
|
+
if(claim.connection_id)throw refuse('Claim retry refused: this grant belongs to a built-in connection.');
|
|
2330
|
+
return;
|
|
2331
|
+
}
|
|
2332
|
+
// NULL is a grant made before the connection was recorded: it cannot be proved, so it is not recovered.
|
|
2333
|
+
if(claim.connection_id!==connectionId)throw refuse('Claim retry refused: this grant belongs to a different connection.');
|
|
2334
|
+
const approval=this.destinationApproval(id);
|
|
2335
|
+
if(!approval)return;
|
|
2336
|
+
let digest;
|
|
2337
|
+
try {
|
|
2338
|
+
if(typeof this.destinationProfile!=='function')throw new Error('destination resolver required');
|
|
2339
|
+
const profile=this.destinationProfile();
|
|
2340
|
+
if(profile&&typeof profile.then==='function')throw new Error('destination resolver must be synchronous');
|
|
2341
|
+
digest=connectionsDigest(profile,worker);
|
|
2342
|
+
} catch(error) { throw this.destinationConfigurationError(id,error); }
|
|
2343
|
+
if(digest!==approval.snapshot.connections_digest)throw refuse('Claim retry refused: the approved connection set changed.');
|
|
2344
|
+
}
|
|
2345
|
+
claim(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,ctx=null,connectionId=null) {
|
|
2346
|
+
const requestedLeaseMs=arguments[7]??null;
|
|
2347
|
+
return nonterminalOutcome(id,this.destinationOutcome(this.transaction(()=>this.isProtocolJob(id)
|
|
2348
|
+
?this.protocolClaimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,ctx?{...ctx,requestedLeaseMs}:ctx,connectionId)
|
|
2349
|
+
:this.claimInTransaction(id,claimant,subject,capacity,preflight,worker,acquisitionId,leaseMs,connectionId))));
|
|
2350
|
+
}
|
|
2351
|
+
claimInTransaction(id,claimant,subject='local-principal',capacity=1,preflight=null,worker='dot',acquisitionId=null,leaseMs=this.limits.leaseMs,connectionId=null) {
|
|
2352
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
2353
|
+
if(!Number.isInteger(leaseMs)||leaseMs<1||leaseMs>this.limits.leaseMs) throw new Error(`invalid lease_ms: must be an integer from 1 to ${this.limits.leaseMs}`);
|
|
2354
|
+
if(acquisitionId!==null&&(typeof acquisitionId!=='string'||!/^[A-Za-z0-9_-]{1,128}$/.test(acquisitionId))) throw new Error('invalid acquisition_id: use 1-128 letters, digits, underscores or hyphens');
|
|
2355
|
+
if(!this.mayAct(worker,id)) throw new Error('assignment not found');
|
|
2356
|
+
if (this.paused()) throw new Error(pausedClaimMessage);
|
|
2357
|
+
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2358
|
+
if(a.cancelled_at) throw new Error(a.cancelled_reason==='expired'?expiredError(a.valid_until,{cancelled:true}):'assignment cancelled'); if(a.status==='finished') throw new Error('assignment finished');
|
|
2359
|
+
if(a.status==='queued'&&this.db.prepare(`SELECT 1 FROM assignments WHERE request_id=? AND ${expired(this.nowMs())}`).get(id)) throw new Error(expiredError(a.valid_until,{requeue:a.valid_until_source==='queue_p90'&&(a.expiry_requeues??0)<2}));
|
|
2360
|
+
const old=this.db.prepare('SELECT * FROM claims WHERE request_id=?').get(id);
|
|
2361
|
+
if(old&&old.worker!==worker) throw new Error('invalid claim');
|
|
2362
|
+
this.assertLiveConnection(id,worker,connectionId);
|
|
2363
|
+
const laneScope=old?.lane_scope??this.workers.laneScope;
|
|
2364
|
+
const laneKey=laneScope==='subject'?subject:worker;
|
|
2365
|
+
const takeover=old?.state==='active';
|
|
2366
|
+
if(this.isExactClaimRetry(old,claimant,subject,acquisitionId)) {
|
|
2367
|
+
this.assertRetryConnection(id,old,worker,connectionId);
|
|
2368
|
+
this.touchHeldClaim(id,old.claim_id,subject,worker); this.markNotesSeen(id,subject,worker);
|
|
2369
|
+
return {request_id:id,claim_id:old.claim_id,epoch:old.epoch,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:true,guidance:this.guidanceFor(worker),...this.destinationClaimFields(id)};
|
|
2370
|
+
}
|
|
2371
|
+
if(old && (old.state!=='active' || this.leaseExpired(old))) this.assertRegrantReady(old);
|
|
2372
|
+
if(takeover&&old.subject===subject&&this.isIdleClaim(old)) return this.rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs,connectionId);
|
|
2373
|
+
if(takeover) {
|
|
2374
|
+
if(!this.leaseExpired(old)&&old.subject===subject&&this.resumeIdleMs()>0) throw new Error(JSON.stringify({error:'claim_busy',message:`Request ${id}: another run of this worker holds it and is active; pick other work or retry after its lease expires. This affects only ${id}.`,request_id:id}));
|
|
2375
|
+
if(!this.leaseExpired(old)) throw new Error('already claimed by another claimant');
|
|
2376
|
+
}
|
|
2377
|
+
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
2378
|
+
if(destinationRefusal)return destinationRefusal;
|
|
2379
|
+
// Every new epoch of an existing claim (takeover, claim after abandon) waits for reconcile.
|
|
2380
|
+
if(old) this.assertNoUncertainDelivery(id);
|
|
2381
|
+
if(this.activeClaims(subject,worker,id).length>=capacity) throw new Error('capacity_full');
|
|
2382
|
+
this.recordPrPreflight(id,'claim',JSON.parse(a.payload),preflight,!!old);
|
|
2383
|
+
if(takeover) { const why=Store.expirySummary(old); this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(this.stamp(),why,id); this.lifecycle(id,'abandoned','system',why,old); this.laneFreed(); }
|
|
2384
|
+
const claimId=`claim_${randomUUID()}`;
|
|
2385
|
+
const claimedAt=this.stamp(), seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
|
|
2386
|
+
if(old) {
|
|
2387
|
+
this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,subject=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=epoch+1,state='active',abandoned_at=NULL,abandon_reason=NULL,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,lane_key=?,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,claimedAt,subject,claimedAt,seen,laneKey,acquisitionId,leaseMs,connectionId??null,id);
|
|
2388
|
+
this.rebindClaim(id,claimId);
|
|
2389
|
+
} else this.db.prepare('INSERT INTO claims(request_id,claimant,claim_id,claimed_at,subject,last_claim_activity_at,last_seen_note_seq,worker,lane_key,lane_scope,acquisition_id,lease_ms,connection_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)').run(id,claimant,claimId,claimedAt,subject,claimedAt,seen,worker,laneKey,laneScope,acquisitionId,leaseMs,connectionId??null);
|
|
2390
|
+
this.setClaimDeadlineInTransaction(id,leaseMs);
|
|
2391
|
+
if(a.status==='queued') this.recordPassedOver(id,worker);
|
|
2392
|
+
this.db.prepare("UPDATE assignments SET status='claimed',listed_count=0,last_listed_at=NULL,skipped_at=NULL,eligible_since=NULL,passed_over=0 WHERE request_id=?").run(id);
|
|
2393
|
+
this.lifecycle(id,'claimed',`worker:${subject}`,takeover?'takeover':old?'reclaim':'new',{claim_id:claimId,epoch:old?old.epoch+1:1,worker});
|
|
2394
|
+
this.db.prepare('DELETE FROM claim_denials WHERE request_id=?').run(id);
|
|
2395
|
+
return {request_id:id,claim_id:claimId,epoch:old?old.epoch+1:1,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:false,guidance:this.guidanceFor(worker),...this.destinationGrantedInTransaction(id)};
|
|
2396
|
+
}
|
|
2397
|
+
// Resume wake: the same worker and subject claims its own idle claim. The claim moves to a new claim_id and the next epoch in one
|
|
2398
|
+
// transaction, so a run still alive under the old claim_id is refused on its next call (claim_superseded). Worktree and sealed
|
|
2399
|
+
// uploads move with it (rebindClaim). Lifecycle: a 'claimed' event with reason 'resume' (not counted as a new admission; the
|
|
2400
|
+
// event type list is closed, so no 'resumed' type). The previous epoch and the idle time go to the progress history.
|
|
2401
|
+
rotateIdleClaim(old,a,claimant,subject,worker,acquisitionId,leaseMs=this.limits.leaseMs,connectionId=null) {
|
|
2402
|
+
this.assertRegrantReady(old);
|
|
2403
|
+
this.assertLiveConnection(old.request_id,worker,connectionId);
|
|
2404
|
+
const id=old.request_id, idleS=Math.floor(this.claimIdleMs(old)/1000);
|
|
2405
|
+
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
2406
|
+
if(destinationRefusal)return destinationRefusal;
|
|
2407
|
+
this.assertNoUncertainDelivery(id);
|
|
2408
|
+
const claimId=`claim_${randomUUID()}`, at=this.stamp(), epoch=old.epoch+1;
|
|
2409
|
+
const seen=this.db.prepare('SELECT COALESCE(max(sequence),0) n FROM owner_notes WHERE request_id=?').get(id).n;
|
|
2410
|
+
this.db.prepare("UPDATE claims SET claimant=?,claim_id=?,claimed_at=?,last_claim_activity_at=?,last_seen_note_seq=?,last_progress_at=NULL,epoch=?,tool_calls=0,last_tool=NULL,last_tool_at=NULL,last_tool_error=NULL,first_workspace_tool_at=NULL,acquisition_id=?,lease_ms=?,connection_id=? WHERE request_id=?").run(claimant,claimId,at,at,seen,epoch,acquisitionId,leaseMs,connectionId??null,id);
|
|
2411
|
+
this.setClaimDeadlineInTransaction(id,leaseMs);
|
|
2412
|
+
this.rebindClaim(id,claimId);
|
|
2413
|
+
this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,`[bridge] run resumed: epoch ${old.epoch} lease expired after ${idleS}s without activity; epoch ${epoch} continues under a new claim`,at,worker);
|
|
2414
|
+
this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch,worker});
|
|
2415
|
+
return {request_id:id,claim_id:claimId,epoch,previous_epoch:old.epoch,resumed:true,idle_seconds:idleS,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),duplicate:false,guidance:this.guidanceFor(worker),...this.destinationGrantedInTransaction(id)};
|
|
2416
|
+
}
|
|
2417
|
+
// The same subject continues under a fresh claim_id and the next epoch, so a lost process holding the old claim_id is fenced off.
|
|
2418
|
+
resume(id,subject='local-principal',connectionId=null) { return this.destinationOutcome(this.transaction(() => {
|
|
2419
|
+
const a=this.db.prepare('SELECT * FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2420
|
+
if(a.cancelled_at) throw new Error('assignment cancelled'); if(a.status==='finished') throw new Error('assignment finished');
|
|
2421
|
+
const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
2422
|
+
if(!old||old.subject!==subject||a.status!=='claimed') throw new Error('no active claim for this subject');
|
|
2423
|
+
this.assertLiveConnection(id,old.worker,connectionId);
|
|
2424
|
+
this.assertRegrantReady(old);
|
|
2425
|
+
const destinationRefusal=this.destinationAdmissionInTransaction(id);
|
|
2426
|
+
if(destinationRefusal)return destinationRefusal;
|
|
2427
|
+
this.assertNoUncertainDelivery(id);
|
|
2428
|
+
const claimId=`claim_${randomUUID()}`;
|
|
2429
|
+
this.db.prepare('UPDATE claims SET claim_id=?,epoch=epoch+1,last_claim_activity_at=?,connection_id=COALESCE(?,connection_id) WHERE request_id=?').run(claimId,this.stamp(),connectionId??null,id);
|
|
2430
|
+
this.rebindClaim(id,claimId);
|
|
2431
|
+
this.setClaimDeadlineInTransaction(id,this.claimLeaseMs(old));
|
|
2432
|
+
this.markNotesSeen(id,subject);
|
|
2433
|
+
this.lifecycle(id,'claimed',`worker:${subject}`,'resume',{claim_id:claimId,epoch:old.epoch+1});
|
|
2434
|
+
if(this.isProtocolJob(id)) {
|
|
2435
|
+
this.advanceProtocolRevisionInTransaction(id);
|
|
2436
|
+
this.protocolEventInTransaction(id,'claimed',{claim_id:claimId,resumed:true},old.epoch+1);
|
|
2437
|
+
}
|
|
2438
|
+
return {request_id:id,claim_id:claimId,epoch:old.epoch+1,previous_epoch:old.epoch,assignment:JSON.parse(a.payload),owner_notes:this.ownerNotes(id),guidance:workerGuidance,...this.destinationGrantedInTransaction(id)};
|
|
2439
|
+
})); }
|
|
2440
|
+
// Withdraw the active claim and requeue the assignment, never while a delivery for it may be in flight or already delivered.
|
|
2441
|
+
abandon(id,{actor='operator',reason='abandoned'}={}) { return this.transaction(() => {
|
|
2442
|
+
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2443
|
+
const old=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND state='active'").get(id);
|
|
2444
|
+
if(a.status==='finished'||a.status==='cancelled') throw new Error('assignment is terminal');
|
|
2445
|
+
if(!old||a.status!=='claimed') throw new Error('no active claim');
|
|
2446
|
+
this.assertNoUncertainDelivery(id);
|
|
2447
|
+
const at=this.stamp();
|
|
2448
|
+
const expired=reason==='lease_expired'&&this.leaseExpired(old);
|
|
2449
|
+
if(reason==='lease_expired') reason=Store.expirySummary(old);
|
|
2450
|
+
this.db.prepare("UPDATE claims SET state='abandoned',abandoned_at=?,abandon_reason=? WHERE request_id=?").run(at,reason,id);
|
|
2451
|
+
this.db.prepare("UPDATE assignments SET status='queued' WHERE request_id=?").run(id);
|
|
2452
|
+
this.lifecycle(id,'abandoned',actor,reason,old);
|
|
2453
|
+
this.lifecycle(id,'queued',actor,'requeued',null);
|
|
2454
|
+
if(this.isProtocolJob(id)) {
|
|
2455
|
+
this.advanceProtocolRevisionInTransaction(id);
|
|
2456
|
+
this.protocolEventInTransaction(id,expired?'expired':'abandoned',{reason},old.epoch);
|
|
2457
|
+
}
|
|
2458
|
+
for(const sub of this.activeSubscriptions()) this.queueEvent(id,sub,true);
|
|
2459
|
+
this.laneFreed();
|
|
2460
|
+
return {request_id:id,status:'queued',abandoned:{claim_id:old.claim_id,epoch:old.epoch,claimant:old.claimant,subject:old.subject,abandoned_at:at,reason,actor}};
|
|
2461
|
+
}); }
|
|
2462
|
+
// Result hints for list_pending and claim. Free lanes are bounded by both the lane capacity and the claim cap, so the
|
|
2463
|
+
// count never invites a claim that capacity_full would refuse.
|
|
2464
|
+
laneState(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) {
|
|
2465
|
+
return {free_lanes:this.freeLanes(subject,worker,laneCapacity,claimCapacity),queued:this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked).length};
|
|
2466
|
+
}
|
|
2467
|
+
// A claimed assignment left its lane: the next reannounceQueued tick may wake the worker at once instead of waiting out rewakeMs.
|
|
2468
|
+
laneFreed() { this.dispatchWake=true; }
|
|
2469
|
+
// Up to `free` live queued assignments in list_pending order (oldest, normal work first), never `exceptId`, with the one-line prompt to claim them.
|
|
2470
|
+
nextQueued(free,exceptId=null,worker='dot') {
|
|
2471
|
+
if(free<=0) return {};
|
|
2472
|
+
const all=this.listPending(worker).filter(x=>x.kind==='assignment'&&!x.blocked&&x.request_id!==exceptId);
|
|
2473
|
+
if(!all.length) return {};
|
|
2474
|
+
const next=all.slice(0,free).map(({request_id,title})=>({request_id,title}));
|
|
2475
|
+
return {next_queued:next,next_action:`${all.length} queued and ${free} ${free===1?'lane':'lanes'} free: claim ${next.map(x=>x.request_id).join(', ')} now (oldest first)`};
|
|
2476
|
+
}
|
|
2477
|
+
freeLanes(subject,worker='dot',laneCapacity=this.limits.laneCapacity??6,claimCapacity=this.capacity) { return Math.max(0,Math.min(laneCapacity,claimCapacity)-this.activeClaims(subject,worker).length); }
|
|
2478
|
+
// Active claims for the operator, with the lease state that decides whether another claimant may take one over.
|
|
2479
|
+
claims() {
|
|
2480
|
+
return this.db.prepare("SELECT c.*,a.priority FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active' ORDER BY c.claimed_at").all().map(c=>({
|
|
2481
|
+
request_id:c.request_id,claimant:c.claimant,subject:c.subject,claim_id:c.claim_id,epoch:c.epoch,claimed_at:c.claimed_at,last_activity_at:c.last_claim_activity_at??c.claimed_at,
|
|
2482
|
+
lease_expires_at:this.leaseExpiresAt(c),expired:this.leaseExpired(c),priority:c.priority,uncertain_deliveries:this.uncertainDeliveries(c.request_id)}));
|
|
2483
|
+
}
|
|
2484
|
+
// Uploads are rebound to each new claim_id. Bridge-written check output and patches keep the claim_id they ran under and stay citable.
|
|
2485
|
+
assertSealedArtifacts(id,claimId,artifactIds) { for(const artifactId of artifactIds) if(!this.db.prepare("SELECT 1 FROM artifacts WHERE COALESCE(client_artifact_id,id)=? AND request_id=? AND (claim_id=? OR kind<>'upload') AND sealed=1").get(artifactId,id,claimId)) throw new Error('invalid sealed artifact'); }
|
|
2486
|
+
// A worker mutation is refused at the lease deadline (now >= leaseExpiresAt) without refreshing the lease and without writing anything.
|
|
2487
|
+
// The sweep (sweepStaleLeases) or a takeover is what moves the claim to abandoned; until then the row stays active but cannot act.
|
|
2488
|
+
// A claim_id that an earlier epoch of this assignment held (rotation, takeover, reclaim) is superseded, not unknown. Only its own worker and subject learn that.
|
|
2489
|
+
refuseClaim(id,claimId,subject,worker) {
|
|
2490
|
+
const cur=this.mayAct(worker,id)?this.db.prepare("SELECT claim_id,epoch,subject,worker FROM claims WHERE request_id=? AND state='active'").get(id):null;
|
|
2491
|
+
if(cur&&cur.claim_id!==claimId&&cur.subject===subject&&cur.worker===worker&&this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND claim_id=? AND type='claimed'").get(id,claimId))
|
|
2492
|
+
return new Error(JSON.stringify({error:'claim_superseded',message:`invalid claim: claim ${claimId} for ${id} was superseded by epoch ${cur.epoch}; stop using this claim. This affects only ${id}.`,request_id:id}));
|
|
2493
|
+
return new Error('invalid claim');
|
|
2494
|
+
}
|
|
2495
|
+
// Commit-time authority only: never re-admit the grant against destination/repository policy.
|
|
2496
|
+
assertMutationConnection(id,claim,connectionId=null) {
|
|
2497
|
+
if(connectionId==null&&claim.connection_id==null&&typeof this.connectionIsLive!=='function')return;
|
|
2498
|
+
const refuse=()=>destinationError({error:'connection_not_live',request_id:id,
|
|
2499
|
+
message:'Claim mutation refused: the granting connection is not live or does not match.'});
|
|
2500
|
+
if(typeof connectionId!=='string'||!connectionId.trim()||claim.connection_id!==connectionId||
|
|
2501
|
+
typeof this.connectionIsLive!=='function')throw refuse();
|
|
2502
|
+
let live=false;
|
|
2503
|
+
try { live=this.connectionIsLive(connectionId)===true; } catch { /* Fail closed without disclosing auth internals. */ }
|
|
2504
|
+
if(!live)throw refuse();
|
|
2505
|
+
}
|
|
2506
|
+
assertClaim(id,claimId,subject='local-principal',worker='dot') {
|
|
2507
|
+
const c=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND state='active'").get(id,claimId);
|
|
2508
|
+
if(!c||c.subject!==subject||c.worker!==worker||!this.mayAct(worker,id)) throw this.refuseClaim(id,claimId,subject,worker);
|
|
2509
|
+
this.assertProtocolAvailable(id);
|
|
2510
|
+
if(this.isProtocolJob(id)&&this.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='finished'").get(id)) throw questionError('TERMINAL','assignment is terminal');
|
|
2511
|
+
if(this.leaseExpired(c)) {
|
|
2512
|
+
const deadline=this.leaseExpiresAt(c);
|
|
2513
|
+
const cancelled=this.db.prepare("SELECT 1 FROM assignments WHERE request_id=? AND status='cancelled'").get(id);
|
|
2514
|
+
throw new Error(JSON.stringify({error:cancelled?'assignment_cancelled':'lease_expired',
|
|
2515
|
+
message:cancelled?`Assignment ${id} was cancelled. This expired claim cannot submit a result or late output.`:
|
|
2516
|
+
`the lease on assignment ${id} ended at ${deadline}; claim ${claimId} can no longer act. This affects only ${id}. Claim it again to continue; the sweep may already have requeued it.`,
|
|
2517
|
+
request_id:id,lease_expires_at:deadline}));
|
|
2518
|
+
}
|
|
2519
|
+
return c;
|
|
2520
|
+
}
|
|
2521
|
+
// A worker note that reports a denied claim and names queued requests: stop re-waking them (rewakeCandidates) until claimed.
|
|
2522
|
+
// The ID, a claim and a denial must share one sentence: a note about a denied read that mentions another request is not one.
|
|
2523
|
+
recordClaimDenials(reportedIn,text,worker='dot') {
|
|
2524
|
+
if(!claimDenial.test(text)) return [];
|
|
2525
|
+
const queued=this.db.prepare("SELECT request_id FROM assignments WHERE status='queued' AND request_id<>? AND target_worker=?").all(reportedIn,worker).map(r=>r.request_id);
|
|
2526
|
+
const put=this.db.prepare(`INSERT INTO claim_denials(request_id,at,reported_in,capacity,note,worker) VALUES(?,?,?,?,?,?)
|
|
2527
|
+
ON CONFLICT(request_id) DO UPDATE SET at=excluded.at,reported_in=excluded.reported_in,capacity=max(capacity,excluded.capacity),note=excluded.note`);
|
|
2528
|
+
const named=new Set();
|
|
2529
|
+
for(const sentence of text.split(/(?<=[.!?;])\s+|\n+/)) {
|
|
2530
|
+
if(!claimDenial.test(sentence)||!/\bclaim(?:s|ed|ing)?\b/i.test(sentence)) continue;
|
|
2531
|
+
for(const rid of queued) if(new RegExp(`(?<![-\\w])${rid}(?![-\\w])`).test(sentence)) { put.run(rid,this.stamp(),reportedIn,Number(/\bcapacity\b/i.test(sentence)),text.slice(0,500),worker); named.add(rid); }
|
|
2532
|
+
}
|
|
2533
|
+
return [...named];
|
|
2534
|
+
}
|
|
2535
|
+
claimDenial(id) { const r=this.db.prepare('SELECT at,reported_in,capacity,note FROM claim_denials WHERE request_id=?').get(id); return r?{...r,capacity:!!r.capacity}:null; }
|
|
2536
|
+
deniedQueued(worker='dot') { return this.db.prepare("SELECT d.request_id,d.at,d.reported_in,d.capacity FROM claim_denials d JOIN assignments a USING(request_id) WHERE a.status='queued' AND d.worker=? AND a.target_worker=d.worker ORDER BY d.at").all(worker); }
|
|
2537
|
+
// Until when a capacity-overrun denial holds every re-wake: until a claimed assignment completes, is abandoned or cancelled
|
|
2538
|
+
// (a slot frees), at most capacityHoldMaxMs. null when no such hold applies.
|
|
2539
|
+
capacityHoldUntil(worker='dot') {
|
|
2540
|
+
const at=this.db.prepare('SELECT max(at) at FROM claim_denials WHERE capacity=1 AND worker=?').get(worker).at;
|
|
2541
|
+
if(!at||this.nowMs()>=Date.parse(at)+capacityHoldMaxMs) return null;
|
|
2542
|
+
// Only a claimed assignment ending frees a slot; cancelling or expiring queued work does not.
|
|
2543
|
+
if(this.db.prepare("SELECT 1 FROM lifecycle_events e WHERE e.type IN ('completed','abandoned','cancelled') AND e.at>? AND e.worker=? AND EXISTS(SELECT 1 FROM claims c WHERE c.request_id=e.request_id) LIMIT 1").get(at,worker)) return null;
|
|
2544
|
+
return iso(Date.parse(at)+capacityHoldMaxMs);
|
|
2545
|
+
}
|
|
2546
|
+
progress(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null,ctx=null,connectionId=null) {
|
|
2547
|
+
const result=this.transaction(()=>{
|
|
2548
|
+
if(!this.isProtocolJob(id)) {
|
|
2549
|
+
this.assertMutationConnection(id,this.assertClaim(id,claimId,subject,worker),connectionId);
|
|
2550
|
+
return this.progressInTransaction(id,claimId,note,subject,blocker,worker,question);
|
|
2551
|
+
}
|
|
2552
|
+
const receipt=this.protocolMutationInTransaction(id,claimId,subject,worker,
|
|
2553
|
+
{...ctx,operation:question?'ask':'progress',args:{note,blocker,question}},()=>{
|
|
2554
|
+
const value=this.progressInTransaction(id,claimId,note,subject,blocker,worker,question);
|
|
2555
|
+
if(value.duplicate===true)protocolError('question_exists');
|
|
2556
|
+
this.protocolEventInTransaction(id,question?'questioned':'progressed',
|
|
2557
|
+
question?{question_id:question.questionId}:{note,blocker},this.assertClaim(id,claimId,subject,worker).epoch);
|
|
2558
|
+
return value;
|
|
2559
|
+
},connectionId);
|
|
2560
|
+
return {...receipt.value,revision:receipt.revision};
|
|
2561
|
+
});
|
|
2562
|
+
// Decorate after replay validation too, including receipts stored before this field existed.
|
|
2563
|
+
return question?result:nonterminalOutcome(id,result);
|
|
2564
|
+
}
|
|
2565
|
+
progressInTransaction(id,claimId,note,subject='local-principal',blocker=false,worker='dot',question=null) {
|
|
2566
|
+
if(!this.db.isTransaction) throw new Error('progress requires a caller-owned transaction');
|
|
2567
|
+
const claim=this.assertClaim(id,claimId,subject,worker);
|
|
2568
|
+
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id);
|
|
2569
|
+
if(a.status==='finished'||a.status==='cancelled') throw new Error('assignment is terminal: this job is already finished or cancelled; stop work on it and call list_pending for your next job');
|
|
2570
|
+
if(question) {
|
|
2571
|
+
validateQuestion(question.questionId,question.text);
|
|
2572
|
+
const old=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(id,question.questionId);
|
|
2573
|
+
if(old) {
|
|
2574
|
+
if(old.claim_id!==claimId||old.epoch!==claim.epoch) throw questionError('STALE_EPOCH','question identity belongs to an earlier grant');
|
|
2575
|
+
if(old.text!==question.text) throw questionError('KEY_CONFLICT','question identity has different text');
|
|
2576
|
+
return {recorded:true,question_id:question.questionId,duplicate:true};
|
|
2577
|
+
}
|
|
2578
|
+
this.db.prepare('INSERT INTO job_questions(request_id,question_id,claim_id,epoch,worker,subject,text,asked_at) VALUES(?,?,?,?,?,?,?,?)').run(id,question.questionId,claimId,claim.epoch,worker,subject,question.text,this.stamp());
|
|
2579
|
+
}
|
|
2580
|
+
this.db.prepare('INSERT INTO progress(request_id,note,created_at,worker) VALUES(?,?,?,?)').run(id,note,this.stamp(),worker);
|
|
2581
|
+
this.recordClaimDenials(id,note,worker);
|
|
2582
|
+
this.db.prepare('UPDATE claims SET last_progress_at=? WHERE request_id=?').run(this.stamp(),id);
|
|
2583
|
+
this.refreshClaimActivity(id,claim.claim_id);
|
|
2584
|
+
const isBlocker=blocker||/^\s*(?:BLOCKED:|QUESTION:)/im.test(note);
|
|
2585
|
+
this.lifecycle(id,question?'waiting':progressType(note,blocker),`worker:${subject}`,question?`question:ask:${question.questionId}`:null,claim);
|
|
2586
|
+
if(isBlocker) {
|
|
2587
|
+
const ownerNoteSeq=this.db.prepare('SELECT COALESCE(max(sequence),0) sequence FROM owner_notes WHERE request_id=?').get(id).sequence;
|
|
2588
|
+
const body=JSON.stringify({note,epoch:claim.epoch,owner_note_seq:ownerNoteSeq,...(question?{question_id:question.questionId}:{})});
|
|
2589
|
+
// Legacy bodies have no generation fields. Preserve them only before any later answer/claim boundary;
|
|
2590
|
+
// equal timestamps at a boundary cannot prove the original generation, so do not suppress a fresh question.
|
|
2591
|
+
// Owner notes have no shared sequence with notifications; table-local rowids or a delivered-ID set cannot
|
|
2592
|
+
// distinguish answer-before-question from question-before-answer. See docs/operations.md#legacy-question-ties.
|
|
2593
|
+
const old=question?null:this.db.prepare(`SELECT n.id FROM notifications n WHERE n.kind IN ('blocker','wait') AND n.request_id=? AND
|
|
2594
|
+
(n.body=? OR n.body=? AND NOT EXISTS(SELECT 1 FROM owner_notes o WHERE o.request_id=n.request_id AND o.at>=n.created_at)
|
|
2595
|
+
AND (?=1 OR EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=n.request_id AND e.type='claimed' AND e.claim_id=? AND e.at<n.created_at)))`).get(id,body,JSON.stringify({note}),claim.epoch,claimId);
|
|
2596
|
+
if(!old) this.db.prepare('INSERT INTO notifications(id,kind,request_id,body,created_at) VALUES(?,?,?,?,?)').run(`evt_${randomUUID()}`,this.deliveryKind(id,'blocker'),id,body,this.stamp());
|
|
2597
|
+
}
|
|
2598
|
+
return {recorded:true,blocker_forwarded:isBlocker,...(question?{question_id:question.questionId,duplicate:false}:{})};
|
|
2599
|
+
}
|
|
2600
|
+
// Output filed after cancel is audit evidence in late_evidence: never a result, never delivered, never a lane freed. Cancellation wins.
|
|
2601
|
+
static resultAuthority(late) { return {result_authority:!late,status:late?'cancelled':'finished',terminal:true}; }
|
|
2602
|
+
static clipBytes(text,max) { const buf=Buffer.from(text); if(buf.length<=max) return text; let end=max; while(end>0&&(buf[end]&0xC0)===0x80) end--; return buf.subarray(0,end).toString(); }
|
|
2603
|
+
static lateEvidenceLimits={summary:4096,result:64*1024};
|
|
2604
|
+
finish(id,claimId,outcome,summary,result,subject='local-principal',evidence=null,worker='dot',ctx=null,captureEvidence=null,connectionId=null) {
|
|
2605
|
+
if(this.isProtocolJob(id)&&this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id)?.status!=='cancelled')
|
|
2606
|
+
return finishProtocol(this,id,claimId,outcome,summary,result,subject,evidence,worker,ctx,captureEvidence,connectionId);
|
|
2607
|
+
const rollback=[];
|
|
2608
|
+
let done;
|
|
2609
|
+
try { done=this.transaction(() => this.finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence?()=>captureEvidence(cleanup=>rollback.push(cleanup)):null,connectionId)); }
|
|
2610
|
+
catch(error) {for(const cleanup of rollback)cleanup();throw error;}
|
|
2611
|
+
// Thrown after the transaction commits so the evidence row stays. TERMINAL: the worker has nothing more to do for this request.
|
|
2612
|
+
if(done.cancelled) throw new Error(JSON.stringify({error:'assignment_cancelled',message:`${id} was cancelled${done.reason?` (reason: ${done.reason})`:''} before this finish. Your output was kept as audit evidence only (not a result); nothing more is needed for ${id}; your other assignments are unaffected.${done.contradiction?' A different output was already kept for this request; this one was not stored.':''}`,request_id:id}));
|
|
2613
|
+
return done;
|
|
2614
|
+
}
|
|
2615
|
+
// A committed report retry reads its receipt; the original grant still binds worker and subject, but needs no live lease.
|
|
2616
|
+
assertFinishClaim(id,claimId,subject='local-principal',worker='dot') {
|
|
2617
|
+
const report=this.db.prepare('SELECT claim_id,worker FROM reports WHERE request_id=?').get(id);
|
|
2618
|
+
if(!report) return this.assertClaim(id,claimId,subject,worker);
|
|
2619
|
+
const claim=this.db.prepare("SELECT * FROM claims WHERE request_id=? AND claim_id=? AND state='active'").get(id,claimId);
|
|
2620
|
+
if(!claim||claim.subject!==subject||claim.worker!==worker||report.claim_id!==claimId||report.worker!==worker||!this.mayAct(worker,id)) throw this.refuseClaim(id,claimId,subject,worker);
|
|
2621
|
+
this.assertProtocolAvailable(id);
|
|
2622
|
+
return claim;
|
|
2623
|
+
}
|
|
2624
|
+
finishOnce(id,claimId,outcome,summary,result,subject,evidence,worker,captureEvidence=null,connectionId=null) {
|
|
2625
|
+
const claim=this.assertFinishClaim(id,claimId,subject,worker);
|
|
2626
|
+
this.assertMutationConnection(id,claim,connectionId);
|
|
2627
|
+
const old=this.db.prepare('SELECT * FROM reports WHERE request_id=?').get(id);
|
|
2628
|
+
if(old) { if(old.outcome!==outcome||old.summary!==summary||old.result!==result) throw new Error('contradictory report: this request already has a different stored report, which is kept; do not call finish again with other text. Call list_pending for your next job.'); return {receipt_id:old.receipt_id,request_id:id,duplicate:true,late:!!old.late,...Store.resultAuthority(!!old.late)}; }
|
|
2629
|
+
const a=this.db.prepare('SELECT status,cancelled_reason FROM assignments WHERE request_id=?').get(id);
|
|
2630
|
+
if(a.status==='cancelled') {
|
|
2631
|
+
this.recordClaimDenials(id,`${summary}\n${result}`,worker);
|
|
2632
|
+
const limits=Store.lateEvidenceLimits, full=createHash('sha256').update(summary+result).digest('hex');
|
|
2633
|
+
const kept=this.db.prepare('SELECT outcome,full_sha256 FROM late_evidence WHERE request_id=? AND claim_id=?').get(id,claimId);
|
|
2634
|
+
if(!kept) {
|
|
2635
|
+
const s=Store.clipBytes(summary,limits.summary), r=Store.clipBytes(result,limits.result);
|
|
2636
|
+
this.db.prepare('INSERT INTO late_evidence(request_id,claim_id,epoch,worker,outcome,summary,result,full_sha256,truncated,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,claimId,claim.epoch,worker,outcome,s,r,full,s!==summary||r!==result?1:0,this.stamp());
|
|
2637
|
+
}
|
|
2638
|
+
return {cancelled:true,reason:a.cancelled_reason,contradiction:!!kept&&(kept.outcome!==outcome||kept.full_sha256!==full)};
|
|
2639
|
+
}
|
|
2640
|
+
this.assertQuestionsResolved(id,claimId,outcome);
|
|
2641
|
+
if(captureEvidence) evidence=captureEvidence();
|
|
2642
|
+
this.recordClaimDenials(id,`${summary}\n${result}`,worker);
|
|
2643
|
+
const receipt=`report_${randomUUID()}`;
|
|
2644
|
+
this.db.prepare('INSERT INTO reports(request_id,claim_id,outcome,summary,result,receipt_id,created_at,late,workspace_evidence,worker) VALUES(?,?,?,?,?,?,?,?,?,?)').run(id,claimId,outcome,summary,result,receipt,this.stamp(),0,evidence?JSON.stringify(evidence):null,worker);
|
|
2645
|
+
// completed means the worker filed its terminal report; acceptance is only ever the owner's accept event.
|
|
2646
|
+
this.lifecycle(id,'completed',`worker:${subject}`,`outcome=${outcome}`,claim);
|
|
2647
|
+
if(outcome==='blocked') this.lifecycle(id,'blocked',`worker:${subject}`,null,claim);
|
|
2648
|
+
this.db.prepare("UPDATE assignments SET status='finished' WHERE request_id=?").run(id);
|
|
2649
|
+
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
2650
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='result superseded watch' WHERE request_id=? AND kind='watch' AND state IN ('pending','failed')").run(id);
|
|
2651
|
+
this.suppressFinishedQuestions(id);
|
|
2652
|
+
this.db.prepare('INSERT INTO notifications(id,kind,request_id,created_at) VALUES(?,?,?,?)').run(`evt_${randomUUID()}`,this.deliveryKind(id,'t3'),id,this.stamp());
|
|
2653
|
+
this.laneFreed();
|
|
2654
|
+
return {receipt_id:receipt,request_id:id,duplicate:false,late:false,...Store.resultAuthority(false),...this.nextQueued(this.freeLanes(claim.subject,claim.worker),id,worker)};
|
|
2655
|
+
}
|
|
2656
|
+
cancel(id,reason=null,ctx=null,ownerToken=null) {
|
|
2657
|
+
const workCancelled=this.pullQueue.cancel(id,reason);if(workCancelled)return workCancelled;
|
|
2658
|
+
return this.isProtocolJob(id)?cancelProtocolJob(this,id,reason,ownerToken,ctx):this.transaction(()=>this.cancelInTransaction(id,reason));
|
|
2659
|
+
}
|
|
2660
|
+
cancelInTransaction(id,reason=null) {
|
|
2661
|
+
if(!this.db.isTransaction)protocolError('transaction_required');
|
|
2662
|
+
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found'); if(a.status==='finished') throw new Error('already finished');
|
|
2663
|
+
if(a.status!=='cancelled') {
|
|
2664
|
+
this.assertNoUncertainDelivery(id);
|
|
2665
|
+
if(a.status==='claimed') this.laneFreed();
|
|
2666
|
+
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason=? WHERE request_id=?").run(this.stamp(),reason,id);
|
|
2667
|
+
this.lifecycle(id,'cancelled','owner',reason);
|
|
2668
|
+
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
2669
|
+
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
2670
|
+
}
|
|
2671
|
+
return {request_id:id,status:'cancelled',cancellation_requested:true,authority_revoked:true,compute_stopped:false};
|
|
2672
|
+
}
|
|
2673
|
+
// Cancel only while the row is still queued, in one transaction, so a claim cannot slip in between a check and the cancel.
|
|
2674
|
+
// Returns the resulting state either way: cancelled:true when this call cancelled it, false when it was already claimed,
|
|
2675
|
+
// finished or cancelled (the status then says which). A claimed row keeps running; nothing is revoked.
|
|
2676
|
+
cancelIfQueued(id) { return this.transaction(() => {
|
|
2677
|
+
const pendingWork=this.pullQueue.row(id);
|
|
2678
|
+
if(pendingWork&&!pendingWork.child_request_id) {const status=this.pullQueue.project(pendingWork).status;if(status!=='queued')return {request_id:id,status,cancelled:false};return {...this.pullQueue.cancel(id),cancelled:true};}
|
|
2679
|
+
this.assertProtocolAvailable(id);
|
|
2680
|
+
if(this.isProtocolJob(id)) throw new Error('protocol jobs require keyed /cancel with command_key and expected_revision');
|
|
2681
|
+
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2682
|
+
if(a.status!=='queued') return {request_id:id,status:a.status,cancelled:false};
|
|
2683
|
+
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=? WHERE request_id=? AND status='queued'").run(this.stamp(),id);
|
|
2684
|
+
this.lifecycle(id,'cancelled','owner');
|
|
2685
|
+
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
2686
|
+
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(this.stamp(),id);
|
|
2687
|
+
return {request_id:id,status:'cancelled',cancelled:true};
|
|
2688
|
+
}); }
|
|
2689
|
+
// Lease sweep: a claim whose lease ran out with no claim activity is abandoned (actor system, reason lease_expired) through the
|
|
2690
|
+
// same path as `dalan abandon`, so the row is requeued and its lane is free at once. Before this, an expired lease only
|
|
2691
|
+
// let another claimant take the item over, and a dead claim held its lane for as long as nobody did. A usage break neither holds
|
|
2692
|
+
// the sweep nor moves a deadline: only the claimant's own activity extends a lease. After a bridge start, a claim whose last activity came before the start is not swept
|
|
2693
|
+
// before the start plus that claim's own lease (lease_ms), the full lease a restart would have given it, so a deadline that
|
|
2694
|
+
// passed while the bridge was down or draining does not requeue work the worker may still be running. A claim touched since
|
|
2695
|
+
// the start has no grace. A claim with an uncertain delivery waits for reconcile.
|
|
2696
|
+
// Returns the abandoned request ids.
|
|
2697
|
+
sweepStaleLeases(limit=20) {
|
|
2698
|
+
const done=[];
|
|
2699
|
+
const stale=this.db.prepare("SELECT c.request_id,c.worker,c.lease_ms,c.lease_deadline_at,c.lease_boot_id,c.lease_deadline_monotonic_ms,c.claimed_at,c.last_claim_activity_at,COALESCE(c.last_claim_activity_at,c.claimed_at) activity FROM claims c JOIN assignments a USING(request_id) WHERE a.status='claimed' AND c.state='active'").all()
|
|
2700
|
+
.filter(c=>!this.heldAfterStart(c))
|
|
2701
|
+
.filter(c=>this.leaseExpired(c)).sort((a,b)=>a.activity<b.activity?-1:1).slice(0,limit);
|
|
2702
|
+
for(const {request_id} of stale) {
|
|
2703
|
+
try { this.abandon(request_id,{actor:'system',reason:'lease_expired'}); done.push(request_id); }
|
|
2704
|
+
catch(e) { if(!/uncertain_delivery|no active claim|terminal/.test(e.message)) throw e; }
|
|
2705
|
+
}
|
|
2706
|
+
return done;
|
|
2707
|
+
}
|
|
2708
|
+
// Expiry sweep: queued rows whose preparation expired (valid_until <= now). A learned (queue_p90) row with requeue
|
|
2709
|
+
// budget left and a computable fresh deadline is requeued, not cancelled: it stays queued with a freshly computed
|
|
2710
|
+
// defaultValidUntil for its worker/kind, expiry_requeues incremented, and a lifecycle 'queued' event (actor system, reason
|
|
2711
|
+
// expired_requeued). The fresh deadline never passes created_at + QUEUE_WINDOW.maxMs (12 h): it is clamped to that cap,
|
|
2712
|
+
// and a row with less than QUEUE_WINDOW.minMs left before the cap is cancelled instead. Rows with no computable fresh deadline (insufficient history), with
|
|
2713
|
+
// expiry_requeues >= 2, and every requester-deadline row are cancelled as before: cancelled_reason 'expired', a lifecycle
|
|
2714
|
+
// 'cancelled' event (reason 'expired'), and pending events and watches suppressed as cancel does. Claimed rows are never
|
|
2715
|
+
// touched; rows without valid_until never match. Bounded and indexed, so the maintenance tick can run it while delivery is
|
|
2716
|
+
// paused. Returns the cancelled request ids, with the requeued ids on the returned array's `requeued` property for the
|
|
2717
|
+
// request log.
|
|
2718
|
+
sweepExpired(limit=100) { return this.transaction(() => {
|
|
2719
|
+
const at=this.stamp(), nowMs=this.nowMs(), rows=this.db.prepare(`SELECT a.request_id,a.valid_until_source,a.expiry_requeues,a.created_at,a.target_worker,${queueKindSql} kind FROM assignments a WHERE status='queued' AND ${expired(nowMs)} ORDER BY valid_until LIMIT ?`).all(limit);
|
|
2720
|
+
const cancelled=[], requeued=[];
|
|
2721
|
+
for(const row of rows) {
|
|
2722
|
+
if(row.valid_until_source==='queue_p90'&&(row.expiry_requeues??0)<2) {
|
|
2723
|
+
const fresh=this.defaultValidUntil(row.target_worker,row.kind), capMs=Date.parse(row.created_at)+QUEUE_WINDOW.maxMs;
|
|
2724
|
+
if(fresh.valid_until&&capMs-nowMs>=QUEUE_WINDOW.minMs) {
|
|
2725
|
+
const next=iso(Math.min(Date.parse(fresh.valid_until),capMs));
|
|
2726
|
+
this.db.prepare("UPDATE assignments SET valid_until=?,expiry_requeues=COALESCE(expiry_requeues,0)+1,skipped_at=NULL,passed_over=0,eligible_since=NULL,listed_count=0,last_listed_at=NULL WHERE request_id=? AND status='queued'").run(next,row.request_id);
|
|
2727
|
+
this.lifecycle(row.request_id,'queued','system','expired_requeued',null);
|
|
2728
|
+
requeued.push(row.request_id);
|
|
2729
|
+
continue;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason='expired' WHERE request_id=? AND status='queued'").run(at,row.request_id);
|
|
2733
|
+
this.lifecycle(row.request_id,'cancelled','system','expired',null);
|
|
2734
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='assignment expired' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(row.request_id);
|
|
2735
|
+
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(at,row.request_id);
|
|
2736
|
+
cancelled.push(row.request_id);
|
|
2737
|
+
}
|
|
2738
|
+
cancelled.push(...this.pullQueue.sweepExpired(Math.max(0,limit-rows.length)));
|
|
2739
|
+
cancelled.requeued=requeued;
|
|
2740
|
+
return cancelled;
|
|
2741
|
+
}); }
|
|
2742
|
+
// Skip expiry sweep: a queued worker assignment that the worker has passed over for skipExpireMs (skipped_at old enough) and
|
|
2743
|
+
// at least SKIP_AFTER_PASSED times is cancelled with cancelled_reason 'skipped_by_worker', so its sender sees the cancellation.
|
|
2744
|
+
// Queued rows for target_worker 'dot' only; claimed rows are never touched. This maintenance runs while delivery is paused.
|
|
2745
|
+
// Returns the ids.
|
|
2746
|
+
sweepSkipped(limit=100) { return this.transaction(() => {
|
|
2747
|
+
const at=this.stamp(), due=iso(this.nowMs()-this.skipExpireMs);
|
|
2748
|
+
const ids=this.db.prepare("SELECT request_id FROM assignments WHERE status='queued' AND target_worker='dot' AND skipped_at IS NOT NULL AND skipped_at<=? AND passed_over>=? ORDER BY skipped_at LIMIT ?").all(due,SKIP_AFTER_PASSED,limit).map(r=>r.request_id);
|
|
2749
|
+
for(const id of ids) {
|
|
2750
|
+
this.db.prepare("UPDATE assignments SET status='cancelled',cancelled_at=?,cancelled_reason='skipped_by_worker' WHERE request_id=? AND status='queued'").run(at,id);
|
|
2751
|
+
this.lifecycle(id,'cancelled','system','skipped_by_worker',null);
|
|
2752
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='skipped by worker' WHERE request_id=? AND state IN ('pending','failed','waiting')").run(id);
|
|
2753
|
+
this.db.prepare("UPDATE watches SET state='suppressed',updated_at=? WHERE request_id=? AND state IN ('armed','fired')").run(at,id);
|
|
2754
|
+
}
|
|
2755
|
+
return ids;
|
|
2756
|
+
}); }
|
|
2757
|
+
// Refresh or cancel an expired preparation before PR preflight; a bounded sweep may leave it expired and queued.
|
|
2758
|
+
refuseExpired(id) {
|
|
2759
|
+
const read=()=>this.db.prepare(`SELECT status,valid_until,valid_until_source,expiry_requeues,cancelled_at,cancelled_reason,${expired(this.nowMs())} expired FROM assignments WHERE request_id=?`).get(id);
|
|
2760
|
+
let a=read();
|
|
2761
|
+
if(a?.status==='queued'&&a.expired) { this.sweepExpired(); a=read(); }
|
|
2762
|
+
if(!a) return;
|
|
2763
|
+
if(a.cancelled_at&&a.cancelled_reason==='expired') throw new Error(expiredError(a.valid_until,{cancelled:true}));
|
|
2764
|
+
if(a.status==='queued'&&a.expired) throw new Error(expiredError(a.valid_until,{requeue:a.valid_until_source==='queue_p90'&&(a.expiry_requeues??0)<2}));
|
|
2765
|
+
}
|
|
2766
|
+
// Queued rows past valid_until, or protocol rows past their retention, that a bounded sweep has not reached yet.
|
|
2767
|
+
queuedExpired(worker=null) {
|
|
2768
|
+
const row=this.db.prepare(`SELECT count(*) n,min(valid_until) oldest FROM assignments WHERE status='queued' AND NOT (${live(this.nowMs())}) AND (? IS NULL OR target_worker=?)`).get(worker,worker);
|
|
2769
|
+
return {count:row.n,oldest_expired_at:row.oldest??null};
|
|
2770
|
+
}
|
|
2771
|
+
// Queued rows previously requeued after a preparation expiry (expiry_requeues > 0) that are still queued, with the oldest
|
|
2772
|
+
// current deadline among them. Reported as queued_expired_requeued next to queued_expired in status --json.
|
|
2773
|
+
queuedExpiredRequeued(worker=null) {
|
|
2774
|
+
const row=this.db.prepare(`SELECT count(*) n,min(valid_until) oldest FROM assignments WHERE status='queued' AND COALESCE(expiry_requeues,0)>0 AND (? IS NULL OR target_worker=?)`).get(worker,worker);
|
|
2775
|
+
return {count:row.n,oldest_valid_until:row.oldest??null};
|
|
2776
|
+
}
|
|
2777
|
+
deliveryMuted(id) { return !!this.db.prepare('SELECT 1 FROM assignment_delivery_mutes WHERE request_id=?').get(id); }
|
|
2778
|
+
suppressFinishedQuestions(requestId=null) {
|
|
2779
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='result superseded question' WHERE (kind='blocker' OR kind='wait' AND body IS NOT NULL) AND state IN ('pending','failed') AND request_id IN (SELECT request_id FROM assignments WHERE status='finished' AND (? IS NULL OR request_id=?))").run(requestId,requestId);
|
|
2780
|
+
}
|
|
2781
|
+
quietDelivery(id,reason) {
|
|
2782
|
+
// Keep results/questions in the existing wait queue. Watches stay visible to
|
|
2783
|
+
// get without masquerading as a worker blocker or an outbound retry.
|
|
2784
|
+
this.db.prepare("UPDATE notifications SET kind=CASE WHEN kind='watch' THEN kind ELSE 'wait' END,state=CASE WHEN kind='watch' THEN 'quiet' ELSE 'pending' END,next_at=0,last_error=? WHERE id=? AND kind IN ('t3','blocker','watch','break') AND state IN ('pending','failed','sending')").run(reason,id);
|
|
2785
|
+
this.suppressFinishedQuestions(this.db.prepare('SELECT request_id FROM notifications WHERE id=?').get(id)?.request_id??null);
|
|
2786
|
+
}
|
|
2787
|
+
quarantineDelivery(id,reason) {
|
|
2788
|
+
return this.db.prepare("UPDATE notifications SET state='suppressed',last_error=?,uncertain_reason=NULL WHERE id=? AND state IN ('pending','failed')").run(String(reason).slice(0,500),id).changes===1;
|
|
2789
|
+
}
|
|
2790
|
+
retryDelivery(id,reason,delayMs=1000) {
|
|
2791
|
+
return this.db.prepare("UPDATE notifications SET state='pending',next_at=?,last_error=?,uncertain_reason=NULL WHERE id=? AND state IN ('pending','failed')").run(this.nowMs()+delayMs,String(reason).slice(0,500),id).changes===1;
|
|
2792
|
+
}
|
|
2793
|
+
paused() { return this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get().paused_at !== null; }
|
|
2794
|
+
setPause(reason) { return this.transaction(() => { this.db.prepare('UPDATE operator_state SET paused_at=?,reason=? WHERE id=1').run(reason?this.stamp():null,reason||null); return {paused:!!reason,reason:reason||null}; }); }
|
|
2795
|
+
suppressStaleQuestion(row) {
|
|
2796
|
+
if(!row||!['blocker','wait'].includes(row.kind)||!row.body) return false;
|
|
2797
|
+
let body;try{body=JSON.parse(row.body);}catch{return false;}
|
|
2798
|
+
if(typeof body.note!=='string'||!Number.isInteger(body.epoch)||!Number.isInteger(body.owner_note_seq)) return false;
|
|
2799
|
+
if(body.question_id!==undefined) {
|
|
2800
|
+
const question=this.db.prepare('SELECT * FROM job_questions WHERE request_id=? AND question_id=?').get(row.request_id,body.question_id);
|
|
2801
|
+
let current=false;
|
|
2802
|
+
if(question&&question.answered_at===null&&question.epoch===body.epoch) try{this.assertQuestionGrant(row.request_id,question);current=true;}catch{}
|
|
2803
|
+
if(!current) return this.db.prepare("UPDATE notifications SET state='suppressed',last_error='structured question no longer current' WHERE id=? AND state IN ('pending','failed','waiting')").run(row.id).changes===1;
|
|
2804
|
+
return false;
|
|
2805
|
+
}
|
|
2806
|
+
const claim=this.db.prepare('SELECT epoch FROM claims WHERE request_id=?').get(row.request_id);
|
|
2807
|
+
if(!claim||body.epoch>=claim.epoch) return false;
|
|
2808
|
+
return this.db.prepare("UPDATE notifications SET state='suppressed',last_error='claim epoch superseded question' WHERE id=? AND state IN ('pending','failed','waiting')").run(row.id).changes===1;
|
|
2809
|
+
}
|
|
2810
|
+
startAttempt(id,argv) { return this.transaction(() => {
|
|
2811
|
+
const row=this.db.prepare('SELECT * FROM notifications WHERE id=?').get(id);
|
|
2812
|
+
if (!row || !['pending','failed'].includes(row.state) || this.paused()) return null;
|
|
2813
|
+
if(this.suppressStaleQuestion(row)) return null;
|
|
2814
|
+
if(!this.questionWakeCurrent(row)) { this.db.prepare("UPDATE notifications SET state='suppressed',last_error='question answer wake no longer current' WHERE id=?").run(id);return null; }
|
|
2815
|
+
const a=row.request_id?this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(row.request_id):null;
|
|
2816
|
+
const message=row.message_id?this.db.prepare('SELECT status FROM messages WHERE message_id=?').get(row.message_id):null;
|
|
2817
|
+
if (a?.status==='cancelled' || a?.status==='finished'&&(row.kind==='blocker'||row.kind==='wait'&&row.body!==null) || message && message.status!=='pending' || row.kind==='watch' && (a.status==='finished'||this.db.prepare('SELECT state,notification_id FROM watches WHERE request_id=?').get(row.request_id)?.notification_id!==id)) {
|
|
2818
|
+
this.db.prepare("UPDATE notifications SET state='suppressed' WHERE id=?").run(id); return null;
|
|
2819
|
+
}
|
|
2820
|
+
if(row.kind==='event'&&row.request_id&&this.isProtocolJob(row.request_id)&&!this.protocolListingLive(row.request_id)) {
|
|
2821
|
+
this.db.prepare("UPDATE notifications SET state='suppressed',last_error='protocol retention expired' WHERE id=?").run(id);return null;
|
|
2822
|
+
}
|
|
2823
|
+
// A re-wake no longer valid is suppressed unsent: it is no last wake, so the next tick recomputes the head. A still
|
|
2824
|
+
// valid retry keeps its id and body.
|
|
2825
|
+
const stale=row.wake_kind==='rewake'&&this.rewakeStale(row);
|
|
2826
|
+
if (stale) { this.db.prepare("UPDATE notifications SET state='suppressed',last_error=? WHERE id=?").run(`re-wake not sent: ${stale}`,id); return null; }
|
|
2827
|
+
if(row.kind==='event') {
|
|
2828
|
+
const sub=this.db.prepare('SELECT * FROM subscriptions WHERE id=?').get(row.subscription_id);
|
|
2829
|
+
if(!this.subscriptionActive(sub)||!this.mayAct(sub.worker,row.request_id??row.message_id)) {this.db.prepare("UPDATE notifications SET state='suppressed',last_error='worker cannot see event' WHERE id=?").run(id);return null;}
|
|
2830
|
+
}
|
|
2831
|
+
const attemptId=`attempt_${randomUUID()}`;
|
|
2832
|
+
this.db.prepare("UPDATE notifications SET state='sending',attempts=attempts+1,attempt_started_at=?,attempt_id=?,argv=? WHERE id=?").run(this.stamp(),attemptId,argv?JSON.stringify(argv):null,id);
|
|
2833
|
+
return {...row,attempt_id:attemptId};
|
|
2834
|
+
}); }
|
|
2835
|
+
deliveryAttemptIsCurrent(id,attemptId) { return !!this.db.prepare("SELECT 1 FROM notifications WHERE id=? AND state='sending' AND attempt_id=?").get(id,attemptId); }
|
|
2836
|
+
// Reserve a durable owner-attention delivery for a currently attached long-poll.
|
|
2837
|
+
// The caller must release it on socket close; only a completed response settles it.
|
|
2838
|
+
deliveryKind(requestId, t3Kind) { return this.db.prepare('SELECT delivery FROM assignments WHERE request_id=?').get(requestId).delivery==='none'?'wait':t3Kind; }
|
|
2839
|
+
deliveryCursor(requestId) { return this.db.prepare('SELECT COALESCE(max(rowid),0) cursor FROM notifications WHERE request_id=?').get(requestId).cursor; }
|
|
2840
|
+
claimWaiterDelivery(requestId, cursor) { return this.transaction(() => {
|
|
2841
|
+
const row=this.db.prepare("SELECT * FROM notifications WHERE request_id=? AND kind IN ('t3','blocker','wait') AND state='pending' AND (rowid>? OR kind='wait') ORDER BY rowid LIMIT 1").get(requestId,cursor);
|
|
2842
|
+
if(!row||this.suppressStaleQuestion(row)) return null;
|
|
2843
|
+
const attemptId='wait:'+JSON.stringify({...waiterProcessIdentity(),nonce:randomUUID()});
|
|
2844
|
+
const changed=this.db.prepare("UPDATE notifications SET state='waiting',attempt_started_at=?,attempt_id=? WHERE id=? AND state='pending'").run(this.stamp(),attemptId,row.id);
|
|
2845
|
+
return changed.changes===1?{...row,state:'waiting',attempt_id:attemptId}:null;
|
|
2846
|
+
}); }
|
|
2847
|
+
settleWaiterDelivery(id, consume=true) { return this.transaction(() => {
|
|
2848
|
+
const row=this.db.prepare('SELECT kind,request_id,body FROM notifications WHERE id=?').get(id);
|
|
2849
|
+
const changed=this.db.prepare("UPDATE notifications SET state='delivered',last_error='',uncertain_reason=NULL WHERE id=? AND state='waiting'").run(id).changes;
|
|
2850
|
+
// A result notification has no body; blocker attention carries the note.
|
|
2851
|
+
if(consume&&changed&&row?.request_id&&row.body===null) this.consumeOnce(row.request_id,'wait');
|
|
2852
|
+
}); }
|
|
2853
|
+
// The owner received a finished report (wait delivery or admin get). Only the first receipt per request counts.
|
|
2854
|
+
consumeOnce(id,via) {
|
|
2855
|
+
this.pullQueue.consume(id);
|
|
2856
|
+
this.db.prepare("UPDATE assignments SET owner_read_at=? WHERE request_id=? AND status='cancelled' AND owner_read_at IS NULL").run(this.stamp(),id);
|
|
2857
|
+
if(this.db.prepare("SELECT status FROM assignments WHERE request_id=?").get(id)?.status!=='finished') return false;
|
|
2858
|
+
if(this.db.prepare("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='consumed' LIMIT 1").get(id)) return false;
|
|
2859
|
+
this.lifecycle(id,'consumed','owner',via);
|
|
2860
|
+
return true;
|
|
2861
|
+
}
|
|
2862
|
+
// Read-only view of one request for the owner's inbox: what the owner has and has not seen. Writes nothing.
|
|
2863
|
+
ownerInbox(id) {
|
|
2864
|
+
const policyInbox=this.pullQueue.inbox(id);if(policyInbox)return policyInbox;
|
|
2865
|
+
const a=this.db.prepare('SELECT status,payload,target_worker,created_at,cancelled_at,cancelled_reason,owner_read_at FROM assignments WHERE request_id=?').get(id);
|
|
2866
|
+
const one=(sql,...p)=>this.db.prepare(sql).get(...p);
|
|
2867
|
+
const report=one('SELECT outcome,created_at FROM reports WHERE request_id=?',id);
|
|
2868
|
+
const cancelActor=a.status==='cancelled'?one("SELECT actor FROM lifecycle_events WHERE request_id=? AND type='cancelled' ORDER BY rowid DESC LIMIT 1",id)?.actor??null:null;
|
|
2869
|
+
const blockers=this.db.prepare('SELECT note,created_at FROM progress WHERE request_id=? ORDER BY id').all(id).filter(p=>/^\s*(?:BLOCKED:|QUESTION:)/im.test(p.note));
|
|
2870
|
+
const lastAnswer=one('SELECT max(at) at FROM owner_notes WHERE request_id=?',id)?.at??null;
|
|
2871
|
+
const lastBlocker=blockers.at(-1)??null;
|
|
2872
|
+
return {
|
|
2873
|
+
target_worker:a.target_worker,brief:String(JSON.parse(a.payload).brief??''),created_at:a.created_at,
|
|
2874
|
+
finished_at:report?.created_at??null,outcome:report?.outcome??null,
|
|
2875
|
+
consumed:!!one("SELECT 1 FROM lifecycle_events WHERE request_id=? AND type='consumed' LIMIT 1",id),
|
|
2876
|
+
decision:this.latestDecision(id)?.decision??null,
|
|
2877
|
+
// The finished result reached the owner's T3 thread: a 't3' notification the bridge sent ('delivered' via finishAttempt) or
|
|
2878
|
+
// that the transcript check confirmed ('delivered' via reconciled). A sent-but-uncertain, failed or pending one does not count.
|
|
2879
|
+
delivered_t3:!!one("SELECT 1 FROM notifications WHERE request_id=? AND kind='t3' AND state='delivered' LIMIT 1",id),
|
|
2880
|
+
cancelled_at:a.cancelled_at,cancelled_reason:a.cancelled_reason??null,cancelled_by_owner:cancelActor==='owner',read:a.owner_read_at!==null,
|
|
2881
|
+
...this.failureFields(id),
|
|
2882
|
+
unanswered_blocker:lastBlocker&&(lastAnswer===null||lastBlocker.created_at>lastAnswer)?{text:lastBlocker.note,at:lastBlocker.created_at}:null,
|
|
2883
|
+
};
|
|
2884
|
+
}
|
|
2885
|
+
// Owner action for `dalan inbox --mark-read`: the same read marker as get, without fetching the result. True when it was unread.
|
|
2886
|
+
markInboxRead(id,via) { return this.transaction(() => {
|
|
2887
|
+
const status=this.get(id).status, v=this.ownerInbox(id);
|
|
2888
|
+
const unread=status==='finished'?!v.consumed:status==='cancelled'?!v.read:false;
|
|
2889
|
+
this.consumeOnce(id,via); return unread;
|
|
2890
|
+
}); }
|
|
2891
|
+
recordConsumed(id,via) { return this.transaction(() => this.consumeOnce(id,via)); }
|
|
2892
|
+
// Latest decision on a request: the decisions table, else the legacy accept/reject events from before it existed.
|
|
2893
|
+
latestDecision(id) {
|
|
2894
|
+
const row=this.db.prepare('SELECT decision,actor,at FROM decisions WHERE request_id=? ORDER BY id DESC LIMIT 1').get(id);
|
|
2895
|
+
if(row) return row;
|
|
2896
|
+
const legacy=this.db.prepare("SELECT type,at FROM lifecycle_events WHERE request_id=? AND (type='accepted' OR type='consumed' AND reason LIKE 'rejected%') ORDER BY id DESC LIMIT 1").get(id);
|
|
2897
|
+
return legacy?{decision:legacy.type==='accepted'?'accepted':'not_useful',actor:'owner',at:legacy.at}:null;
|
|
2898
|
+
}
|
|
2899
|
+
// Record a decision on a finished report. Append-only: a different decision is added and the latest wins; the same decision
|
|
2900
|
+
// again is a no-op. accepted and applied also write the 'accepted' event, not_useful the legacy reject event, so readers of
|
|
2901
|
+
// those events keep working; an owner decision also counts as the owner read.
|
|
2902
|
+
decide(id,decision,opts={}) { return this.transaction(() => this.recordDecision(id,decision,opts)); }
|
|
2903
|
+
recordDecision(id,decision,{note=null,actor='owner',via='cli'}={}) {
|
|
2904
|
+
if(!decisionTypes.includes(decision)) throw new Error(`decision must be one of ${decisionTypes.join(', ')}`);
|
|
2905
|
+
const a=this.db.prepare('SELECT status FROM assignments WHERE request_id=?').get(id); if(!a) throw new Error('assignment not found');
|
|
2906
|
+
if(a.status!=='finished') throw new Error('only a finished assignment can be decided');
|
|
2907
|
+
const latest=this.db.prepare('SELECT decision,actor FROM decisions WHERE request_id=? ORDER BY id DESC LIMIT 1').get(id);
|
|
2908
|
+
if(decision==='stale'&&(actor!=='system'||this.latestDecision(id))) return {request_id:id,decision:latest?.decision??null,duplicate:true};
|
|
2909
|
+
if(latest&&latest.decision===decision&&latest.actor===actor) return {request_id:id,decision,duplicate:true,at:this.stamp()};
|
|
2910
|
+
const at=this.stamp();
|
|
2911
|
+
this.db.prepare('INSERT INTO decisions(request_id,decision,note,actor,via,at) VALUES(?,?,?,?,?,?)').run(id,decision,note,actor,via,at);
|
|
2912
|
+
if(actor==='owner') {
|
|
2913
|
+
this.consumeOnce(id,'decide');
|
|
2914
|
+
if(decision==='accepted'||decision==='applied') this.lifecycle(id,'accepted','owner',decision==='applied'?(note?`applied: ${note}`:'applied'):note);
|
|
2915
|
+
else if(decision==='not_useful') this.lifecycle(id,'consumed','owner',note?`rejected: ${note}`:'rejected');
|
|
2916
|
+
}
|
|
2917
|
+
return {request_id:id,decision,note,at};
|
|
2918
|
+
}
|
|
2919
|
+
// Owner verdicts on a finished report (accept and reject, kept as aliases of decide accepted and not_useful).
|
|
2920
|
+
verdict(id,accepted,note=null) {
|
|
2921
|
+
const r=this.decide(id,accepted?'accepted':'not_useful',{note});
|
|
2922
|
+
return {request_id:id,verdict:accepted?'accepted':'rejected',decision:r.decision,note,at:r.at??this.stamp()};
|
|
2923
|
+
}
|
|
2924
|
+
// Finished reports with no decision for `days` days get decision 'stale' (actor system). Looks back at most 90 days and
|
|
2925
|
+
// records at most `limit` per call, oldest first, so a first run on an old database stays small.
|
|
2926
|
+
sweepStaleDecisions(days,{limit=500,now=Date.now()}={}) { return this.transaction(() => {
|
|
2927
|
+
const ids=this.db.prepare(`SELECT r.request_id FROM reports r JOIN assignments a USING(request_id) WHERE a.status='finished' AND r.created_at<? AND r.created_at>=?
|
|
2928
|
+
AND NOT EXISTS(SELECT 1 FROM decisions d WHERE d.request_id=r.request_id)
|
|
2929
|
+
AND NOT EXISTS(SELECT 1 FROM lifecycle_events e WHERE e.request_id=r.request_id AND (e.type='accepted' OR e.type='consumed' AND e.reason LIKE 'rejected%'))
|
|
2930
|
+
ORDER BY r.created_at LIMIT ?`).all(new Date(now-days*86400000).toISOString(),new Date(now-90*86400000).toISOString(),limit).map(r=>r.request_id);
|
|
2931
|
+
for(const id of ids) this.recordDecision(id,'stale',{actor:'system',via:'sweep',note:`no decision in ${days} days`});
|
|
2932
|
+
return ids;
|
|
2933
|
+
}); }
|
|
2934
|
+
// The fix loop reports a merged PR. Idempotent per request.
|
|
2935
|
+
integrated(id,reason=null) { return this.transaction(() => {
|
|
2936
|
+
if(!this.hasAssignment(id)) throw new Error('assignment not found');
|
|
2937
|
+
const old=this.db.prepare("SELECT at FROM lifecycle_events WHERE request_id=? AND type='integrated' LIMIT 1").get(id);
|
|
2938
|
+
if(old) return {request_id:id,integrated_at:old.at,duplicate:true};
|
|
2939
|
+
this.lifecycle(id,'integrated','fix-loop',reason);
|
|
2940
|
+
return {request_id:id,integrated_at:this.stamp(),duplicate:false};
|
|
2941
|
+
}); }
|
|
2942
|
+
releaseWaiterDelivery(id, reason='waiter disconnected') { return this.transaction(()=>{
|
|
2943
|
+
const row=this.db.prepare('SELECT * FROM notifications WHERE id=?').get(id);
|
|
2944
|
+
if(this.suppressStaleQuestion(row)) return;
|
|
2945
|
+
this.db.prepare("UPDATE notifications SET state='pending',next_at=0,last_error=? WHERE id=? AND state='waiting'").run(reason,id);
|
|
2946
|
+
this.suppressFinishedQuestions(row?.request_id??null);
|
|
2947
|
+
}); }
|
|
2948
|
+
finishAttempt(id,attemptId,state,reason='') { return this.transaction(() => {
|
|
2949
|
+
const row=this.db.prepare('SELECT kind,request_id,attempts FROM notifications WHERE id=?').get(id);
|
|
2950
|
+
const changed=this.db.prepare('UPDATE notifications SET state=?,last_error=?,uncertain_reason=?,next_at=? WHERE id=? AND attempt_id=? AND state=\'sending\'').run(state,reason,state==='uncertain'?reason:null,Date.now()+Math.min(60000,1000*2**Math.min(row.attempts,6)),id,attemptId).changes;
|
|
2951
|
+
// Webhook events are not a destination and write no lifecycle event.
|
|
2952
|
+
if(changed&&row.request_id&&['t3','blocker','watch'].includes(row.kind)&&(state==='delivered'||state==='uncertain')) this.lifecycle(row.request_id,state==='delivered'?'delivery_sent':'delivery_uncertain','system',row.kind);
|
|
2953
|
+
}); }
|
|
2954
|
+
recoverSends() { return this.transaction(() => {
|
|
2955
|
+
const rows=this.db.prepare("SELECT id,kind,request_id FROM notifications WHERE state='sending'").all();
|
|
2956
|
+
for (const row of rows) {
|
|
2957
|
+
this.db.prepare("UPDATE notifications SET state=?,uncertain_reason='interrupted send' WHERE id=?").run(row.kind==='event'?'failed':'uncertain',row.id);
|
|
2958
|
+
if(row.request_id&&['t3','blocker','watch'].includes(row.kind)) this.lifecycle(row.request_id,'delivery_uncertain','system',`${row.kind}: interrupted send`);
|
|
2959
|
+
}
|
|
2960
|
+
for(const row of this.db.prepare("SELECT * FROM notifications WHERE state='waiting'").all()) {
|
|
2961
|
+
// Absence of a local waiter Map is not evidence that another process died.
|
|
2962
|
+
if(!waiterOwnerGone(row.attempt_id)) continue;
|
|
2963
|
+
if(!this.suppressStaleQuestion(row)) this.db.prepare("UPDATE notifications SET state='pending',next_at=0,last_error='waiter owner exited' WHERE id=? AND state='waiting'").run(row.id);
|
|
2964
|
+
}
|
|
2965
|
+
this.suppressFinishedQuestions();
|
|
2966
|
+
return rows;
|
|
2967
|
+
}); }
|
|
2968
|
+
due() { return this.db.prepare("SELECT * FROM notifications WHERE kind IN ('event','t3','blocker','watch','break') AND state IN ('pending','failed') AND next_at<=? ORDER BY next_at,created_at,id LIMIT 10").all(Date.now()); }
|
|
2969
|
+
uncertain(id) { return this.db.prepare("SELECT * FROM notifications WHERE state IN ('uncertain','uncertain_terminal') AND kind IN ('t3','watch','blocker','break') AND (? IS NULL OR request_id=?) ORDER BY COALESCE(last_reconciled_at,'') ASC,created_at ASC").all(id??null,id??null); }
|
|
2970
|
+
uncertainOne(id) { return this.db.prepare("SELECT * FROM notifications WHERE state IN ('uncertain','uncertain_terminal') AND kind IN ('t3','watch','blocker','break') AND request_id=? ORDER BY COALESCE(last_reconciled_at,'') ASC,created_at ASC LIMIT 1").get(id)??null; }
|
|
2971
|
+
uncertainDue(now=this.nowMs()) { return this.uncertainBatch(now,1)[0]??null; }
|
|
2972
|
+
uncertainBatch(now=this.nowMs(),limit=25) {
|
|
2973
|
+
if(!Number.isFinite(now)||!Number.isInteger(now)||!Number.isFinite(new Date(now-60000).getTime())) return [];
|
|
2974
|
+
if(!Number.isInteger(limit)||limit<1||limit>25) throw new Error('invalid reconciliation batch limit');
|
|
2975
|
+
return this.db.prepare("SELECT * FROM notifications WHERE state IN ('uncertain','uncertain_terminal') AND kind IN ('t3','watch','blocker','event') AND next_at<=? AND (last_reconciled_at IS NULL OR last_reconciled_at<=?) ORDER BY COALESCE(last_reconciled_at,'') ASC,created_at ASC,id ASC LIMIT ?").all(now,iso(now-60000),limit);
|
|
2976
|
+
}
|
|
2977
|
+
reconciled(id,state,reason,{attemptId,threadId,environmentId,targetWorker,attemptStartedAt,body,argv,assignmentStatus,deliveryMode,reportSnapshot}={}) { return this.transaction(() => {
|
|
2978
|
+
const row=this.db.prepare('SELECT n.*,a.thread_id,a.environment_id,a.target_worker FROM notifications n LEFT JOIN assignments a USING(request_id) WHERE n.id=?').get(id);
|
|
2979
|
+
// get() projects legacy empty thread/environment strings as null in the captured snapshot.
|
|
2980
|
+
if(!row||!['uncertain','uncertain_terminal'].includes(row.state)||row.attempt_id!==attemptId||row.attempt_started_at!==attemptStartedAt||row.body!==body||row.argv!==argv||(row.thread_id||null)!==threadId||(row.environment_id||null)!==environmentId||row.target_worker!==targetWorker) return false;
|
|
2981
|
+
const assignment=this.db.prepare('SELECT status,delivery delivery_mode FROM assignments WHERE request_id=?').get(row.request_id);
|
|
2982
|
+
if((assignment?.status??null)!==assignmentStatus||(assignment?.delivery_mode??null)!==deliveryMode) return false;
|
|
2983
|
+
const report=this.db.prepare('SELECT outcome,summary,result FROM reports WHERE request_id=?').get(row.request_id)??null;
|
|
2984
|
+
if(JSON.stringify(report)!==reportSnapshot) return false;
|
|
2985
|
+
// Missing proof cannot turn an aged unknown into a fresh retry cycle.
|
|
2986
|
+
if(row.state==='uncertain_terminal'&&state==='uncertain') state='uncertain_terminal';
|
|
2987
|
+
const changed=this.db.prepare("UPDATE notifications SET state=?,last_reconciled_at=?,uncertain_reason=?,last_error=?,next_at=? WHERE id=? AND state IN ('uncertain','uncertain_terminal') AND attempt_id IS ? AND attempt_started_at IS ? AND body IS ? AND argv IS ?").run(state,this.stamp(),['uncertain','uncertain_terminal'].includes(state)?reason:null,reason,this.nowMs()+60000,id,attemptId,attemptStartedAt,body,argv).changes;
|
|
2988
|
+
if(changed&&state==='delivered'&&row.request_id&&!['break','event'].includes(row.kind)) this.lifecycle(row.request_id,'reconciled','system',row.kind);
|
|
2989
|
+
return changed===1;
|
|
2990
|
+
}); }
|
|
2991
|
+
releaseAgedUncertain(observedIds=null) { return this.transaction(()=>{
|
|
2992
|
+
const now=this.nowMs(); if(!Number.isFinite(now)||!Number.isInteger(now)||!Number.isFinite(new Date(now).getTime())) return [];
|
|
2993
|
+
if(observedIds!==null&&(!Array.isArray(observedIds)||observedIds.length>25||observedIds.some(id=>typeof id!=='string'))) throw new Error('invalid observed reconciliation IDs');
|
|
2994
|
+
if(observedIds?.length===0) return [];
|
|
2995
|
+
const filter=observedIds===null?'':` AND id IN (${observedIds.map(()=>'?').join(',')})`;
|
|
2996
|
+
const candidates=this.db.prepare("SELECT * FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','event')"+filter+" ORDER BY COALESCE(attempt_started_at,created_at) ASC,COALESCE(last_reconciled_at,'') ASC,created_at ASC LIMIT 100").all(...(observedIds??[]));
|
|
2997
|
+
const released=[];
|
|
2998
|
+
for(const row of candidates) {
|
|
2999
|
+
const started=Date.parse(row.attempt_started_at||row.created_at);
|
|
3000
|
+
if(!Number.isFinite(started)||now<started||now-started<UNCERTAIN_DELIVERY_MAX_AGE_MS) continue;
|
|
3001
|
+
const reason='delivery unknown, not proven undelivered; automatic retries ended after 30 minutes; new claims require positive reconciliation',at=this.stamp();
|
|
3002
|
+
const changed=this.db.prepare("UPDATE notifications SET state='uncertain_terminal',terminal_at=?,terminal_reason=?,last_error=?,uncertain_reason=? WHERE id=? AND state='uncertain'").run(at,reason,reason,reason,row.id).changes;
|
|
3003
|
+
if(!changed) continue;
|
|
3004
|
+
this.db.prepare('INSERT INTO uncertain_delivery_alerts(notification_id,request_id,created_at,reason) VALUES(?,?,?,?) ON CONFLICT(notification_id) DO NOTHING').run(row.id,row.request_id,at,reason);
|
|
3005
|
+
released.push({id:row.id,request_id:row.request_id,at,reason});
|
|
3006
|
+
if(released.length===25) break;
|
|
3007
|
+
}
|
|
3008
|
+
return released;
|
|
3009
|
+
}); }
|
|
3010
|
+
pendingDeliveryAlerts() { return this.db.prepare('SELECT x.*,n.message_id FROM uncertain_delivery_alerts x JOIN notifications n ON n.id=x.notification_id WHERE x.published_at IS NULL ORDER BY x.created_at,x.notification_id LIMIT 25').all(); }
|
|
3011
|
+
deliveryAlertLogged(id) { this.db.prepare('UPDATE uncertain_delivery_alerts SET logged_at=? WHERE notification_id=? AND logged_at IS NULL').run(this.stamp(),id); }
|
|
3012
|
+
deliveryAlertPublished(id) { this.db.prepare('UPDATE uncertain_delivery_alerts SET published_at=? WHERE notification_id=? AND published_at IS NULL').run(this.stamp(),id); }
|
|
3013
|
+
eventResult(subscriptionId,status) { this.db.prepare('UPDATE subscriptions SET last_event_2xx_at=CASE WHEN ? BETWEEN 200 AND 299 THEN ? ELSE last_event_2xx_at END,auth_failures=CASE WHEN ? IN (401,403) THEN auth_failures+1 ELSE 0 END WHERE id=?').run(status,this.stamp(),status,subscriptionId); }
|
|
3014
|
+
adopt(id,ownerToken) { return this.transaction(() => { const row=this.db.prepare('SELECT owner_hash FROM assignments WHERE request_id=?').get(id); if(!row) throw new Error('assignment not found'); if(row.owner_hash) throw new Error('request already owned'); this.db.prepare('UPDATE assignments SET owner_hash=? WHERE request_id=?').run(hash(ownerToken),id); return {request_id:id,adopted:true}; }); }
|
|
3015
|
+
status({limits=this.limits,capacity=this.capacity,backgroundMaxInFlight=this.backgroundMaxInFlight}={}) {
|
|
3016
|
+
// Queued counts are live: rows past valid_until are reported as queued_expired, and protocol jobs past retention are
|
|
3017
|
+
// left out, never counted as queue, cap or throttle room.
|
|
3018
|
+
const queuedExpired=this.queuedExpired(), queuedExpiredRequeued=this.queuedExpiredRequeued();
|
|
3019
|
+
const counts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE status<>'queued' OR ${live(this.nowMs())} GROUP BY status`).all().filter(x=>x.count>0);
|
|
3020
|
+
const sub=this.db.prepare("SELECT * FROM subscriptions WHERE worker='dot' ORDER BY verified_at DESC LIMIT 1").get();
|
|
3021
|
+
const active=this.activeSubscriptions().filter(sub=>sub.worker==='dot');
|
|
3022
|
+
const oldest=this.db.prepare(`SELECT min(created_at) oldest FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())}`).get().oldest;
|
|
3023
|
+
const lastClaim=this.db.prepare("SELECT max(claimed_at) last_claim FROM claims WHERE worker='dot'").get().last_claim;
|
|
3024
|
+
const uncertain=this.db.prepare("SELECT count(*) n FROM notifications WHERE state='uncertain' AND kind IN ('t3','watch','blocker','break','event')").get().n;
|
|
3025
|
+
const pause=this.db.prepare('SELECT paused_at,reason FROM operator_state WHERE id=1').get();
|
|
3026
|
+
const queued=this.queuedRows().filter(row=>row.target_worker==='dot').length;
|
|
3027
|
+
const dotQueuedWithoutSubscription=active.length===0&&!!this.db.prepare(`SELECT 1 FROM assignments WHERE target_worker='dot' AND status='queued' AND ${live(this.nowMs())} LIMIT 1`).get();
|
|
3028
|
+
const subscription={state:!sub?'absent':sub.state==='revoked'?'revoked':sub.rotation_blocked?'rotation_blocked':sub.auth_failures>=3?'callback_blocked':sub.expires_at<=this.stamp()?'expired':'active',expires_at:sub?.expires_at||null,last_verified_at:sub?.verified_at||null,last_event_2xx_at:sub?.last_event_2xx_at||null,last_claim_at:lastClaim,principal:sub?.principal||null,auth_failures:sub?.auth_failures||0};
|
|
3029
|
+
const priority_counts=Object.fromEntries(['normal','background'].map(priority=>[priority,Object.fromEntries(['queued','claimed'].map(status=>[status,this.db.prepare(`SELECT count(*) n FROM assignments WHERE priority=? AND status=? AND (status<>'queued' OR ${live(this.nowMs())})`).get(priority,status).n]))]));
|
|
3030
|
+
const throttle=this.rollingUsage(limits);
|
|
3031
|
+
const budget={window:'rolling_24h',calls_used:throttle.tool_calls_last_24h,calls_cap:throttle.max_tool_calls_per_24h,
|
|
3032
|
+
bytes_used:throttle.response_bytes_last_24h,bytes_cap:throttle.max_response_bytes_per_24h};
|
|
3033
|
+
budget.remaining_fraction=Math.round(Math.max(0,Math.min(1,1-budget.calls_used/budget.calls_cap,1-budget.bytes_used/budget.bytes_cap))*1000)/1000;
|
|
3034
|
+
const denied=this.deniedQueued();
|
|
3035
|
+
const dotCapacity=this.workerCapacityEvidence('dot',active,limits,capacity);
|
|
3036
|
+
const freeLanes=dotCapacity.free_lanes;
|
|
3037
|
+
const legacyScope=this.workers.legacy===true||this.workers.workers.has('dot')?'dot':'none';
|
|
3038
|
+
const dispatch={scope:legacyScope,state:pause.paused_at?'paused':freeLanes===null?'unknown':freeLanes<=0?'full':queued>0?'dispatch_gap':'supply_gap',free_lanes:freeLanes,queued_live:queued,oldest_unclaimed_age_ms:oldest?this.nowMs()-Date.parse(oldest):null};
|
|
3039
|
+
const workerNames=new Set([...this.workers.workers.keys(),...this.db.prepare('SELECT DISTINCT target_worker worker FROM assignments').all().map(r=>r.worker),...this.db.prepare('SELECT DISTINCT worker FROM claims').all().map(r=>r.worker)]);
|
|
3040
|
+
const by_worker=Object.fromEntries([...workerNames].sort().map(worker=>{
|
|
3041
|
+
const workerSubscriptions=worker==='dot'?active:this.activeSubscriptions().filter(row=>row.worker===worker);
|
|
3042
|
+
const liveness=this.liveness(limits,capacity,worker),expired=this.queuedExpired(worker);
|
|
3043
|
+
const requeued=this.queuedExpiredRequeued(worker);
|
|
3044
|
+
const workerCounts=this.db.prepare(`SELECT status,count(*) count FROM assignments WHERE target_worker=? AND (status<>'queued' OR ${live(this.nowMs())}) GROUP BY status`).all(worker).filter(row=>row.count>0);
|
|
3045
|
+
const liveQueued=this.queuedRows().filter(row=>row.target_worker===worker).length;
|
|
3046
|
+
return [worker,{scope:'worker',counts:workerCounts,queued_expired:expired,queued_expired_requeued:requeued,active_claims:liveness.claimed_outer_count,queued_live:liveQueued,subscriptions_active:workerSubscriptions.length,capacity:this.workerCapacityEvidence(worker,workerSubscriptions,limits,capacity),last_call_at:liveness.last_worker_call_at,last_list_pending_at:liveness.last_list_pending_at,stale_claims:liveness.stale_claims,queue_classes:liveness.queue_classes,unclaimed_after_reannounce:liveness.unclaimed_after_reannounce,oldest_claim_age_ms:liveness.oldest_claim_age_ms,oldest_claim_progress_age_ms:liveness.oldest_claim_progress_age_ms,oldest_unclaimed_event_2xx_age_ms:liveness.oldest_unclaimed_event_2xx_age_ms,silence_ms:liveness.worker_silence_ms}];
|
|
3047
|
+
}));
|
|
3048
|
+
const released=this.db.prepare("SELECT id,id notice_id,request_id,message_id,subscription_id,attempt_id,attempt_started_at,terminal_at,terminal_reason FROM notifications WHERE state='uncertain_terminal' ORDER BY terminal_at DESC LIMIT 20").all();
|
|
3049
|
+
return {dispatch,liveness_scope:legacyScope,counts,counts_scope:'global',by_worker,priority_counts,priority_counts_scope:'global',background_max_in_flight:backgroundMaxInFlight,skipped_by_worker:(skipped=>({count:skipped.length,request_ids:skipped.slice(0,20).map(x=>x.request_id)}))(this.skippedByDot()),claim_denied:{count:denied.length,request_ids:denied.map(d=>d.request_id).slice(0,20),capacity_hold_until:this.capacityHoldUntil()},subscriptions_active:active.length,last_verified:sub?.verified_at||null,oldest_pending:oldest,last_claim:lastClaim,last_claim_at:lastClaim,subscription,queued_without_active_subscription:dotQueuedWithoutSubscription,oldest_queue_age_ms:oldest?this.nowMs()-Date.parse(oldest):null,uncertain_deliveries:uncertain,uncertain_terminal_deliveries:released,queued_expired:queuedExpired,queued_expired_requeued:queuedExpiredRequeued,paused:!!pause.paused_at,pause_reason:pause.reason,...(({items,...rest})=>rest)(this.liveness(limits,capacity)),worker_break:this.breakState(),throttle,budget,...statusEvidence(this)};
|
|
3050
|
+
}
|
|
3051
|
+
workerCapacityEvidence(worker,subscriptions,limits,capacity) {
|
|
3052
|
+
const byPrincipal=[...new Map(subscriptions.map(sub=>[sub.principal,sub])).values()];
|
|
3053
|
+
const scope=this.workers.laneScope==='worker'?'worker':'principal';
|
|
3054
|
+
const unknown=reason=>({state:'unknown',scope,source:null,free_lanes:null,unknown_reason:reason});
|
|
3055
|
+
if(!byPrincipal.length) return unknown('no_active_subscription');
|
|
3056
|
+
const subjectKeys=this.db.prepare("SELECT DISTINCT c.lane_key FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.state='active' AND c.lane_scope='subject' AND a.status='claimed'").all(worker).map(row=>row.lane_key);
|
|
3057
|
+
const principals=[...new Set([...byPrincipal.map(sub=>sub.principal),...subjectKeys])];
|
|
3058
|
+
if((scope==='principal'||subjectKeys.length>0)&&principals.length>1) {
|
|
3059
|
+
return {...unknown('ambiguous_principal_scope'),by_principal:Object.fromEntries(principals.map(principal=>{
|
|
3060
|
+
const sub=byPrincipal.find(row=>row.principal===principal);
|
|
3061
|
+
return [principal,sub?{free_lanes:this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity),lane_scope:'subject',lane_key:principal}:{free_lanes:null,lane_scope:'subject',lane_key:principal,unknown_reason:'no_active_subscription'}];
|
|
3062
|
+
}))};
|
|
3063
|
+
}
|
|
3064
|
+
const sub=byPrincipal[0];
|
|
3065
|
+
const lanes=this.subscriptionFreeLanes(sub,limits.laneCapacity??6,capacity);
|
|
3066
|
+
const laneEvidence=this.db.prepare("SELECT DISTINCT c.lane_scope,c.lane_key FROM claims c JOIN assignments a USING(request_id) WHERE c.worker=? AND c.state='active' AND a.status='claimed' ORDER BY c.lane_scope,c.lane_key").all(worker).map(row=>({lane_scope:row.lane_scope,lane_key:row.lane_key}));
|
|
3067
|
+
return {state:'known',scope,source:'subscription_policy',free_lanes:lanes,lane_capacity:Math.min(limits.laneCapacity??6,capacity),principal:scope==='principal'?sub.principal:undefined,lane_evidence:laneEvidence};
|
|
3068
|
+
}
|
|
3069
|
+
}
|