trantor 0.18.148 → 0.18.152

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 (44) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +11 -8
  4. package/bin/cli.mjs +1 -1
  5. package/bin/connect.mjs +10 -1
  6. package/bin/crew/state.mjs +1 -1
  7. package/bin/crew-runner.mjs +9 -6
  8. package/bin/docker-seat.mjs +33 -0
  9. package/bin/heavy-gate-shim/docker +2 -0
  10. package/bin/integrate.mjs +38 -9
  11. package/bin/migrate-dispatcher.mjs +50 -0
  12. package/bin/turn-watchdog.mjs +15 -1
  13. package/deploy/restart-hub.sh +2 -0
  14. package/docs/FEATURES.md +4 -1
  15. package/hooks/sessionstart.mjs +6 -1
  16. package/hub/auth.mjs +8 -3
  17. package/hub/routes/cards.mjs +13 -1
  18. package/hub/routes/dispatcher-operations.mjs +134 -0
  19. package/hub/routes/dispatcher.mjs +18 -9
  20. package/hub/routes/git-policy.mjs +35 -0
  21. package/hub/startup-config.mjs +14 -0
  22. package/hub/store.mjs +49 -0
  23. package/hub.mjs +19 -2
  24. package/kimi.plugin.json +1 -1
  25. package/lib/canary/canary.mjs +2 -0
  26. package/lib/canary/probes.mjs +62 -0
  27. package/lib/dispatcher/admission.mjs +16 -3
  28. package/lib/dispatcher/board-bridge.mjs +82 -0
  29. package/lib/dispatcher/evidence-bridge.mjs +283 -0
  30. package/lib/dispatcher/operations.mjs +527 -0
  31. package/lib/dispatcher/planner.mjs +4 -2
  32. package/lib/dispatcher/preflight.mjs +44 -7
  33. package/lib/dispatcher/rollout.mjs +357 -0
  34. package/lib/dispatcher/schemas.mjs +1 -0
  35. package/lib/dispatcher/snapshot.mjs +76 -1
  36. package/lib/dispatcher/store.mjs +15 -0
  37. package/lib/dispatcher/verifier.mjs +246 -0
  38. package/lib/docker-janitor.mjs +24 -14
  39. package/lib/git-guard.mjs +181 -0
  40. package/lib/integrate.mjs +10 -2
  41. package/lib/store-contract.mjs +63 -0
  42. package/lib/store-pg.mjs +38 -3
  43. package/mcp.mjs +4 -5
  44. package/package.json +3 -3
@@ -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
+ }
@@ -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
- // `docker ps --format '{{.ID}} {{.Names}}'` → [{id, name}]. null = docker absent or the daemon
13
- // errored (the caller skips silently, by contract); [] = docker up, nothing running.
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", "{{.ID}} {{.Names}}"]); } catch { return null; }
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 sp = l.indexOf(" ");
20
- return sp < 0 ? { id: l, name: l } : { id: l.slice(0, sp), name: l.slice(sp + 1).trim() };
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. A null snapshot (docker was
25
- // absent on either side) diffs to nothing — we never accuse a turn we could not observe.
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 everything recorded for one card (or every card when card is undefined) and forget what
89
- // stopped; what could not be stopped stays recorded so the next sweep tries again.
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
- const targets = keys.flatMap(k => (state.cards[k] || []));
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);
@@ -0,0 +1,181 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { checkoutFor, PROJECT_MARKER, resolveHub, resolveProject, worktreeProject } from "./project.mjs";
6
+ import { ownerIdentity } from "./enroll.mjs";
7
+ import { z } from "zod";
8
+ import { sfetch } from "./signed-fetch.mjs";
9
+
10
+ const landing = z.enum(["auto", "review", "click"]);
11
+ const actions = z.strictObject({ land: landing, integrate: landing, push: z.enum(["autonomy", "click"]) });
12
+ const overrides = z.strictObject({
13
+ orchestrator: actions.partial().optional(), mixed: actions.partial().optional(), developer: actions.partial().optional(),
14
+ });
15
+ const mode = z.enum(["orchestrator", "mixed", "developer"]);
16
+ export const gitPolicyUpdate = z.strictObject({ mode, overrides, revision: z.number().int().nonnegative() });
17
+ const storedPolicy = gitPolicyUpdate.extend({ updatedBy: z.string().nullable(), updatedAtMs: z.number().int().nonnegative().nullable() });
18
+ const policyEnvelope = storedPolicy.extend({ effective: actions.optional() });
19
+ const defaults = {
20
+ orchestrator: { land: "auto", integrate: "auto", push: "autonomy" },
21
+ mixed: { land: "review", integrate: "review", push: "click" },
22
+ developer: { land: "click", integrate: "click", push: "click" },
23
+ };
24
+
25
+ export function gitPolicy(value) {
26
+ const parsed = policyEnvelope.safeParse(value);
27
+ const policy = parsed.success ? storedPolicy.parse({ mode: parsed.data.mode, overrides: parsed.data.overrides,
28
+ revision: parsed.data.revision, updatedBy: parsed.data.updatedBy, updatedAtMs: parsed.data.updatedAtMs })
29
+ : { mode: "developer", overrides: {}, revision: 0, updatedBy: null, updatedAtMs: null };
30
+ return { ...policy, effective: { ...defaults[policy.mode], ...policy.overrides[policy.mode] } };
31
+ }
32
+
33
+ export async function readGitPolicy({ hub, project, identity, fetchImpl = sfetch }) {
34
+ try {
35
+ const res = await fetchImpl(`${hub}/projects/${encodeURIComponent(project)}/git-policy`, {
36
+ signal: AbortSignal.timeout(10000),
37
+ }, identity);
38
+ if (!res.ok) return gitPolicy(null);
39
+ const parsed = storedPolicy.extend({ effective: actions }).safeParse(await res.json());
40
+ return gitPolicy(parsed.success ? storedPolicy.parse({ mode: parsed.data.mode, overrides: parsed.data.overrides,
41
+ revision: parsed.data.revision, updatedBy: parsed.data.updatedBy, updatedAtMs: parsed.data.updatedAtMs }) : null);
42
+ } catch {
43
+ // A hub outage must never grant permission to change the operator's checkout.
44
+ return gitPolicy(null);
45
+ }
46
+ }
47
+
48
+ export const GIT_POLICY_CACHE_MS = 60_000;
49
+ const guardConfig = z.strictObject({ project: z.string().min(1), checkout: z.string().min(1) });
50
+ const cacheSchema = z.strictObject({ project: z.string(), fetchedAtMs: z.number().int(), policy: policyEnvelope });
51
+ const marker = "# Trantor managed git landing guard";
52
+ const modulePath = fileURLToPath(import.meta.url);
53
+ const shellQuote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'";
54
+ const runGit = (repo, args) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
55
+ const commonDir = repo => runGit(repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
56
+ const rootDir = repo => realpathSync(runGit(repo, ["rev-parse", "--show-toplevel"]));
57
+ const isSeat = repo => worktreeProject(repo) && runGit(repo, ["rev-parse", "--abbrev-ref", "HEAD"]).startsWith("seat/");
58
+ const configPath = repo => join(commonDir(repo), "trantor-git-guard.json");
59
+ const cachePath = repo => join(commonDir(repo), "trantor-git-policy.json");
60
+
61
+ function readGuard(repo) {
62
+ try { return guardConfig.parse(JSON.parse(readFileSync(configPath(repo), "utf8"))); }
63
+ catch { return null; }
64
+ }
65
+
66
+ function atomicJson(path, value) {
67
+ const temp = `${path}.${process.pid}.tmp`;
68
+ writeFileSync(temp, JSON.stringify(value) + "\n", { mode: 0o600 });
69
+ renameSync(temp, path);
70
+ }
71
+
72
+ function operatorCheckout(repo) {
73
+ const config = readGuard(repo);
74
+ const root = rootDir(repo);
75
+ const common = commonDir(repo);
76
+ for (const candidate of new Set([root, config?.checkout, dirname(common)])) {
77
+ if (!candidate) continue;
78
+ try {
79
+ const marker = z.object({ operatorCheckout: z.string().min(1) }).parse(
80
+ JSON.parse(readFileSync(join(candidate, PROJECT_MARKER), "utf8")));
81
+ if (!isAbsolute(marker.operatorCheckout)) continue;
82
+ const checkout = realpathSync(marker.operatorCheckout);
83
+ if (commonDir(checkout) === common) return checkout;
84
+ } catch { /* Missing registration leaves the reference hook off. */ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ export function checkoutRole(repo) {
90
+ const root = rootDir(repo);
91
+ const checkout = operatorCheckout(repo);
92
+ if (checkout === root) return "operator";
93
+ if (isSeat(root)) return "seat";
94
+ return checkout ? "integration" : "unknown";
95
+ }
96
+
97
+ export function cacheGitPolicy(repo, project, policy, now = Date.now()) {
98
+ atomicJson(cachePath(repo), { project, policy: gitPolicy(policy), fetchedAtMs: now });
99
+ }
100
+
101
+ export function cachedGitPolicy(repo, now = Date.now()) {
102
+ try {
103
+ const config = readGuard(repo);
104
+ const cached = cacheSchema.parse(JSON.parse(readFileSync(cachePath(repo), "utf8")));
105
+ if (!config || cached.project !== config.project || cached.fetchedAtMs > now || now - cached.fetchedAtMs > GIT_POLICY_CACHE_MS) return gitPolicy(null);
106
+ return gitPolicy(cached.policy);
107
+ } catch {
108
+ return gitPolicy(null);
109
+ }
110
+ }
111
+
112
+ export function installGitGuard(repo, project) {
113
+ const checkout = rootDir(repo);
114
+ if (isSeat(checkout)) throw new Error("Install the git guard in the operator's checkout, not a seat worktree");
115
+ const existing = readGuard(repo);
116
+ if (existing && existing.checkout !== checkout) throw new Error("Git guard already belongs to another operator checkout");
117
+ const version = /git version (\d+)\.(\d+)/.exec(runGit(repo, ["--version"]));
118
+ if (!version || Number(version[1]) < 2 || (Number(version[1]) === 2 && Number(version[2]) < 28)) {
119
+ throw new Error("Git landing guard requires Git 2.28 or newer");
120
+ }
121
+ const common = commonDir(repo);
122
+ const hook = resolve(repo, runGit(repo, ["rev-parse", "--git-path", "hooks/reference-transaction"]));
123
+ if (!hook.startsWith(common + sep) && !hook.startsWith(checkout + sep)) {
124
+ throw new Error("Git guard cannot replace a shared external core.hooksPath");
125
+ }
126
+ mkdirSync(dirname(hook), { recursive: true });
127
+ const previous = existsSync(hook) ? readFileSync(hook, "utf8") : "";
128
+ const backup = `${hook}.trantor-original`;
129
+ if (previous && !previous.includes(marker)) {
130
+ if (existsSync(backup)) throw new Error("Git guard hook backup already exists; preserve it before reinstalling");
131
+ renameSync(hook, backup);
132
+ }
133
+ atomicJson(configPath(repo), { project, checkout });
134
+ const script = `#!/bin/sh\n${marker}\nif [ "$1" = prepared ] && [ -n "\${TRANTOR_AGENT_IDENTITY:-}\${RELAY_SESSION:-}" ]; then\n ${shellQuote(process.execPath)} ${shellQuote(modulePath)} hook "$1" || exit $?\nfi\nif [ -x ${shellQuote(backup)} ]; then exec ${shellQuote(backup)} "$@"; fi\n`;
135
+ const temp = `${hook}.${process.pid}.tmp`;
136
+ writeFileSync(temp, script, { mode: 0o755 });
137
+ renameSync(temp, hook);
138
+ return { checkout, hook };
139
+ }
140
+
141
+ export function refreshLocalGitPolicy(project, policy, repo = checkoutFor(project)) {
142
+ if (!repo) return;
143
+ installGitGuard(repo, project);
144
+ cacheGitPolicy(repo, project, policy);
145
+ }
146
+
147
+ export function landingVerdict(policy, { action = "land", review = null, tip = null } = {}) {
148
+ const current = gitPolicy(policy);
149
+ const rule = current.effective[action];
150
+ const label = current.mode[0].toUpperCase() + current.mode.slice(1);
151
+ if (rule === "click") return { allowed: false, reason: `${label} mode: land from the sidebar (${action})` };
152
+ if (rule === "review" && !(review?.reviewed && review.merge && tip && review.tip === tip)) {
153
+ return { allowed: false, reason: `${label} mode: ${action} requires every hunk approved at the current tip` };
154
+ }
155
+ return { allowed: true };
156
+ }
157
+
158
+ export function referenceVerdict(repo, phase, env = process.env) {
159
+ if (phase !== "prepared" || !(env.TRANTOR_AGENT_IDENTITY || env.RELAY_SESSION)) return { allowed: true };
160
+ if (checkoutRole(repo) !== "operator") return { allowed: true };
161
+ const policy = cachedGitPolicy(repo);
162
+ if (policy.effective.land === "click") return landingVerdict(policy);
163
+ return { allowed: true };
164
+ }
165
+
166
+ async function main() {
167
+ const [command, phase] = process.argv.slice(2);
168
+ const repo = process.cwd();
169
+ if (command === "hook") {
170
+ const result = referenceVerdict(repo, phase);
171
+ if (!result.allowed) { console.error(result.reason); process.exitCode = 1; }
172
+ } else if (command === "refresh") {
173
+ const project = resolveProject(repo);
174
+ const policy = await readGitPolicy({ hub: resolveHub(project), project, identity: ownerIdentity() });
175
+ refreshLocalGitPolicy(project, policy, repo);
176
+ console.log(JSON.stringify(policy));
177
+ } else throw new Error("usage: node lib/git-guard.mjs refresh");
178
+ }
179
+ if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
180
+ await main().catch(error => { console.error(error.message); process.exitCode = 1; });
181
+ }
package/lib/integrate.mjs CHANGED
@@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process";
4
4
  import { existsSync, readdirSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { homedir } from "node:os";
7
+ import { cachedGitPolicy, checkoutRole, landingVerdict } from "./git-guard.mjs";
7
8
 
8
9
  const busDir = () => process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
9
10
 
@@ -53,10 +54,17 @@ export function seatAhead(w, base = "main") {
53
54
 
54
55
  /** Merge one seat's branch into the current checkout. A conflict is the collision the overseer exists
55
56
  * to surface, so the merge is aborted and reported rather than left half-done. */
56
- export function mergeSeat(repo, branch) {
57
+ export function mergeSeat(repo, branch, { policy = cachedGitPolicy(repo), review = null, action = "land" } = {}) {
58
+ const tip = git(repo, ["rev-parse", `${branch}^{commit}`]);
59
+ const role = checkoutRole(repo);
60
+ if (role !== "seat" && role !== "integration") {
61
+ const land = landingVerdict(policy, { review, tip });
62
+ const gate = land.allowed ? landingVerdict(policy, { action, review, tip }) : land;
63
+ if (!gate.allowed) return { branch, merged: false, conflict: false, refused: true, detail: gate.reason };
64
+ }
57
65
  const before = git(repo, ["rev-parse", "HEAD"]);
58
66
  try {
59
- git(repo, ["merge", "--no-edit", branch]);
67
+ git(repo, ["merge", "--no-edit", tip]);
60
68
  const after = git(repo, ["rev-parse", "HEAD"]);
61
69
  return { branch, merged: before !== after, conflict: false };
62
70
  } catch (e) {
@@ -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,64 @@ 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_board_revisions (
242
+ org_id TEXT NOT NULL, project TEXT NOT NULL, card BIGINT NOT NULL,
243
+ revision BIGINT NOT NULL, content_hash TEXT NOT NULL,
244
+ PRIMARY KEY(org_id,project,card)
245
+ );
246
+ CREATE TABLE IF NOT EXISTS dispatcher_integration_migrations (
247
+ id TEXT PRIMARY KEY, completed_at_ms BIGINT NOT NULL
248
+ );
249
+ CREATE OR REPLACE FUNCTION dispatcher_card_fence() RETURNS trigger AS $$
250
+ DECLARE organization TEXT; card_id BIGINT;
251
+ BEGIN
252
+ organization := OLD.org_id;
253
+ card_id := OLD.id;
254
+ PERFORM pg_advisory_xact_lock(hashtextextended('dispatcher:' || organization,0));
255
+ IF current_setting('trantor.dispatcher_card_write',true) = 'on' THEN
256
+ IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
257
+ END IF;
258
+ IF EXISTS(SELECT 1 FROM dispatcher_cards WHERE org_id=organization AND card=card_id
259
+ AND row->>'depsBasis' IS DISTINCT FROM 'board') THEN
260
+ IF TG_OP='DELETE' OR NEW IS DISTINCT FROM OLD THEN
261
+ RAISE EXCEPTION 'managed card requires dispatcher transaction' USING ERRCODE='40001';
262
+ END IF;
263
+ END IF;
264
+ IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
265
+ END;
266
+ $$ LANGUAGE plpgsql;
267
+ DO $$ BEGIN
268
+ IF to_regclass('tasks') IS NOT NULL THEN
269
+ DROP TRIGGER IF EXISTS dispatcher_card_fence ON tasks;
270
+ CREATE TRIGGER dispatcher_card_fence BEFORE UPDATE OR DELETE ON tasks
271
+ FOR EACH ROW EXECUTE FUNCTION dispatcher_card_fence();
272
+ END IF;
273
+ END $$;
274
+ INSERT INTO dispatcher_integration_migrations VALUES('dispatcher-b6-v1',
275
+ (extract(epoch from clock_timestamp())*1000)::bigint) ON CONFLICT(id) DO NOTHING;
276
+ `;