trantor 0.18.148 → 0.18.149
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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/bin/crew/state.mjs +1 -1
- package/bin/crew-runner.mjs +4 -2
- package/bin/docker-seat.mjs +33 -0
- package/bin/heavy-gate-shim/docker +2 -0
- package/bin/migrate-dispatcher.mjs +50 -0
- package/hub/auth.mjs +3 -3
- package/hub/routes/cards.mjs +13 -1
- package/hub/routes/dispatcher-operations.mjs +122 -0
- package/hub/routes/dispatcher.mjs +18 -9
- package/hub/store.mjs +20 -0
- package/hub.mjs +16 -1
- package/kimi.plugin.json +1 -1
- package/lib/dispatcher/admission.mjs +15 -3
- package/lib/dispatcher/operations.mjs +401 -0
- package/lib/dispatcher/preflight.mjs +2 -0
- package/lib/dispatcher/snapshot.mjs +72 -1
- package/lib/dispatcher/verifier.mjs +246 -0
- package/lib/docker-janitor.mjs +24 -14
- package/lib/store-contract.mjs +57 -0
- package/lib/store-pg.mjs +38 -3
- package/package.json +1 -1
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { adjudicateAcceptance, createVerificationJob, claimVerificationJob, VerifierGrantSchema,
|
|
4
|
+
JOB_LEASE_MS } from './acceptance.mjs';
|
|
5
|
+
import { canonicalHash, canonicalJson } from './snapshot.mjs';
|
|
6
|
+
import { requireIdentity, storedScopeAllows, reject } from './admission.mjs';
|
|
7
|
+
import { executionRows, saveExecution, fenceExecution } from './executor.mjs';
|
|
8
|
+
|
|
9
|
+
const text = z.string().min(1).max(8192);
|
|
10
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
11
|
+
const VerifyRequestSchema = z.strictObject({ schemaVersion: z.literal(1), artifactHash: text,
|
|
12
|
+
cardRevision: integer, drillSpecId: text, featureRegistryHash: text, idempotencyKey: text });
|
|
13
|
+
const ClaimRequestSchema = z.strictObject({ grantId: text, machine: text, capabilityReportHash: text });
|
|
14
|
+
const BeatSchema = z.strictObject({ jobNonce: text, sequence: integer.min(1), processIdentity: z.json() });
|
|
15
|
+
const SubmissionSchema = z.strictObject({ schemaVersion: z.literal(1), jobId: text, jobNonce: text,
|
|
16
|
+
cardRevision: integer, artifactHash: text, testedSha: text.nullable(), drillSpecId: text,
|
|
17
|
+
probeResults: z.array(z.strictObject({ probeId: text, result: z.enum(['pass','fail','skip']) })),
|
|
18
|
+
result: z.enum(['pass','fail']), evidenceRef: z.string().regex(/^sha256:[0-9a-f]{64}$/) });
|
|
19
|
+
|
|
20
|
+
async function identityFor(client, orgId, actor, project, roles) {
|
|
21
|
+
const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
|
|
22
|
+
if (!identity || identity.revoked_at != null || !storedScopeAllows(identity, project, roles)) reject('permission_denied', 403);
|
|
23
|
+
return identity;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function grantRecord(row) {
|
|
27
|
+
if (!row) reject('permission_denied', 403);
|
|
28
|
+
return VerifierGrantSchema.parse({ id: row.id, identityId: row.identity_id, project: row.project,
|
|
29
|
+
machine: row.machine, allowedDrillSpecIds: row.allowed_drill_spec_ids, expiresAtMs: Number(row.expires_at_ms),
|
|
30
|
+
grantedBy: row.granted_by, revokedAtMs: row.revoked_at_ms == null ? null : Number(row.revoked_at_ms) });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// The durable row holds a nonce hash. Plaintext exists only in the signed claim response and submission.
|
|
34
|
+
export function verificationJobProjection(row, nonce, grant) {
|
|
35
|
+
return { id: row.id, attemptId: row.attempt_id, artifactHash: row.artifact_hash, testedSha: row.tested_sha,
|
|
36
|
+
cardRevision: Number(row.card_revision), drillSpecId: row.drill_spec_id, probeIds: row.probe_ids,
|
|
37
|
+
registryHash: row.registry_hash, state: row.state === 'queued' ? 'queued' : ['passed','failed'].includes(row.state) ? 'complete' : 'claimed',
|
|
38
|
+
verifierGrantId: row.verifier_grant_id, nonce, expiresAtMs: row.row.expiresAtMs,
|
|
39
|
+
createdAtMs: Number(row.created_at_ms), lease: row.verifier_grant_id ? {
|
|
40
|
+
verifierPrincipal: grant.identityId, machine: grant.machine, grantId: grant.id,
|
|
41
|
+
leaseExpiresAtMs: Number(row.lease_expires_at_ms) } : null };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function createVerifier({ store, evidence, clock = Date.now, reserveVerification = null }) {
|
|
45
|
+
const getJob = async (client, orgId, id) => {
|
|
46
|
+
const job = (await client.query('SELECT * FROM dispatcher_verification_jobs WHERE org_id=$1 AND id=$2', [orgId, id])).rows[0];
|
|
47
|
+
if (!job) reject('job_missing', 404);
|
|
48
|
+
return job;
|
|
49
|
+
};
|
|
50
|
+
const getGrant = async (client, orgId, id) => {
|
|
51
|
+
const row = (await client.query('SELECT * FROM dispatcher_verifier_grants WHERE org_id=$1 AND id=$2', [orgId, id])).rows[0];
|
|
52
|
+
const grant = grantRecord(row);
|
|
53
|
+
if (grant.revokedAtMs !== null || grant.expiresAtMs <= clock()) reject('permission_denied', 403);
|
|
54
|
+
return { row, grant };
|
|
55
|
+
};
|
|
56
|
+
const currentCard = async (client, orgId, attempt) => {
|
|
57
|
+
const record = (await client.query('SELECT revision,row FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
58
|
+
[orgId, attempt.project, attempt.card])).rows[0];
|
|
59
|
+
if (!record || Number(record.revision) !== attempt.cardRevision) reject('card_stale');
|
|
60
|
+
return record.row;
|
|
61
|
+
};
|
|
62
|
+
const service = {
|
|
63
|
+
async registerGrant(orgId, input, actor) {
|
|
64
|
+
const request = VerifierGrantSchema.omit({ grantedBy: true, revokedAtMs: true }).extend({ expectedRevision: integer, revoked: z.boolean() }).parse(input);
|
|
65
|
+
return store.locked(orgId, async client => {
|
|
66
|
+
await identityFor(client, orgId, actor, request.project, ['owner']);
|
|
67
|
+
await identityFor(client, orgId, { pubkey: request.identityId }, request.project, ['approver','owner']);
|
|
68
|
+
const producers = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2
|
|
69
|
+
AND row->'producerIdentityIds' ? $3`, [orgId, request.project, actor.pubkey])).rows;
|
|
70
|
+
if (actor.pubkey === request.identityId && producers.length) reject('permission_denied', 403);
|
|
71
|
+
const previous = (await client.query('SELECT * FROM dispatcher_verifier_grants WHERE org_id=$1 AND id=$2', [orgId, request.id])).rows[0];
|
|
72
|
+
if (Number(previous?.revision || 0) !== request.expectedRevision) reject('grant_stale');
|
|
73
|
+
if (previous && (previous.project !== request.project || previous.identity_id !== request.identityId || previous.machine !== request.machine)) reject('grant_stale');
|
|
74
|
+
if (!request.revoked && request.expiresAtMs <= clock()) reject('grant_expired');
|
|
75
|
+
const grant = VerifierGrantSchema.parse({ id: request.id, identityId: request.identityId, project: request.project,
|
|
76
|
+
machine: request.machine, allowedDrillSpecIds: request.allowedDrillSpecIds, expiresAtMs: request.expiresAtMs,
|
|
77
|
+
grantedBy: actor.pubkey, revokedAtMs: request.revoked ? clock() : null });
|
|
78
|
+
await client.query(`INSERT INTO dispatcher_verifier_grants VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
|
|
79
|
+
ON CONFLICT(org_id,id) DO UPDATE SET allowed_drill_spec_ids=EXCLUDED.allowed_drill_spec_ids,
|
|
80
|
+
expires_at_ms=EXCLUDED.expires_at_ms,revoked_at_ms=EXCLUDED.revoked_at_ms,revision=EXCLUDED.revision,row=EXCLUDED.row`,
|
|
81
|
+
[orgId, grant.id, grant.identityId, grant.project, grant.machine, JSON.stringify(grant.allowedDrillSpecIds),
|
|
82
|
+
grant.expiresAtMs, grant.grantedBy, grant.revokedAtMs, request.expectedRevision + 1, grant]);
|
|
83
|
+
if (previous) await client.query(`UPDATE dispatcher_verification_jobs SET state='stopping',nonce_hash=NULL,updated_at_ms=$3
|
|
84
|
+
WHERE org_id=$1 AND verifier_grant_id=$2 AND state='running'`, [orgId, grant.id, clock()]);
|
|
85
|
+
await store.audit(client, orgId, { action: request.revoked ? 'verifier-revoked' : 'verifier-registered',
|
|
86
|
+
actor: actor.pubkey, atMs: clock(), grantId: grant.id, revision: request.expectedRevision + 1 });
|
|
87
|
+
return { ...grant, revision: request.expectedRevision + 1 };
|
|
88
|
+
});
|
|
89
|
+
},
|
|
90
|
+
async enqueue(orgId, attemptId, input, actor) {
|
|
91
|
+
const request = VerifyRequestSchema.parse(input);
|
|
92
|
+
return store.locked(orgId, async client => {
|
|
93
|
+
const rows = await executionRows(client, orgId, attemptId);
|
|
94
|
+
await requireIdentity(client, orgId, actor, rows.attempt.project);
|
|
95
|
+
const route = `/dispatch/${attemptId}/verify`;
|
|
96
|
+
const hash = canonicalHash(request);
|
|
97
|
+
const previous = (await client.query('SELECT request_hash,response FROM dispatcher_idempotency WHERE org_id=$1 AND project=$2 AND route=$3 AND key=$4',
|
|
98
|
+
[orgId, rows.attempt.project, route, request.idempotencyKey])).rows[0];
|
|
99
|
+
if (previous) {
|
|
100
|
+
if (previous.request_hash !== hash) reject('idempotency_conflict');
|
|
101
|
+
return { ...previous.response, replayed: true };
|
|
102
|
+
}
|
|
103
|
+
const card = await currentCard(client, orgId, rows.attempt);
|
|
104
|
+
if (card.drillSpecId !== request.drillSpecId || card.featureRegistryHash !== request.featureRegistryHash) reject('card_stale');
|
|
105
|
+
const spec = await evidence(client, orgId, 'drill', card.drillSpecId);
|
|
106
|
+
if (spec.project !== card.project || spec.registryHash !== card.featureRegistryHash) reject('drill_stale');
|
|
107
|
+
const created = createVerificationJob({ attempt: rows.attempt, request, nowMs: clock(), probeIds: spec.probeIds });
|
|
108
|
+
if (!created.ok) reject(created.code, created.status);
|
|
109
|
+
const active = (await client.query(`SELECT id FROM dispatcher_verification_jobs WHERE org_id=$1 AND attempt_id=$2
|
|
110
|
+
AND artifact_hash=$3 AND card_revision=$4 AND drill_spec_id=$5 AND registry_hash=$6
|
|
111
|
+
AND state IN ('queued','running','stopping','reconciling')`,
|
|
112
|
+
[orgId, attemptId, request.artifactHash, request.cardRevision, request.drillSpecId, request.featureRegistryHash])).rows[0];
|
|
113
|
+
const id = active?.id || `job-${randomUUID()}`;
|
|
114
|
+
if (!active) await client.query(`INSERT INTO dispatcher_verification_jobs
|
|
115
|
+
(org_id,id,project,attempt_id,artifact_hash,tested_sha,card_revision,drill_spec_id,registry_hash,probe_ids,state,created_at_ms,updated_at_ms,row)
|
|
116
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'queued',$11,$11,$12)`,
|
|
117
|
+
[orgId, id, card.project, attemptId, request.artifactHash, created.job.testedSha, request.cardRevision,
|
|
118
|
+
request.drillSpecId, request.featureRegistryHash, JSON.stringify(spec.probeIds), clock(),
|
|
119
|
+
{ expiresAtMs: created.job.expiresAtMs, specHash: canonicalHash(spec) }]);
|
|
120
|
+
const response = { schemaVersion: 1, jobId: id, state: 'queued', replayed: false };
|
|
121
|
+
await client.query('INSERT INTO dispatcher_idempotency VALUES($1,$2,$3,$4,$5,$6,$7)',
|
|
122
|
+
[orgId, card.project, route, request.idempotencyKey, hash, response, clock()]);
|
|
123
|
+
await store.audit(client, orgId, { action: 'verification-queued', actor: actor.pubkey, atMs: clock(), jobId: id, attemptId });
|
|
124
|
+
return response;
|
|
125
|
+
});
|
|
126
|
+
},
|
|
127
|
+
async claim(orgId, input, actor) {
|
|
128
|
+
const request = ClaimRequestSchema.parse(input);
|
|
129
|
+
return store.locked(orgId, async client => {
|
|
130
|
+
const { row: grantRow, grant } = await getGrant(client, orgId, request.grantId);
|
|
131
|
+
const identity = await identityFor(client, orgId, actor, grant.project, ['approver','owner']);
|
|
132
|
+
if (actor.pubkey !== grant.identityId || request.machine !== grant.machine) reject('permission_denied', 403);
|
|
133
|
+
const jobs = (await client.query(`SELECT * FROM dispatcher_verification_jobs WHERE org_id=$1 AND project=$2
|
|
134
|
+
AND state='queued' AND drill_spec_id=ANY($3::text[]) ORDER BY created_at_ms,id FOR UPDATE SKIP LOCKED`,
|
|
135
|
+
[orgId, grant.project, grant.allowedDrillSpecIds])).rows;
|
|
136
|
+
for (const job of jobs) {
|
|
137
|
+
const { attempt } = await executionRows(client, orgId, job.attempt_id);
|
|
138
|
+
if (attempt.producerIdentityIds.includes(actor.pubkey)) continue;
|
|
139
|
+
await currentCard(client, orgId, attempt);
|
|
140
|
+
const spec = await evidence(client, orgId, 'drill', job.drill_spec_id);
|
|
141
|
+
if (spec.machine !== grant.machine || canonicalHash(spec) !== job.row.specHash
|
|
142
|
+
|| spec.registryHash !== job.registry_hash || job.row.expiresAtMs <= clock()) continue;
|
|
143
|
+
if (spec.kind === 'manual') {
|
|
144
|
+
if (identity.kind !== 'human' || request.capabilityReportHash !== canonicalHash(spec)) reject('permission_denied', 403);
|
|
145
|
+
} else {
|
|
146
|
+
if (!reserveVerification) reject('verification_admission_unavailable', 503);
|
|
147
|
+
await reserveVerification(client, { orgId, job, spec, grant, capabilityReportHash: request.capabilityReportHash });
|
|
148
|
+
}
|
|
149
|
+
const nonce = randomBytes(32).toString('hex');
|
|
150
|
+
const projected = verificationJobProjection(job, null, grant);
|
|
151
|
+
const claimed = claimVerificationJob({ job: projected, grant, verifier: { principalId: actor.pubkey },
|
|
152
|
+
machine: request.machine, nowMs: clock(), nonce });
|
|
153
|
+
if (!claimed.ok) reject(claimed.code, claimed.status);
|
|
154
|
+
await client.query(`UPDATE dispatcher_verification_jobs SET state='running',verifier_grant_id=$3,grant_revision=$4,
|
|
155
|
+
nonce_hash=$5,claim_sequence=1,lease_expires_at_ms=$6,last_beat_ms=$7,updated_at_ms=$7 WHERE org_id=$1 AND id=$2`,
|
|
156
|
+
[orgId, job.id, grant.id, Number(grantRow.revision), canonicalHash(nonce), clock() + JOB_LEASE_MS, clock()]);
|
|
157
|
+
await store.audit(client, orgId, { action: 'verification-claimed', actor: actor.pubkey, atMs: clock(), jobId: job.id, grantId: grant.id });
|
|
158
|
+
return { schemaVersion: 1, job: claimed.job, spec };
|
|
159
|
+
}
|
|
160
|
+
return { schemaVersion: 1, job: null };
|
|
161
|
+
});
|
|
162
|
+
},
|
|
163
|
+
async heartbeat(orgId, jobId, input, actor) {
|
|
164
|
+
const request = BeatSchema.parse(input);
|
|
165
|
+
return store.locked(orgId, async client => {
|
|
166
|
+
const job = await getJob(client, orgId, jobId);
|
|
167
|
+
const { row, grant } = await getGrant(client, orgId, job.verifier_grant_id);
|
|
168
|
+
await identityFor(client, orgId, actor, job.project, ['approver','owner']);
|
|
169
|
+
if (grant.identityId !== actor.pubkey) reject('permission_denied', 403);
|
|
170
|
+
if (job.state !== 'running' || Number(row.revision) !== Number(job.grant_revision)
|
|
171
|
+
|| job.nonce_hash !== canonicalHash(request.jobNonce) || Number(job.lease_expires_at_ms) <= clock()) reject('job_stale');
|
|
172
|
+
if (job.process_identity && canonicalJson(job.process_identity) !== canonicalJson(request.processIdentity)) reject('job_stale');
|
|
173
|
+
if (request.sequence <= Number(job.claim_sequence)) return { renewed: false };
|
|
174
|
+
const expiresAtMs = Math.min(clock() + JOB_LEASE_MS, job.row.expiresAtMs);
|
|
175
|
+
await client.query(`UPDATE dispatcher_verification_jobs SET claim_sequence=$3,last_beat_ms=$4,lease_expires_at_ms=$5,
|
|
176
|
+
process_identity=$6,updated_at_ms=$4 WHERE org_id=$1 AND id=$2`,
|
|
177
|
+
[orgId, jobId, request.sequence, clock(), expiresAtMs, request.processIdentity]);
|
|
178
|
+
return { renewed: true, expiresAtMs };
|
|
179
|
+
});
|
|
180
|
+
},
|
|
181
|
+
async accept(orgId, attemptId, input, actor) {
|
|
182
|
+
const submission = SubmissionSchema.parse(input);
|
|
183
|
+
const outcome = await store.locked(orgId, async client => {
|
|
184
|
+
const rows = await executionRows(client, orgId, attemptId);
|
|
185
|
+
await identityFor(client, orgId, actor, rows.attempt.project, ['approver','owner']);
|
|
186
|
+
if (rows.attempt.producerIdentityIds.includes(actor.pubkey)) reject('permission_denied', 403);
|
|
187
|
+
const job = await getJob(client, orgId, submission.jobId);
|
|
188
|
+
const { row: grantRow, grant } = await getGrant(client, orgId, job.verifier_grant_id);
|
|
189
|
+
if (grant.identityId !== actor.pubkey || job.project !== rows.attempt.project) reject('permission_denied', 403);
|
|
190
|
+
const card = await currentCard(client, orgId, rows.attempt);
|
|
191
|
+
const spec = await evidence(client, orgId, 'drill', job.drill_spec_id);
|
|
192
|
+
if (job.attempt_id !== attemptId || Number(job.grant_revision) !== Number(grantRow.revision)
|
|
193
|
+
|| job.nonce_hash !== canonicalHash(submission.jobNonce) || card.featureRegistryHash !== job.registry_hash
|
|
194
|
+
|| canonicalHash(spec) !== job.row.specHash || card.drillSpecId !== job.drill_spec_id) reject('job_stale');
|
|
195
|
+
const resultHash = canonicalHash(submission);
|
|
196
|
+
if (job.result_hash) {
|
|
197
|
+
if (job.result_hash !== resultHash) {
|
|
198
|
+
await store.audit(client, orgId, { action: 'acceptance-conflict', actor: actor.pubkey, atMs: clock(), jobId: job.id, resultHash });
|
|
199
|
+
return { error: 'acceptance_conflict' };
|
|
200
|
+
}
|
|
201
|
+
const acceptance = (await client.query('SELECT row FROM dispatcher_acceptances WHERE org_id=$1 AND id=$2', [orgId, job.acceptance_id])).rows[0]?.row;
|
|
202
|
+
return { schemaVersion: 1, acceptance, replayed: true };
|
|
203
|
+
}
|
|
204
|
+
if (job.state !== 'running') reject('job_stale');
|
|
205
|
+
const acceptances = (await client.query('SELECT row FROM dispatcher_acceptances WHERE org_id=$1 AND attempt_id=$2', [orgId, attemptId])).rows.map(r => r.row);
|
|
206
|
+
const result = adjudicateAcceptance({ submission, verifier: { principalId: actor.pubkey, project: rows.attempt.project },
|
|
207
|
+
attempt: rows.attempt, job: verificationJobProjection(job, submission.jobNonce, grant), grant, acceptances, nowMs: clock() });
|
|
208
|
+
for (const event of result.events) await store.audit(client, orgId, event);
|
|
209
|
+
if (!result.ok) return { error: result.code, status: result.status };
|
|
210
|
+
const acceptance = result.acceptance;
|
|
211
|
+
await client.query('INSERT INTO dispatcher_acceptances(org_id,id,attempt_id,row,job_id) VALUES($1,$2,$3,$4,$5)',
|
|
212
|
+
[orgId, acceptance.id, attemptId, acceptance, job.id]);
|
|
213
|
+
await client.query(`UPDATE dispatcher_verification_jobs SET state=$3,result_hash=$4,acceptance_id=$5,updated_at_ms=$6
|
|
214
|
+
WHERE org_id=$1 AND id=$2`, [orgId, job.id, acceptance.result === 'pass' ? 'passed' : 'failed', resultHash, acceptance.id, clock()]);
|
|
215
|
+
rows.attempt.acceptance = acceptance;
|
|
216
|
+
if (rows.generation.usageSettled && rows.generation.stopProof && ['reconciled','released'].includes(rows.lease.state) && !rows.lease.claims.length) {
|
|
217
|
+
rows.attempt.state = acceptance.result === 'pass' ? 'accepted' : 'failed';
|
|
218
|
+
rows.attempt.endedAtMs = clock();
|
|
219
|
+
await saveExecution(client, orgId, rows);
|
|
220
|
+
} else {
|
|
221
|
+
await fenceExecution(client, orgId, rows, 'verification-complete', clock());
|
|
222
|
+
}
|
|
223
|
+
return { schemaVersion: 1, acceptance, replayed: false };
|
|
224
|
+
});
|
|
225
|
+
if (outcome.error) reject(outcome.error, outcome.status || 409);
|
|
226
|
+
return outcome;
|
|
227
|
+
},
|
|
228
|
+
async reconcile(orgId) {
|
|
229
|
+
return store.locked(orgId, async client => {
|
|
230
|
+
await client.query(`UPDATE dispatcher_verification_jobs SET state='stopping',nonce_hash=NULL,updated_at_ms=$2
|
|
231
|
+
WHERE org_id=$1 AND state='running' AND lease_expires_at_ms<=$2`, [orgId, clock()]);
|
|
232
|
+
const attempts = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND row->'acceptance' <> 'null'::jsonb
|
|
233
|
+
AND state NOT IN ('accepted','failed','expired')`, [orgId])).rows;
|
|
234
|
+
for (const { id } of attempts) {
|
|
235
|
+
const rows = await executionRows(client, orgId, id);
|
|
236
|
+
if (!rows.attempt.acceptance || !rows.generation.usageSettled || !rows.generation.stopProof
|
|
237
|
+
|| !['reconciled','released'].includes(rows.lease.state) || rows.lease.claims.length) continue;
|
|
238
|
+
rows.attempt.state = rows.attempt.acceptance.result === 'pass' ? 'accepted' : 'failed';
|
|
239
|
+
rows.attempt.endedAtMs = clock();
|
|
240
|
+
await saveExecution(client, orgId, rows);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
return service;
|
|
246
|
+
}
|
package/lib/docker-janitor.mjs
CHANGED
|
@@ -9,24 +9,26 @@ import { homedir } from "node:os";
|
|
|
9
9
|
const dockerExec = (args) =>
|
|
10
10
|
spawnSync("docker", args, { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 8000 });
|
|
11
11
|
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
export const SEAT_LABEL = "com.trantor.seat";
|
|
13
|
+
|
|
14
|
+
// null = docker absent or the daemon errored (the caller skips silently, by contract);
|
|
15
|
+
// [] = docker up, nothing running. The seat label makes concurrent turns distinguishable.
|
|
14
16
|
export function listContainers(exec = dockerExec) {
|
|
15
17
|
let r;
|
|
16
|
-
try { r = exec(["ps", "--format",
|
|
18
|
+
try { r = exec(["ps", "--format", `{{.ID}}\t{{.Names}}\t{{.Label "${SEAT_LABEL}"}}`]); } catch { return null; }
|
|
17
19
|
if (!r || r.error || r.status !== 0) return null;
|
|
18
20
|
return String(r.stdout || "").split("\n").map(l => l.trim()).filter(Boolean).map(l => {
|
|
19
|
-
const
|
|
20
|
-
return
|
|
21
|
+
const [id, name = id, seat = ""] = l.split("\t");
|
|
22
|
+
return { id, name, seat };
|
|
21
23
|
});
|
|
22
24
|
}
|
|
23
25
|
|
|
24
|
-
// Containers present in `after` that were not in `before`, by id.
|
|
25
|
-
//
|
|
26
|
-
export function newContainers(before, after) {
|
|
26
|
+
// Containers present in `after` that were not in `before`, by id. With an owner, only its label
|
|
27
|
+
// qualifies. A null snapshot diffs to nothing — we never accuse a turn we could not observe.
|
|
28
|
+
export function newContainers(before, after, owner = "") {
|
|
27
29
|
if (!Array.isArray(before) || !Array.isArray(after)) return [];
|
|
28
30
|
const seen = new Set(before.map(c => c.id));
|
|
29
|
-
return after.filter(c => !seen.has(c.id));
|
|
31
|
+
return after.filter(c => !seen.has(c.id) && (!owner || c.seat === owner));
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
// One state file per seat, so a card close, a park or `trantor down <seat>` can still stop what
|
|
@@ -85,17 +87,25 @@ export function stopContainers({ exec = dockerExec, containers } = {}) {
|
|
|
85
87
|
return { unavailable: false, stopped, failed };
|
|
86
88
|
}
|
|
87
89
|
|
|
88
|
-
// Stop
|
|
89
|
-
//
|
|
90
|
-
export function sweep({ path, exec = dockerExec, card } = {}) {
|
|
90
|
+
// Stop records for one card (or every card when card is undefined), limited to the owner's live
|
|
91
|
+
// label when supplied. Forget stops and foreign misattributions; retain failures for the next sweep.
|
|
92
|
+
export function sweep({ path, exec = dockerExec, card, owner = "" } = {}) {
|
|
91
93
|
const state = loadContainers(path);
|
|
92
94
|
const keys = card === undefined ? Object.keys(state.cards) : [String(card)];
|
|
93
|
-
|
|
95
|
+
let targets = keys.flatMap(k => (state.cards[k] || []));
|
|
94
96
|
if (!targets.length) return { skipped: false, stopped: [], failed: [] };
|
|
97
|
+
const foreign = new Set();
|
|
98
|
+
if (owner) {
|
|
99
|
+
const running = listContainers(exec);
|
|
100
|
+
if (!Array.isArray(running)) return { skipped: true, stopped: [], failed: [] };
|
|
101
|
+
const byId = new Map(running.map(c => [c.id, c]));
|
|
102
|
+
for (const c of targets) if (byId.get(c.id)?.seat && byId.get(c.id).seat !== owner) foreign.add(c.id);
|
|
103
|
+
targets = targets.filter(c => byId.get(c.id)?.seat === owner);
|
|
104
|
+
}
|
|
95
105
|
const r = stopContainers({ exec, containers: targets });
|
|
96
106
|
if (r.unavailable) return { skipped: true, stopped: [], failed: [] };
|
|
97
107
|
for (const k of keys) {
|
|
98
|
-
state.cards[k] = (state.cards[k] || []).filter(c => !r.stopped.includes(c.name || c.id));
|
|
108
|
+
state.cards[k] = (state.cards[k] || []).filter(c => !foreign.has(c.id) && !r.stopped.includes(c.name || c.id));
|
|
99
109
|
if (!state.cards[k].length) delete state.cards[k];
|
|
100
110
|
}
|
|
101
111
|
saveContainers(path, state);
|
package/lib/store-contract.mjs
CHANGED
|
@@ -178,6 +178,8 @@ export const KV_KEYS = ["verifyGates", "balances", "handoffLog", "aliases", "pha
|
|
|
178
178
|
export const STORE_API = Object.freeze({
|
|
179
179
|
init: "() -> Promise<void> // create schema if absent, apply migrations",
|
|
180
180
|
close: "() -> Promise<void>",
|
|
181
|
+
transaction: "(fn, {isolation='serializable'}?) -> Promise<any> // PG only; three attempts for 40001/40P01; database-only callback",
|
|
182
|
+
createDispatcherStore: "() -> DispatcherStore // PG only; bound transactional admission store",
|
|
181
183
|
|
|
182
184
|
appendEvent: "(orgId, evt) -> Promise<number> // returns event id; evt: {type,project,by,taskId?,payload}",
|
|
183
185
|
readEvents: "(orgId, {project,type,by,taskId,since,limit}) -> Promise<{events,cursor,latest}>",
|
|
@@ -211,3 +213,58 @@ export const DEFAULT_ORG = "local";
|
|
|
211
213
|
// Cross-writer change protocol: EVERY writer NOTIFYs this channel after a committed write with
|
|
212
214
|
// `{"src":"<writer-id>"}`; the hub LISTENs and reloads its projection on a foreign src.
|
|
213
215
|
export const CHANGE_CHANNEL = "trantor_changes";
|
|
216
|
+
|
|
217
|
+
export const DISPATCHER_INTEGRATION_SQL = `
|
|
218
|
+
CREATE TABLE IF NOT EXISTS dispatcher_authority_state (
|
|
219
|
+
org_id TEXT PRIMARY KEY, revision BIGINT NOT NULL DEFAULT 0,
|
|
220
|
+
policy_version TEXT, FOREIGN KEY(org_id,policy_version) REFERENCES dispatcher_policies(org_id,version)
|
|
221
|
+
);
|
|
222
|
+
CREATE TABLE IF NOT EXISTS dispatcher_evidence (
|
|
223
|
+
org_id TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, revision BIGINT NOT NULL CHECK(revision>0),
|
|
224
|
+
source TEXT NOT NULL, source_ref TEXT NOT NULL, observed_at_ms BIGINT NOT NULL,
|
|
225
|
+
expires_at_ms BIGINT NOT NULL, registered_by TEXT NOT NULL, registered_at_ms BIGINT NOT NULL,
|
|
226
|
+
hash TEXT NOT NULL, row JSONB NOT NULL, PRIMARY KEY(org_id,kind,id,revision),
|
|
227
|
+
FOREIGN KEY(org_id,registered_by) REFERENCES identities(org_id,pubkey),
|
|
228
|
+
CHECK(expires_at_ms>observed_at_ms)
|
|
229
|
+
);
|
|
230
|
+
CREATE TABLE IF NOT EXISTS dispatcher_collectors (
|
|
231
|
+
org_id TEXT NOT NULL, pubkey TEXT NOT NULL, machine TEXT NOT NULL,
|
|
232
|
+
registered_by TEXT NOT NULL, revoked_at_ms BIGINT,
|
|
233
|
+
PRIMARY KEY(org_id,pubkey), FOREIGN KEY(org_id,pubkey) REFERENCES identities(org_id,pubkey)
|
|
234
|
+
);
|
|
235
|
+
CREATE TABLE IF NOT EXISTS dispatcher_cards (
|
|
236
|
+
org_id TEXT NOT NULL, project TEXT NOT NULL, card BIGINT NOT NULL,
|
|
237
|
+
revision BIGINT NOT NULL CHECK(revision>=0), status TEXT NOT NULL,
|
|
238
|
+
ready_since_ms BIGINT, row JSONB NOT NULL,
|
|
239
|
+
PRIMARY KEY(org_id,project,card)
|
|
240
|
+
);
|
|
241
|
+
CREATE TABLE IF NOT EXISTS dispatcher_integration_migrations (
|
|
242
|
+
id TEXT PRIMARY KEY, completed_at_ms BIGINT NOT NULL
|
|
243
|
+
);
|
|
244
|
+
CREATE OR REPLACE FUNCTION dispatcher_card_fence() RETURNS trigger AS $$
|
|
245
|
+
DECLARE organization TEXT; card_id BIGINT;
|
|
246
|
+
BEGIN
|
|
247
|
+
organization := OLD.org_id;
|
|
248
|
+
card_id := OLD.id;
|
|
249
|
+
PERFORM pg_advisory_xact_lock(hashtextextended('dispatcher:' || organization,0));
|
|
250
|
+
IF current_setting('trantor.dispatcher_card_write',true) = 'on' THEN
|
|
251
|
+
IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
|
|
252
|
+
END IF;
|
|
253
|
+
IF EXISTS(SELECT 1 FROM dispatcher_cards WHERE org_id=organization AND card=card_id) THEN
|
|
254
|
+
IF TG_OP='DELETE' OR NEW IS DISTINCT FROM OLD THEN
|
|
255
|
+
RAISE EXCEPTION 'managed card requires dispatcher transaction' USING ERRCODE='40001';
|
|
256
|
+
END IF;
|
|
257
|
+
END IF;
|
|
258
|
+
IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
|
|
259
|
+
END;
|
|
260
|
+
$$ LANGUAGE plpgsql;
|
|
261
|
+
DO $$ BEGIN
|
|
262
|
+
IF to_regclass('tasks') IS NOT NULL THEN
|
|
263
|
+
DROP TRIGGER IF EXISTS dispatcher_card_fence ON tasks;
|
|
264
|
+
CREATE TRIGGER dispatcher_card_fence BEFORE UPDATE OR DELETE ON tasks
|
|
265
|
+
FOR EACH ROW EXECUTE FUNCTION dispatcher_card_fence();
|
|
266
|
+
END IF;
|
|
267
|
+
END $$;
|
|
268
|
+
INSERT INTO dispatcher_integration_migrations VALUES('dispatcher-b6-v1',
|
|
269
|
+
(extract(epoch from clock_timestamp())*1000)::bigint) ON CONFLICT(id) DO NOTHING;
|
|
270
|
+
`;
|
package/lib/store-pg.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// trantor Phase 1 Postgres store: implements the frozen STORE_API from ./store-contract.mjs as the durable
|
|
2
2
|
// backing when RELAY_STORE=pg. SAFETY: the typeof checks here decode untrusted jsonb rows at the boundary.
|
|
3
3
|
/* oxlint-disable anti-slop/no-runtime-typeof */
|
|
4
|
+
import { createDispatcherStore } from "./dispatcher/store.mjs";
|
|
5
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
4
6
|
import { SCHEMA_SQL, SCHEMA_VERSION, KV_KEYS, DEFAULT_ORG, CHANGE_CHANNEL } from "./store-contract.mjs";
|
|
5
7
|
|
|
6
8
|
const TURNS_SCHEMA_SQL = `
|
|
@@ -104,7 +106,7 @@ export function taskExtra(t = {}) {
|
|
|
104
106
|
return extra;
|
|
105
107
|
}
|
|
106
108
|
|
|
107
|
-
function taskFromRow(row) {
|
|
109
|
+
export function taskFromRow(row) {
|
|
108
110
|
const extra = row.extra && typeof row.extra === "object" ? row.extra : {};
|
|
109
111
|
return {
|
|
110
112
|
...extra,
|
|
@@ -244,6 +246,34 @@ function diffById(prevArr, nextArr, idOf) {
|
|
|
244
246
|
}
|
|
245
247
|
|
|
246
248
|
export class PgStore {
|
|
249
|
+
// Retried callbacks must contain only database work; external effects belong after commit.
|
|
250
|
+
async transaction(fn, { isolation = "serializable" } = {}) {
|
|
251
|
+
if (!["serializable", "repeatable read", "read committed"].includes(isolation)) {
|
|
252
|
+
throw new RangeError("unsupported transaction isolation");
|
|
253
|
+
}
|
|
254
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
255
|
+
const client = await this.pool.connect();
|
|
256
|
+
let discard;
|
|
257
|
+
try {
|
|
258
|
+
await client.query(`BEGIN ISOLATION LEVEL ${isolation.toUpperCase()}`);
|
|
259
|
+
const result = await fn(client);
|
|
260
|
+
await client.query("COMMIT");
|
|
261
|
+
return result;
|
|
262
|
+
} catch (error) {
|
|
263
|
+
try { await client.query("ROLLBACK"); }
|
|
264
|
+
catch (rollbackError) { discard = rollbackError; }
|
|
265
|
+
if (!["40001", "40P01"].includes(error.code) || attempt === 3) throw error;
|
|
266
|
+
} finally {
|
|
267
|
+
client.release(discard);
|
|
268
|
+
}
|
|
269
|
+
await delay((10 + Math.floor(Math.random() * 41)) * attempt);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
createDispatcherStore() {
|
|
274
|
+
return createDispatcherStore({ pool: this.pool, transaction: this.transaction.bind(this) });
|
|
275
|
+
}
|
|
276
|
+
|
|
247
277
|
constructor(options = {}) {
|
|
248
278
|
this.url = options.url || process.env.RELAY_DATABASE_URL || process.env.DATABASE_URL || "";
|
|
249
279
|
this.pool = options.pool || null;
|
|
@@ -371,7 +401,9 @@ export class PgStore {
|
|
|
371
401
|
}
|
|
372
402
|
|
|
373
403
|
async upsertTask(orgId, task) {
|
|
374
|
-
await this.
|
|
404
|
+
await this.transaction(async client => {
|
|
405
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`dispatcher:${orgId}`]);
|
|
406
|
+
await client.query(
|
|
375
407
|
`INSERT INTO tasks(id, org_id, project, title, status, assignee, source, difficulty, model, phase, cost_usd, deps, history, created, updated, extra)
|
|
376
408
|
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb,$13::jsonb,$14,$15,$16::jsonb)
|
|
377
409
|
ON CONFLICT(org_id, id) DO UPDATE SET
|
|
@@ -386,7 +418,8 @@ export class PgStore {
|
|
|
386
418
|
JSON.stringify(Array.isArray(task.history) ? task.history : []),
|
|
387
419
|
ms(task.ts || task.created, 0), ms(task.updated || task.ts, 0), JSON.stringify(taskExtra(task)),
|
|
388
420
|
],
|
|
389
|
-
|
|
421
|
+
);
|
|
422
|
+
});
|
|
390
423
|
}
|
|
391
424
|
|
|
392
425
|
async readTasks(orgId, filters = {}) {
|
|
@@ -530,6 +563,7 @@ export class PgStore {
|
|
|
530
563
|
const c = await this.pool.connect();
|
|
531
564
|
try {
|
|
532
565
|
await c.query("BEGIN");
|
|
566
|
+
await c.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`dispatcher:${orgId}`]);
|
|
533
567
|
await c.query("DELETE FROM tasks WHERE org_id=$1", [orgId]);
|
|
534
568
|
await c.query("DELETE FROM events WHERE org_id=$1", [orgId]);
|
|
535
569
|
await c.query("DELETE FROM messages WHERE org_id=$1", [orgId]);
|
|
@@ -666,6 +700,7 @@ export class PgStore {
|
|
|
666
700
|
const c = await this.pool.connect();
|
|
667
701
|
try {
|
|
668
702
|
await c.query("BEGIN");
|
|
703
|
+
await c.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [`dispatcher:${orgId}`]);
|
|
669
704
|
for (const raw of tasks.upserts) {
|
|
670
705
|
const t = stripNulDeep(raw);
|
|
671
706
|
await c.query(
|