trantor 0.18.146 → 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/advise.mjs +23 -7
- package/bin/capacity.mjs +18 -2
- package/bin/cli.mjs +6 -2
- package/bin/connect.mjs +10 -3
- package/bin/crew/state.mjs +1 -1
- package/bin/crew-runner.mjs +29 -4
- package/bin/dispatch.mjs +78 -0
- package/bin/docker-seat.mjs +33 -0
- package/bin/heavy-gate-shim/docker +2 -0
- package/bin/integrate.mjs +14 -2
- package/bin/migrate-dispatcher.mjs +50 -0
- package/bin/review.mjs +35 -0
- package/hooks/sessionstart.mjs +4 -1
- package/hub/auth.mjs +3 -3
- package/hub/routes/capacity.mjs +30 -23
- package/hub/routes/cards.mjs +13 -1
- package/hub/routes/dispatcher-operations.mjs +122 -0
- package/hub/routes/dispatcher.mjs +106 -0
- package/hub/routes/insights.mjs +68 -4
- package/hub/routes/worktree-status.mjs +56 -0
- package/hub/store.mjs +20 -0
- package/hub.mjs +17 -1
- package/kimi.plugin.json +1 -1
- package/lib/capacity.mjs +94 -16
- package/lib/dispatcher/acceptance.mjs +314 -0
- package/lib/dispatcher/accounts.mjs +442 -0
- package/lib/dispatcher/admission.mjs +731 -0
- package/lib/dispatcher/breakers.mjs +70 -0
- package/lib/dispatcher/executor.mjs +486 -0
- package/lib/dispatcher/forecast.mjs +391 -0
- package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
- package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
- package/lib/dispatcher/harness/contract.mjs +198 -0
- package/lib/dispatcher/harness/crew.mjs +463 -0
- package/lib/dispatcher/harness/publication.mjs +188 -0
- package/lib/dispatcher/migrate-attempts.mjs +51 -0
- package/lib/dispatcher/operations.mjs +401 -0
- package/lib/dispatcher/planner.mjs +516 -0
- package/lib/dispatcher/policy.mjs +9 -0
- package/lib/dispatcher/preflight.mjs +249 -0
- package/lib/dispatcher/resources.mjs +44 -0
- package/lib/dispatcher/schemas.mjs +3 -1
- package/lib/dispatcher/snapshot.mjs +72 -1
- package/lib/dispatcher/spend.mjs +319 -0
- package/lib/dispatcher/store.mjs +207 -2
- package/lib/dispatcher/verifier.mjs +246 -0
- package/lib/docker-janitor.mjs +24 -14
- package/lib/fitness.mjs +227 -41
- package/lib/review-gate.mjs +63 -0
- package/lib/store-contract.mjs +57 -0
- package/lib/store-pg.mjs +38 -3
- package/lib/telemetry-ship.mjs +8 -7
- package/lib/worktree-status.mjs +216 -0
- package/mcp.mjs +53 -7
- package/package.json +1 -1
package/lib/capacity.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// #14653: the pure views behind GET /capacity and `trantor capacity` — budgets (windows, resets,
|
|
2
2
|
// prepaid, merged across machine snapshots), burn rate from turn telemetry, seats with their last
|
|
3
|
-
// turn, machine rows joined with seat counts, and online-seat faults
|
|
4
|
-
//
|
|
3
|
+
// turn, machine rows joined with seat counts, and online-seat faults (#14662). #14671: the burn
|
|
4
|
+
// rate now carries crew USD spend from real receipts — slice 2 reported turns/tokens only.
|
|
5
5
|
|
|
6
6
|
// Unknown values stay null; ages ride along so a consumer can say HOW unknown ("12m old", "no
|
|
7
7
|
// beat"). Pure: a function over the hub's state and telemetry rows, so tests feed fixtures.
|
|
8
8
|
import { fmtReset, isLow, DEFAULT_LOW, DEFAULT_LOW_QUOTA_PCT } from "./balances.mjs";
|
|
9
|
+
import { crewSpend } from "./dispatcher/spend.mjs";
|
|
9
10
|
|
|
10
11
|
const GiB = 1024 ** 3;
|
|
11
12
|
const SUCCESS_OUTCOMES = new Set(["completed", "asked", "blocked"]);
|
|
@@ -65,9 +66,11 @@ export function budgetsView({ state, nowMs, thresholds = DEFAULT_LOW, quotaPct =
|
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
// Burn rate per trailing window (1h for "right now", 24h for the pace). Totals count every row
|
|
68
|
-
// (an aggregate); bySeat lists only seats the reader may see
|
|
69
|
-
//
|
|
70
|
-
|
|
69
|
+
// (an aggregate); bySeat lists only seats the reader may see. spendReceipts (#14671) carry the
|
|
70
|
+
// CREW's real USD outflow — one-shot and dispatcher receipts, never token-derived estimates;
|
|
71
|
+
// unknown receipts count, they never sum as zero.
|
|
72
|
+
export function burnView({ rows, nowMs, canSee = () => true, spendReceipts = [] }) {
|
|
73
|
+
const spend = crewSpend({ receipts: spendReceipts, nowMs });
|
|
71
74
|
const windows = {};
|
|
72
75
|
for (const [name, spanMs] of [["1h", 3600e3], ["24h", 86400e3]]) {
|
|
73
76
|
const sinceMs = nowMs - spanMs;
|
|
@@ -83,6 +86,19 @@ export function burnView({ rows, nowMs, canSee = () => true }) {
|
|
|
83
86
|
if (seat.lastTs == null || Number(r.ts) > seat.lastTs) seat.lastTs = Number(r.ts);
|
|
84
87
|
seats.set(key, seat);
|
|
85
88
|
}
|
|
89
|
+
for (const seat of (spend.windows[name] || {}).bySeat || []) {
|
|
90
|
+
const key = `${seat.persona}\u0000${seat.project}`;
|
|
91
|
+
const existing = seats.get(key);
|
|
92
|
+
if (existing) {
|
|
93
|
+
existing.spendUsdMicros = seat.spendUsdMicros;
|
|
94
|
+
existing.spendCalls = seat.calls;
|
|
95
|
+
} else {
|
|
96
|
+
seats.set(key, { persona: seat.persona, project: seat.project, agent: "",
|
|
97
|
+
turns: 0, tokens: 0, failures: 0, lastTs: null,
|
|
98
|
+
spendUsdMicros: seat.spendUsdMicros, spendCalls: seat.calls });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const spendWindow = spend.windows[name] || { spendUsdMicros: 0, billedUsdMicros: 0, estimatedUsdMicros: 0, unknownCount: 0 };
|
|
86
102
|
windows[name] = {
|
|
87
103
|
sinceMs,
|
|
88
104
|
hours,
|
|
@@ -90,7 +106,11 @@ export function burnView({ rows, nowMs, canSee = () => true }) {
|
|
|
90
106
|
tokens: inWindow.reduce((acc, r) => acc + (Number(r.tokens) || 0), 0),
|
|
91
107
|
turnsPerHour: inWindow.length ? +(inWindow.length / hours).toFixed(2) : 0,
|
|
92
108
|
tokensPerHour: inWindow.length ? +((inWindow.reduce((acc, r) => acc + (Number(r.tokens) || 0), 0)) / hours).toFixed(0) : 0,
|
|
93
|
-
|
|
109
|
+
spendUsdMicros: spendWindow.spendUsdMicros,
|
|
110
|
+
spendBilledUsdMicros: spendWindow.billedUsdMicros,
|
|
111
|
+
spendEstimatedUsdMicros: spendWindow.estimatedUsdMicros,
|
|
112
|
+
spendUnknownCount: spendWindow.unknownCount,
|
|
113
|
+
bySeat: [...seats.values()].filter((s) => canSee(s)).sort((a, b) => b.turns - a.turns || (b.spendUsdMicros || 0) - (a.spendUsdMicros || 0)),
|
|
94
114
|
};
|
|
95
115
|
}
|
|
96
116
|
return { windows };
|
|
@@ -144,19 +164,77 @@ export function seatsView({ peers, lastRows, messages = [], nowMs, onlineMs, stu
|
|
|
144
164
|
.sort((a, b) => (b.online - a.online) || (b.lastSeen - a.lastSeen) || a.session.localeCompare(b.session));
|
|
145
165
|
}
|
|
146
166
|
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const
|
|
167
|
+
// Machine rows for /capacity (#14702): the /machines/health beat registry joined with seat counts
|
|
168
|
+
// from presence, over every machine name the hub knows (beats, presence labels, balances hosts).
|
|
169
|
+
// The join key is lowercased: the same machine arrives as a runner's chosen label ("netcup") and
|
|
170
|
+
// as a balances host name ("MacBook-Pro-M1") and keeps ONE row under its best display name.
|
|
171
|
+
export function machinesView({ beats = [], peers = {}, nowMs, ttlMs, onlineMs, balanceMachines = [] }) {
|
|
172
|
+
const display = new Map();
|
|
173
|
+
const learn = (name) => {
|
|
174
|
+
const raw = String(name || "").trim();
|
|
175
|
+
if (!raw || raw.length > 60) return;
|
|
176
|
+
const key = raw.toLowerCase();
|
|
177
|
+
const cur = display.get(key);
|
|
178
|
+
if (cur == null || (cur === cur.toLowerCase() && raw !== raw.toLowerCase())) display.set(key, raw);
|
|
179
|
+
};
|
|
180
|
+
for (const h of beats) learn(h?.machine);
|
|
181
|
+
for (const [, p] of Object.entries(peers || {})) learn(p?.machine);
|
|
182
|
+
for (const m of balanceMachines) learn(m);
|
|
183
|
+
|
|
184
|
+
const hostOf = (session) => {
|
|
185
|
+
const s = String(session || "");
|
|
186
|
+
const i = s.indexOf(":");
|
|
187
|
+
return i > 0 ? s.slice(0, i) : "";
|
|
188
|
+
};
|
|
189
|
+
// An unlabeled session's "host:project" id (the convention touch() itself derives the project
|
|
190
|
+
// from) attributes it to a machine the hub already knows: that is how the operator's Mac lists,
|
|
191
|
+
// whose clients ship no valid lowercase label ("MacBook-Pro-M1" fails the label grammar, so
|
|
192
|
+
// presence carries nothing). A persona-prefixed crew session spawns no pseudo-machine row.
|
|
193
|
+
const machineOf = (session, p) => {
|
|
194
|
+
const label = String(p?.machine || "").trim();
|
|
195
|
+
if (label) return label;
|
|
196
|
+
const host = hostOf(session);
|
|
197
|
+
return host && display.has(host.toLowerCase()) ? host : "";
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
const seatsBy = new Map();
|
|
201
|
+
for (const [session, p] of Object.entries(peers || {})) {
|
|
202
|
+
if (!p?.lastSeen || p.lastSeen < nowMs - ttlMs) continue;
|
|
203
|
+
const name = machineOf(session, p);
|
|
204
|
+
if (!name) continue;
|
|
205
|
+
const key = name.toLowerCase();
|
|
206
|
+
const row = seatsBy.get(key) || { seats: 0, seatsOnline: 0, presenceTs: 0 };
|
|
155
207
|
row.seats += 1;
|
|
156
208
|
if (p.lastSeen > nowMs - onlineMs) row.seatsOnline += 1;
|
|
157
|
-
|
|
209
|
+
row.presenceTs = Math.max(row.presenceTs, p.lastSeen);
|
|
210
|
+
seatsBy.set(key, row);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const rows = [];
|
|
214
|
+
const seen = new Set();
|
|
215
|
+
for (const h of beats) {
|
|
216
|
+
const key = String(h?.machine || "").trim().toLowerCase();
|
|
217
|
+
if (!key || seen.has(key)) continue;
|
|
218
|
+
seen.add(key);
|
|
219
|
+
const counts = seatsBy.get(key);
|
|
220
|
+
rows.push({ ...h, machine: display.get(key) || h.machine,
|
|
221
|
+
seats: counts?.seats || 0, seatsOnline: counts?.seatsOnline || 0, heartbeat: true,
|
|
222
|
+
presenceAgeMs: counts ? Math.max(0, nowMs - counts.presenceTs) : null });
|
|
223
|
+
}
|
|
224
|
+
// Machines only presence knows (no runner heartbeat) still list, with null health and their seat
|
|
225
|
+
// count; a balances host nobody beats and nobody runs stays off — no beat and no seats says
|
|
226
|
+
// nothing worth a row.
|
|
227
|
+
for (const [key, counts] of seatsBy) {
|
|
228
|
+
if (seen.has(key)) continue;
|
|
229
|
+
rows.push({
|
|
230
|
+
machine: display.get(key) || key, cpuPct: null, memUsed: null, memTotal: null, cores: null,
|
|
231
|
+
memPressurePct: null, swapUsed: null, swapTotal: null, diskFree: null, diskTotal: null,
|
|
232
|
+
ts: null, ageMs: null, stale: true, heartbeat: false,
|
|
233
|
+
seats: counts.seats, seatsOnline: counts.seatsOnline,
|
|
234
|
+
presenceAgeMs: Math.max(0, nowMs - counts.presenceTs),
|
|
235
|
+
});
|
|
158
236
|
}
|
|
159
|
-
return
|
|
237
|
+
return rows.sort((a, b) => a.machine.localeCompare(b.machine));
|
|
160
238
|
}
|
|
161
239
|
|
|
162
240
|
const numberOrNull = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
// #14672 (B2): verified acceptance — docs/TDD-dispatcher.md §3.1. The pure trust chain an
|
|
2
|
+
// acceptance must survive before it may enable done or fitness: active verifier grant, leased
|
|
3
|
+
// job, nonce/artifact/revision freshness, independence from producing identities, probes passed.
|
|
4
|
+
// B6 supplies authenticated state; a producer's own report of verification never promotes. Pure.
|
|
5
|
+
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
import { AcceptanceSchema } from './schemas.mjs';
|
|
9
|
+
|
|
10
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
11
|
+
const text = z.string().min(1).max(8192);
|
|
12
|
+
const short = z.string().min(1).max(200);
|
|
13
|
+
|
|
14
|
+
export const JOB_LEASE_MS = 30 * 60_000;
|
|
15
|
+
export const JOB_TTL_MS = 24 * 3600_000;
|
|
16
|
+
|
|
17
|
+
// The acceptance submission of §3.1 `POST /dispatch/:id/acceptance`, exactly its named fields.
|
|
18
|
+
const SubmissionSchema = z.strictObject({
|
|
19
|
+
schemaVersion: z.literal(1),
|
|
20
|
+
jobId: short,
|
|
21
|
+
jobNonce: short,
|
|
22
|
+
cardRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
23
|
+
artifactHash: short,
|
|
24
|
+
testedSha: z.string().min(1).max(200).nullable(),
|
|
25
|
+
drillSpecId: short,
|
|
26
|
+
probeResults: z.array(z.strictObject({ probeId: short, result: z.enum(['pass', 'fail', 'skip']) })).max(100),
|
|
27
|
+
result: z.enum(['pass', 'fail']),
|
|
28
|
+
evidenceRef: text,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// A verification job as enqueued by §3.1 `POST /dispatch/:id/verify` and claimed through
|
|
32
|
+
// `/dispatcher/verification-jobs/claim`. The lease is the verifier's current exclusive hold.
|
|
33
|
+
const JobSchema = z.strictObject({
|
|
34
|
+
id: short,
|
|
35
|
+
attemptId: short,
|
|
36
|
+
artifactHash: short,
|
|
37
|
+
testedSha: z.string().min(1).max(200).nullable(),
|
|
38
|
+
cardRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
39
|
+
drillSpecId: short,
|
|
40
|
+
probeIds: z.array(short).max(100),
|
|
41
|
+
registryHash: short,
|
|
42
|
+
state: z.enum(['queued', 'claimed', 'complete', 'expired']),
|
|
43
|
+
verifierGrantId: z.string().min(1).max(200).nullable(),
|
|
44
|
+
nonce: z.string().min(1).max(200).nullable(),
|
|
45
|
+
expiresAtMs: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
46
|
+
idempotencyKey: short.optional(),
|
|
47
|
+
createdAtMs: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
|
|
48
|
+
lease: z.strictObject({
|
|
49
|
+
verifierPrincipal: short,
|
|
50
|
+
machine: short,
|
|
51
|
+
grantId: z.string().min(1).max(200).nullable(),
|
|
52
|
+
leaseExpiresAtMs: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
53
|
+
}).nullable(),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// A VerifierGrant (§3.1): owner-registered authority binding one identity, project, machine and
|
|
57
|
+
// drill-spec allowlist. An active explicit grant is required; project write/dispatch authority
|
|
58
|
+
// alone is insufficient and no new role rank is invented here.
|
|
59
|
+
export const VerifierGrantSchema = z.strictObject({
|
|
60
|
+
id: short,
|
|
61
|
+
identityId: short,
|
|
62
|
+
project: short,
|
|
63
|
+
machine: short,
|
|
64
|
+
allowedDrillSpecIds: z.array(short).max(100),
|
|
65
|
+
expiresAtMs: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
66
|
+
grantedBy: short,
|
|
67
|
+
revokedAtMs: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).nullable(),
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
export function validateAcceptanceRecord(record) {
|
|
71
|
+
const parsed = AcceptanceSchema.safeParse(record);
|
|
72
|
+
return parsed.success ? parsed.data : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function parseWith(schema, value) {
|
|
76
|
+
const parsed = schema.safeParse(value);
|
|
77
|
+
return parsed.success ? parsed.data : null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Grant authority state: an expired or revoked grant authorizes nothing (D21).
|
|
81
|
+
export function grantState(grant, nowMs) {
|
|
82
|
+
if (grant == null) return 'missing';
|
|
83
|
+
if (grant.revokedAtMs != null) return 'revoked';
|
|
84
|
+
if (Number(grant.expiresAtMs) <= nowMs) return 'expired';
|
|
85
|
+
return 'active';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// The deterministic Acceptance ID: the same committed result replays to the same ID, and a fresh
|
|
89
|
+
// verification job (the only path a conflicting result may take) yields a fresh ID.
|
|
90
|
+
export function acceptanceId({ attemptId, jobId, drillSpecId, artifactHash, testedSha, cardRevision, result }) {
|
|
91
|
+
const core = sha(`${attemptId}\u0000${jobId}\u0000${drillSpecId}\u0000${artifactHash}\u0000${String(testedSha)}\u0000${Number(cardRevision)}\u0000${result}`);
|
|
92
|
+
return `acc-${core.slice(0, 24)}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const outcome = (ok, status, code, reasons, extra = {}) => ({
|
|
96
|
+
ok, status, code, reasons: reasons.map(reason => ({ code: reason, resource: null, retryAtMs: null })),
|
|
97
|
+
idempotent: false, pending: false, acceptance: null, events: [], ...extra,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Adjudicate one signed acceptance submission (§3.1, D21) over hub-supplied authenticated state:
|
|
101
|
+
// verifier principal, executor attempt, leased job, grant and the attempt's committed
|
|
102
|
+
// acceptances. Producer/revoked reject 403; stale job/artifact/revision and conflicts 409 with a
|
|
103
|
+
// preserved audit event; exact duplicates replay idempotently; a skipped probe stays pending.
|
|
104
|
+
export function adjudicateAcceptance({ submission, verifier, attempt, job, grant, acceptances = [], nowMs }) {
|
|
105
|
+
const body = parseWith(SubmissionSchema, submission);
|
|
106
|
+
if (!body) return outcome(false, 422, 'schema_invalid', ['schema_invalid']);
|
|
107
|
+
if (verifier == null || !verifier.principalId || !verifier.project) {
|
|
108
|
+
return outcome(false, 403, 'permission_denied', ['verifier_unauthenticated']);
|
|
109
|
+
}
|
|
110
|
+
const parsedJob = parseWith(JobSchema, job);
|
|
111
|
+
if (!parsedJob) return outcome(false, 409, 'decision_stale', ['job_not_found']);
|
|
112
|
+
const producers = new Set(Array.isArray(attempt?.producerIdentityIds) ? attempt.producerIdentityIds.map(String) : []);
|
|
113
|
+
|
|
114
|
+
// 403 — authority: project scope, then independence, then the explicit grant.
|
|
115
|
+
if (String(attempt?.project || '') !== String(verifier.project)) {
|
|
116
|
+
return outcome(false, 403, 'permission_denied', ['wrong_project']);
|
|
117
|
+
}
|
|
118
|
+
if (producers.has(String(verifier.principalId))) {
|
|
119
|
+
// An identity in the producing set cannot submit acceptance even holding owner/approver scope.
|
|
120
|
+
return outcome(false, 403, 'permission_denied', ['producer_identity']);
|
|
121
|
+
}
|
|
122
|
+
const state = grantState(parseWith(VerifierGrantSchema, grant), nowMs);
|
|
123
|
+
if (state !== 'active') {
|
|
124
|
+
return outcome(false, 403, 'permission_denied', [`grant_${state}`]);
|
|
125
|
+
}
|
|
126
|
+
if (String(grant.identityId) !== String(verifier.principalId)) {
|
|
127
|
+
return outcome(false, 403, 'permission_denied', ['grant_identity_mismatch']);
|
|
128
|
+
}
|
|
129
|
+
if (String(grant.project) !== String(attempt.project)) {
|
|
130
|
+
return outcome(false, 403, 'permission_denied', ['wrong_project']);
|
|
131
|
+
}
|
|
132
|
+
if (!grant.allowedDrillSpecIds.includes(String(body.drillSpecId))) {
|
|
133
|
+
return outcome(false, 403, 'permission_denied', ['drill_spec_not_granted']);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Job ownership and host: the job must be currently leased by this verifier on its grant machine.
|
|
137
|
+
if (parsedJob.attemptId !== String(attempt?.id || '')) {
|
|
138
|
+
return outcome(false, 409, 'decision_stale', ['job_attempt_mismatch']);
|
|
139
|
+
}
|
|
140
|
+
if (parsedJob.lease == null || parsedJob.lease.verifierPrincipal !== String(verifier.principalId)) {
|
|
141
|
+
return outcome(false, 403, 'permission_denied', ['job_not_leased']);
|
|
142
|
+
}
|
|
143
|
+
if (parsedJob.lease.machine !== String(grant.machine)) {
|
|
144
|
+
return outcome(false, 403, 'permission_denied', ['host_not_granted']);
|
|
145
|
+
}
|
|
146
|
+
if (parsedJob.verifierGrantId != null && parsedJob.verifierGrantId !== String(grant.id)) {
|
|
147
|
+
return outcome(false, 403, 'permission_denied', ['job_grant_mismatch']);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// 409 — freshness: expired job/lease, rotated nonce, stale artifact or card revision.
|
|
151
|
+
if (Number(parsedJob.expiresAtMs) <= nowMs) {
|
|
152
|
+
return outcome(false, 409, 'decision_stale', ['job_expired']);
|
|
153
|
+
}
|
|
154
|
+
if (Number(parsedJob.lease.leaseExpiresAtMs) <= nowMs) {
|
|
155
|
+
return outcome(false, 409, 'decision_stale', ['job_lease_expired']);
|
|
156
|
+
}
|
|
157
|
+
if (String(body.jobNonce) !== String(parsedJob.nonce)) {
|
|
158
|
+
return outcome(false, 409, 'decision_stale', ['job_nonce_stale']);
|
|
159
|
+
}
|
|
160
|
+
if (String(body.jobId) !== String(parsedJob.id)) {
|
|
161
|
+
return outcome(false, 409, 'decision_stale', ['job_id_mismatch']);
|
|
162
|
+
}
|
|
163
|
+
if (String(body.artifactHash) !== String(parsedJob.artifactHash)) {
|
|
164
|
+
return outcome(false, 409, 'snapshot_stale', ['artifact_stale']);
|
|
165
|
+
}
|
|
166
|
+
const publishedHash = String(attempt?.artifact?.contentHash || '');
|
|
167
|
+
if (publishedHash === '' || publishedHash !== String(parsedJob.artifactHash)) {
|
|
168
|
+
// The published artifact is immutable: a job that no longer names it is stale, never re-badged.
|
|
169
|
+
return outcome(false, 409, 'snapshot_stale', ['artifact_mismatch']);
|
|
170
|
+
}
|
|
171
|
+
if (String(body.testedSha ?? '') !== String(parsedJob.testedSha ?? '')) {
|
|
172
|
+
return outcome(false, 409, 'snapshot_stale', ['tested_sha_stale']);
|
|
173
|
+
}
|
|
174
|
+
if (String(body.drillSpecId) !== String(parsedJob.drillSpecId)) {
|
|
175
|
+
return outcome(false, 409, 'decision_stale', ['drill_spec_mismatch']);
|
|
176
|
+
}
|
|
177
|
+
if (Number(body.cardRevision) !== Number(attempt?.cardRevision) || Number(parsedJob.cardRevision) !== Number(attempt?.cardRevision)) {
|
|
178
|
+
return outcome(false, 409, 'card_stale', ['card_revision_stale']);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Required feature probes must pass; a skip is pending, a failed probe forces a failed drill.
|
|
182
|
+
const probes = new Map(body.probeResults.map(probe => [String(probe.probeId), probe.result]));
|
|
183
|
+
for (const probeId of parsedJob.probeIds) {
|
|
184
|
+
const result = probes.get(String(probeId));
|
|
185
|
+
if (result === undefined || result === 'skip') {
|
|
186
|
+
return outcome(false, 409, 'decision_stale', ['probe_skipped'], { pending: true });
|
|
187
|
+
}
|
|
188
|
+
if (result === 'fail' && body.result === 'pass') {
|
|
189
|
+
return outcome(false, 409, 'decision_stale', ['probe_failed']);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const idempotencyKey = `${String(attempt.id)}\u0000${body.result}\u0000${body.artifactHash}\u0000${String(body.testedSha)}\u0000${Number(body.cardRevision)}\u0000${body.drillSpecId}\u0000${body.evidenceRef}\u0000${String(verifier.principalId)}`;
|
|
194
|
+
const valid = (acceptances || []).map(validateAcceptanceRecord).filter(Boolean);
|
|
195
|
+
const duplicate = valid.find(existing =>
|
|
196
|
+
existing.attemptId === String(attempt.id) && `${existing.attemptId}\u0000${existing.result}\u0000${existing.artifactHash}\u0000${String(existing.testedSha)}\u0000${Number(existing.cardRevision)}\u0000${existing.drill}\u0000${existing.evidenceRef}\u0000${existing.verifier}` === idempotencyKey);
|
|
197
|
+
if (duplicate) {
|
|
198
|
+
return { ok: true, status: 200, code: null, reasons: [], idempotent: true, pending: false,
|
|
199
|
+
acceptance: duplicate, enablesDone: duplicate.result === 'pass', events: [] };
|
|
200
|
+
}
|
|
201
|
+
// A conflicting result on an attempt that already carries a verdict is preserved as an audit
|
|
202
|
+
// event and rejected: verdicts never flip, disagreement is resolved by a rescue attempt (D9).
|
|
203
|
+
const conflicting = valid.filter(existing => existing.attemptId === String(attempt.id) && existing.result !== body.result);
|
|
204
|
+
const terminal = ['cancelled', 'expired'].includes(String(attempt?.state))
|
|
205
|
+
|| (String(attempt?.state) === 'failed' && body.result === 'pass');
|
|
206
|
+
if (conflicting.length || terminal) {
|
|
207
|
+
return outcome(false, 409, 'attempt_conflict', conflicting.length ? ['acceptance_conflict'] : ['attempt_terminal'], {
|
|
208
|
+
events: conflicting.map(existing => ({
|
|
209
|
+
id: `aud-${sha(`${existing.id}\u0000${parsedJob.id}\u0000${body.result}\u0000${nowMs}`).slice(0, 24)}`,
|
|
210
|
+
kind: 'acceptance_conflict', attemptId: String(attempt.id), jobId: String(parsedJob.id),
|
|
211
|
+
existingResult: existing.result, submittedResult: body.result, atMs: nowMs, preserved: true,
|
|
212
|
+
})),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const record = {
|
|
217
|
+
id: acceptanceId({ attemptId: String(attempt.id), jobId: String(parsedJob.id), drillSpecId: body.drillSpecId,
|
|
218
|
+
artifactHash: body.artifactHash, testedSha: body.testedSha, cardRevision: Number(body.cardRevision), result: body.result }),
|
|
219
|
+
verifier: String(verifier.principalId), cardRevision: Number(body.cardRevision), attemptId: String(attempt.id),
|
|
220
|
+
artifactHash: String(body.artifactHash), testedSha: body.testedSha === null ? null : String(body.testedSha),
|
|
221
|
+
drill: String(body.drillSpecId), result: body.result, evidenceRef: String(body.evidenceRef), atMs: Number(nowMs),
|
|
222
|
+
};
|
|
223
|
+
return {
|
|
224
|
+
ok: true, status: 200, code: null, reasons: [], idempotent: false, pending: false,
|
|
225
|
+
acceptance: record, enablesDone: record.result === 'pass',
|
|
226
|
+
events: [{ id: `aud-${sha(`${record.id}\u0000${nowMs}`).slice(0, 24)}`, kind: record.result === 'pass' ? 'acceptance_committed' : 'drill_failed',
|
|
227
|
+
attemptId: record.attemptId, jobId: String(parsedJob.id), atMs: Number(nowMs) }],
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Enqueue one verification job (§3.1 verify request): validates the immutable published artifact
|
|
232
|
+
// and current revision, derives the job so a repeat returns the same job, never starts a worker.
|
|
233
|
+
export function createVerificationJob({ attempt, request, jobs = [], nowMs, ttlMs = JOB_TTL_MS, probeIds = [] }) {
|
|
234
|
+
const parsed = parseWith(z.strictObject({
|
|
235
|
+
schemaVersion: z.literal(1), artifactHash: short, cardRevision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
236
|
+
drillSpecId: short, featureRegistryHash: short, idempotencyKey: short,
|
|
237
|
+
}), request);
|
|
238
|
+
if (!parsed) return { ok: false, status: 422, code: 'schema_invalid', reasons: ['schema_invalid'] };
|
|
239
|
+
const publishedHash = String(attempt?.artifact?.contentHash || '');
|
|
240
|
+
if (publishedHash === '') return { ok: false, status: 422, code: 'claims_invalid', reasons: ['artifact_not_published'] };
|
|
241
|
+
if (String(parsed.artifactHash) !== publishedHash) return { ok: false, status: 409, code: 'snapshot_stale', reasons: ['artifact_stale'] };
|
|
242
|
+
if (Number(parsed.cardRevision) !== Number(attempt?.cardRevision)) return { ok: false, status: 409, code: 'card_stale', reasons: ['card_revision_stale'] };
|
|
243
|
+
const id = `job-${sha(`${attempt.id}\u0000${parsed.artifactHash}\u0000${Number(parsed.cardRevision)}\u0000${parsed.drillSpecId}`).slice(0, 24)}`;
|
|
244
|
+
const existing = (jobs || []).find(candidate => candidate.id === id || candidate.idempotencyKey === parsed.idempotencyKey);
|
|
245
|
+
if (existing) return { ok: true, status: 200, job: existing, idempotent: true };
|
|
246
|
+
const job = {
|
|
247
|
+
id, idempotencyKey: parsed.idempotencyKey, attemptId: String(attempt.id),
|
|
248
|
+
artifactHash: String(parsed.artifactHash), testedSha: attempt?.artifact?.commitSha == null ? null : String(attempt.artifact.commitSha),
|
|
249
|
+
cardRevision: Number(parsed.cardRevision), drillSpecId: String(parsed.drillSpecId),
|
|
250
|
+
probeIds: (Array.isArray(probeIds) ? probeIds : []).map(String),
|
|
251
|
+
registryHash: String(parsed.featureRegistryHash), state: 'queued', verifierGrantId: null, nonce: null,
|
|
252
|
+
expiresAtMs: Number(nowMs) + Number(ttlMs), createdAtMs: Number(nowMs), lease: null,
|
|
253
|
+
};
|
|
254
|
+
return { ok: true, status: 202, job, idempotent: false };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Claim a queued job for one verifier (§3.1 claim endpoint): installs the 30-minute lease and
|
|
258
|
+
// the nonce; re-claiming rotates the nonce so an earlier holder's submission is stale (D21).
|
|
259
|
+
export function claimVerificationJob({ job, grant, verifier, machine, nowMs, nonce, leaseMs = JOB_LEASE_MS }) {
|
|
260
|
+
const parsed = parseWith(JobSchema, job);
|
|
261
|
+
const state = grantState(parseWith(VerifierGrantSchema, grant), nowMs);
|
|
262
|
+
if (state !== 'active') {
|
|
263
|
+
return { ok: false, status: 403, code: 'permission_denied', reasons: [`grant_${state}`] };
|
|
264
|
+
}
|
|
265
|
+
if (!parsed) return { ok: false, status: 409, code: 'decision_stale', reasons: ['job_not_found'] };
|
|
266
|
+
if (String(grant.identityId) !== String(verifier?.principalId)) {
|
|
267
|
+
return { ok: false, status: 403, code: 'permission_denied', reasons: ['grant_identity_mismatch'] };
|
|
268
|
+
}
|
|
269
|
+
if (String(grant.machine) !== String(machine)) {
|
|
270
|
+
return { ok: false, status: 403, code: 'permission_denied', reasons: ['host_not_granted'] };
|
|
271
|
+
}
|
|
272
|
+
if (Number(parsed.expiresAtMs) <= nowMs) return { ok: false, status: 409, code: 'decision_stale', reasons: ['job_expired'] };
|
|
273
|
+
if (parsed.state === 'complete') return { ok: false, status: 409, code: 'decision_stale', reasons: ['job_complete'] };
|
|
274
|
+
if (parsed.lease != null && Number(parsed.lease.leaseExpiresAtMs) > nowMs
|
|
275
|
+
&& String(parsed.lease.verifierPrincipal) !== String(verifier?.principalId)) {
|
|
276
|
+
return { ok: false, status: 409, code: 'decision_stale', reasons: ['job_leased'] };
|
|
277
|
+
}
|
|
278
|
+
const rotated = String(nonce || `n-${sha(`${parsed.id}\u0000${nowMs}`).slice(0, 16)}`);
|
|
279
|
+
return {
|
|
280
|
+
ok: true, job: {
|
|
281
|
+
...parsed, state: 'claimed', verifierGrantId: String(grant.id), nonce: rotated,
|
|
282
|
+
lease: { verifierPrincipal: String(verifier.principalId), machine: String(machine),
|
|
283
|
+
grantId: String(grant.id), leaseExpiresAtMs: Number(nowMs) + Number(leaseMs) },
|
|
284
|
+
},
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Read-side verification classification for projections (fitness, /telemetry/attempts): an
|
|
289
|
+
// acceptance that is unbound, artifact-mismatched or producer-forged is rejected and the attempt
|
|
290
|
+
// stays pending — a forged acceptance never counts (D21).
|
|
291
|
+
export function classifyAttemptVerification(attempt) {
|
|
292
|
+
if (attempt == null) return { status: 'legacy', acceptance: null, rejected: [] };
|
|
293
|
+
const linked = attempt.executionAttemptId != null
|
|
294
|
+
|| (Array.isArray(attempt.producerIdentityIds) && attempt.producerIdentityIds.length > 0);
|
|
295
|
+
const baseline = linked ? 'pending' : 'legacy';
|
|
296
|
+
if (attempt.acceptance == null) return { status: baseline, acceptance: null, rejected: [] };
|
|
297
|
+
const record = validateAcceptanceRecord(attempt.acceptance);
|
|
298
|
+
if (!record) return { status: baseline, acceptance: null, rejected: [{ acceptance: attempt.acceptance, reason: 'acceptance_malformed' }] };
|
|
299
|
+
const bound = record.attemptId === String(attempt.executionAttemptId || attempt.id);
|
|
300
|
+
const revisionOk = attempt.cardRevision === undefined || Number(attempt.cardRevision) === Number(record.cardRevision);
|
|
301
|
+
const producers = new Set([
|
|
302
|
+
...(Array.isArray(attempt.producerIdentityIds) ? attempt.producerIdentityIds.map(String) : []),
|
|
303
|
+
...(attempt.seat ? [String(attempt.seat)] : []),
|
|
304
|
+
]);
|
|
305
|
+
const independent = record.verifier !== '' && !producers.has(record.verifier);
|
|
306
|
+
const declaredHash = String(attempt.artifactHash || attempt.contentHash || attempt.commit || '');
|
|
307
|
+
const artifactOk = declaredHash === '' || declaredHash === record.artifactHash;
|
|
308
|
+
if (!bound || !revisionOk || !independent || !artifactOk) {
|
|
309
|
+
const reason = !bound ? 'acceptance_unbound' : !revisionOk ? 'acceptance_revision_stale'
|
|
310
|
+
: !independent ? 'acceptance_producer_forged' : 'acceptance_artifact_mismatch';
|
|
311
|
+
return { status: baseline, acceptance: null, rejected: [{ acceptance: record, reason }] };
|
|
312
|
+
}
|
|
313
|
+
return { status: record.result === 'pass' ? 'accepted' : 'failed', acceptance: record, rejected: [] };
|
|
314
|
+
}
|