trantor 0.18.146 → 0.18.148

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew-runner.mjs +25 -2
  8. package/bin/dispatch.mjs +78 -0
  9. package/bin/integrate.mjs +14 -2
  10. package/bin/review.mjs +35 -0
  11. package/hooks/sessionstart.mjs +4 -1
  12. package/hub/routes/capacity.mjs +30 -23
  13. package/hub/routes/dispatcher.mjs +97 -0
  14. package/hub/routes/insights.mjs +68 -4
  15. package/hub/routes/worktree-status.mjs +56 -0
  16. package/hub.mjs +2 -1
  17. package/kimi.plugin.json +1 -1
  18. package/lib/capacity.mjs +94 -16
  19. package/lib/dispatcher/acceptance.mjs +314 -0
  20. package/lib/dispatcher/accounts.mjs +442 -0
  21. package/lib/dispatcher/admission.mjs +719 -0
  22. package/lib/dispatcher/breakers.mjs +70 -0
  23. package/lib/dispatcher/executor.mjs +486 -0
  24. package/lib/dispatcher/forecast.mjs +391 -0
  25. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  26. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  27. package/lib/dispatcher/harness/contract.mjs +198 -0
  28. package/lib/dispatcher/harness/crew.mjs +463 -0
  29. package/lib/dispatcher/harness/publication.mjs +188 -0
  30. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  31. package/lib/dispatcher/planner.mjs +516 -0
  32. package/lib/dispatcher/policy.mjs +9 -0
  33. package/lib/dispatcher/preflight.mjs +247 -0
  34. package/lib/dispatcher/resources.mjs +44 -0
  35. package/lib/dispatcher/schemas.mjs +3 -1
  36. package/lib/dispatcher/spend.mjs +319 -0
  37. package/lib/dispatcher/store.mjs +207 -2
  38. package/lib/fitness.mjs +227 -41
  39. package/lib/review-gate.mjs +63 -0
  40. package/lib/telemetry-ship.mjs +8 -7
  41. package/lib/worktree-status.mjs +216 -0
  42. package/mcp.mjs +53 -7
  43. package/package.json +1 -1
@@ -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
+ }