trantor 0.18.149 → 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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/bin/advise.mjs +11 -8
- package/bin/cli.mjs +1 -1
- package/bin/connect.mjs +10 -1
- package/bin/crew-runner.mjs +5 -4
- package/bin/integrate.mjs +38 -9
- package/bin/turn-watchdog.mjs +15 -1
- package/deploy/restart-hub.sh +2 -0
- package/docs/FEATURES.md +4 -1
- package/hooks/sessionstart.mjs +6 -1
- package/hub/auth.mjs +5 -0
- package/hub/routes/dispatcher-operations.mjs +12 -0
- package/hub/routes/git-policy.mjs +35 -0
- package/hub/startup-config.mjs +14 -0
- package/hub/store.mjs +31 -2
- package/hub.mjs +4 -2
- package/kimi.plugin.json +1 -1
- package/lib/canary/canary.mjs +2 -0
- package/lib/canary/probes.mjs +62 -0
- package/lib/dispatcher/admission.mjs +1 -0
- package/lib/dispatcher/board-bridge.mjs +82 -0
- package/lib/dispatcher/evidence-bridge.mjs +283 -0
- package/lib/dispatcher/operations.mjs +145 -19
- package/lib/dispatcher/planner.mjs +4 -2
- package/lib/dispatcher/preflight.mjs +42 -7
- package/lib/dispatcher/rollout.mjs +357 -0
- package/lib/dispatcher/schemas.mjs +1 -0
- package/lib/dispatcher/snapshot.mjs +9 -5
- package/lib/dispatcher/store.mjs +15 -0
- package/lib/git-guard.mjs +181 -0
- package/lib/integrate.mjs +10 -2
- package/lib/store-contract.mjs +7 -1
- package/mcp.mjs +4 -5
- package/package.json +3 -3
|
@@ -75,6 +75,44 @@ export function readCachedAdvice(busDir, project, now = Date.now()) {
|
|
|
75
75
|
return { ...row, ageMs: Math.max(0, now - row.cachedAtMs) };
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
// An unreachable hub hands back the last decision for the project, labelled, or nothing.
|
|
79
|
+
function fallbackAdvice({ r, busDir, project, now }) {
|
|
80
|
+
const cached = busDir ? readCachedAdvice(busDir, project, now()) : null;
|
|
81
|
+
const why = { status: r.status, code: errorCode(r), reason: reasonOf(r) };
|
|
82
|
+
if (!cached) return { source: "none", dispatchable: false, decision: null, unavailable: why };
|
|
83
|
+
return { source: "cached", dispatchable: false, cachedAtMs: cached.cachedAtMs, ageMs: cached.ageMs,
|
|
84
|
+
decisionHash: cached.decisionHash, decision: cached.decision, unavailable: why };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const refusal = (status, code, cards = []) => ({ source: "refused", status, code, reasons: [], cards, dispatchable: false, decision: null });
|
|
88
|
+
const isCardNumber = (c) => Number.isSafeInteger(c) && c > 0;
|
|
89
|
+
const isObject = (c) => c !== null && Object(c) === c && !Array.isArray(c);
|
|
90
|
+
|
|
91
|
+
/** #14742: card numbers become the hub's own WorkCards. The planner refuses any card that differs from
|
|
92
|
+
* its snapshot's ready queue (card_stale), so the client copies each one from the projected snapshot
|
|
93
|
+
* (GET /capacity?version=1) and pins /advise to that snapshot. Objects in `cards` pass through. */
|
|
94
|
+
export async function resolveCards({ get, project, cards = [], snapshotId = null }) {
|
|
95
|
+
const bad = cards.filter((c) => !isObject(c) && !isCardNumber(c));
|
|
96
|
+
if (bad.length) return { ok: false, result: refusal(422, "card_number_invalid", bad) };
|
|
97
|
+
if (!cards.some(isCardNumber)) return { ok: true, cards, snapshotId };
|
|
98
|
+
const r = await get(`/capacity?version=1&project=${encodeURIComponent(project)}${snapshotId ? `&snapshotId=${encodeURIComponent(snapshotId)}` : ""}`);
|
|
99
|
+
if (!r.ok) return { ok: false, unavailable: unavailable(r), r, result: unavailable(r) ? null : refusal(r.status, errorCode(r)) };
|
|
100
|
+
const queue = r.json?.schemaVersion === 1 ? r.json.snapshot?.readyQueue : null;
|
|
101
|
+
if (!Array.isArray(queue) || !r.json.snapshotId) return { ok: false, result: refusal(502, "card_lookup_unavailable") };
|
|
102
|
+
const found = new Map(queue.filter((c) => c.project === project).map((c) => [c.card, c]));
|
|
103
|
+
const missing = cards.filter((c) => isCardNumber(c) && !found.has(c));
|
|
104
|
+
if (missing.length) return { ok: false, result: refusal(409, "card_not_ready", missing) };
|
|
105
|
+
return { ok: true, cards: cards.map((c) => (isCardNumber(c) ? found.get(c) : c)), snapshotId: r.json.snapshotId };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** The one advise path for CLI and MCP: resolve card numbers, build the request, ask the hub. */
|
|
109
|
+
export async function adviseCards({ get, post, busDir, project, cards = [], drafts = [], snapshotId, policyVersion, now = () => Date.now() }) {
|
|
110
|
+
const resolved = await resolveCards({ get, project, cards, snapshotId });
|
|
111
|
+
if (!resolved.ok) return resolved.unavailable ? fallbackAdvice({ r: resolved.r, busDir, project, now }) : resolved.result;
|
|
112
|
+
const request = await buildAdviceRequest({ project, cards: resolved.cards, drafts, snapshotId: resolved.snapshotId, policyVersion });
|
|
113
|
+
return requestAdvice({ post, busDir, request, now });
|
|
114
|
+
}
|
|
115
|
+
|
|
78
116
|
/** POST /advise. A hub decision is validated and cached; an unreachable hub yields the cached decision, labelled. */
|
|
79
117
|
export async function requestAdvice({ post, busDir, request, now = () => Date.now() }) {
|
|
80
118
|
const r = await post("/advise", request);
|
|
@@ -89,11 +127,7 @@ export async function requestAdvice({ post, busDir, request, now = () => Date.no
|
|
|
89
127
|
return { source: "hub", dispatchable, decisionHash, decision };
|
|
90
128
|
}
|
|
91
129
|
if (!unavailable(r)) return { source: "refused", status: r.status, code: errorCode(r), reasons: r.json?.reasons || [], dispatchable: false, decision: null };
|
|
92
|
-
|
|
93
|
-
const why = { status: r.status, code: errorCode(r), reason: reasonOf(r) };
|
|
94
|
-
if (!cached) return { source: "none", dispatchable: false, decision: null, unavailable: why };
|
|
95
|
-
return { source: "cached", dispatchable: false, cachedAtMs: cached.cachedAtMs, ageMs: cached.ageMs,
|
|
96
|
-
decisionHash: cached.decisionHash, decision: cached.decision, unavailable: why };
|
|
130
|
+
return fallbackAdvice({ r, busDir, project: request.project, now });
|
|
97
131
|
}
|
|
98
132
|
|
|
99
133
|
/** Deterministic, so a retry after a transport timeout reuses the key instead of rotating it. */
|
|
@@ -172,7 +206,8 @@ const fmtAge = (ms) => ms == null ? "unknown age" : ms < 60e3 ? `${Math.round(ms
|
|
|
172
206
|
export function renderAdvice(result) {
|
|
173
207
|
if (result.source === "refused") {
|
|
174
208
|
const reasons = (result.reasons || []).map((r) => r.code).join(", ");
|
|
175
|
-
|
|
209
|
+
const cards = result.cards?.length ? ` for ${result.cards.map((c) => `#${c}`).join(", ")}` : "";
|
|
210
|
+
return `ADVICE REFUSED: ${result.code} (HTTP ${result.status})${cards}${reasons ? `: ${reasons}` : ""}`;
|
|
176
211
|
}
|
|
177
212
|
if (result.source === "none") return `NO ADVICE: hub unavailable (${result.unavailable.reason}) and no cached decision for this project. Nothing launches.`;
|
|
178
213
|
const d = result.decision;
|
|
@@ -226,7 +261,7 @@ export function orchestratorBrief() {
|
|
|
226
261
|
return [
|
|
227
262
|
"When you orchestrate a Trantor project (you assign cards rather than work them), dispatch through the hub. The same commands work in Claude Code, Codex, Kimi and opencode; no step needs a Claude-only tool.",
|
|
228
263
|
"1. Before every batch: `trantor dispatch preflight --json` (MCP: relay_dispatch action=preflight). Open regressions print first; deal with them before new work.",
|
|
229
|
-
"2. Ask for the plan: `trantor advise --json
|
|
264
|
+
"2. Ask for the plan: `trantor advise --card <n> --json`, repeatable, or {\"cards\":[<n>,...]} on stdin (MCP: relay_advise with cards as card numbers). The hub's decision is the plan; never rank models or choose a fallback yourself.",
|
|
230
265
|
"3. Admit work: `trantor dispatch --decision <id> --json` (MCP: relay_dispatch). One request per card; partial admission is normal; replan rejected cards with a new advise call.",
|
|
231
266
|
"4. A timed-out dispatch is retried with the same command: the idempotency key comes from decision, card and revision, so a retry never launches twice.",
|
|
232
267
|
"5. CACHED ADVICE means the hub was unreachable: advice only, nothing launches. 503 dispatch_unavailable means this hub keeps advice only (JSON store or auth off).",
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { advise, loadWorld } from '../../bin/advise.mjs';
|
|
3
|
+
import { redactKeys } from '../redact.mjs';
|
|
4
|
+
import { loadSeatRecord } from '../seat-record.mjs';
|
|
5
|
+
import { ingestEvent, newRegister, resolveUsage } from './spend.mjs';
|
|
6
|
+
import { canonicalHash, canonicalJson } from './snapshot.mjs';
|
|
7
|
+
import { plan } from './planner.mjs';
|
|
8
|
+
import { reject } from './admission.mjs';
|
|
9
|
+
import { executionRows, fenceExecution, KillSchema } from './executor.mjs';
|
|
10
|
+
|
|
11
|
+
const text = z.string().min(1).max(8192);
|
|
12
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
13
|
+
const DAY = 86400_000;
|
|
14
|
+
export const FIRST_WAVE_DRILLS = Array.from({ length: 25 }, (_, i) => `D${i + 1}`).filter(id => id !== 'D12');
|
|
15
|
+
export const RolloutApprovalSchema = z.strictObject({ cohortId: text, testedSha: z.string().regex(/^[a-f0-9]{40}$/),
|
|
16
|
+
baselineId: text, checks: z.strictObject({ crewMatrix: text, healthyCanaries: text, accountMappings: text, spendReconciliation: text }) });
|
|
17
|
+
export function rolloutPolicyHash(policy) {
|
|
18
|
+
const { hash: _hash, version: _version, parentVersion: _parent, createdAtMs: _at, createdBy: _by, modeByProject: _modes, ...rules } = policy;
|
|
19
|
+
return canonicalHash(rules);
|
|
20
|
+
}
|
|
21
|
+
const key = card => `${card.project}:${card.card}`;
|
|
22
|
+
const sanitize = value => JSON.parse(redactKeys(JSON.stringify(value, (name, item) =>
|
|
23
|
+
/secret|password|api.?key|(?:access|refresh).?token|authorization|^token$/i.test(name) ? '<redacted>' : item)));
|
|
24
|
+
|
|
25
|
+
export function captureShadow({ snapshot, policy, cards, packages, world }) {
|
|
26
|
+
if (cards.some(card => policy.modeByProject[card.project] !== 'shadow')) reject('shadow_required');
|
|
27
|
+
if (packages.length !== cards.length) reject('card_stale');
|
|
28
|
+
const decision = plan({ snapshot, policy, cards });
|
|
29
|
+
const legacy = advise({ packages }, world);
|
|
30
|
+
const bindings = Object.fromEntries(Object.entries(world.roster).map(([executor, entry]) => {
|
|
31
|
+
const seats = snapshot.seats.filter(seat => seat.harness === 'crew' && seat.id === entry.session);
|
|
32
|
+
return [executor, seats.length === 1 ? { seatId: seats[0].id, harness: seats[0].harness, machine: seats[0].machine } : null];
|
|
33
|
+
}));
|
|
34
|
+
const mapping = { version: 1, bindings };
|
|
35
|
+
const policyFingerprint = rolloutPolicyHash(policy);
|
|
36
|
+
const companion = sanitize({ snapshotId: snapshot.id, policyVersion: policy.version,
|
|
37
|
+
input: { packages }, world, output: legacy, mapping: { ...mapping, hash: canonicalHash(mapping) } });
|
|
38
|
+
const companionId = canonicalHash(companion);
|
|
39
|
+
const comparisons = cards.map((card, index) => {
|
|
40
|
+
const old = legacy.routing[index];
|
|
41
|
+
const assignment = decision.assignments.find(a => key(a) === key(card));
|
|
42
|
+
const candidate = assignment?.candidate || null;
|
|
43
|
+
const binding = ['orchestrator', 'scrooge'].includes(old.executor) ? null : bindings[old.executor];
|
|
44
|
+
const comparable = Boolean(binding);
|
|
45
|
+
const costByAccount = new Map();
|
|
46
|
+
for (const charge of assignment?.estimates || []) if (charge.unit === 'usdMicros') {
|
|
47
|
+
costByAccount.set(charge.accountId, Math.max(costByAccount.get(charge.accountId) || 0, charge.estimate));
|
|
48
|
+
}
|
|
49
|
+
const plannerUsd = costByAccount.size ? [...costByAccount.values()].reduce((a, b) => a + b, 0) / 1_000_000 : null;
|
|
50
|
+
const differences = [];
|
|
51
|
+
if (comparable) {
|
|
52
|
+
for (const field of ['seatId', 'harness', 'machine']) if (binding[field] !== candidate?.[field]) differences.push(field);
|
|
53
|
+
if (old.model != null && old.model !== candidate?.model) differences.push('model');
|
|
54
|
+
const effort = z.string().safeParse(old.effort?.params?.reasoning_effort ?? old.effort);
|
|
55
|
+
if (effort.success && effort.data !== candidate?.effort) differences.push('effort');
|
|
56
|
+
}
|
|
57
|
+
return { project: card.project, card: card.card, cardRevision: card.revision,
|
|
58
|
+
stratum: { kind: card.kind, difficulty: card.difficulty, size: card.size, effectClass: card.effectClass,
|
|
59
|
+
machine: policy.placementByKind[card.kind] || policy.placementByKind.default || null },
|
|
60
|
+
estimateComparison: { costDeltaUsd: old.est_cost_usd != null && plannerUsd != null ? plannerUsd - old.est_cost_usd : null,
|
|
61
|
+
legacyUsd: old.est_cost_usd ?? null, plannerUsd, timeDeltaMs: null },
|
|
62
|
+
category: !comparable ? 'not-comparable' : differences.length ? 'disagreement' : 'agreement', differences,
|
|
63
|
+
legacy: { executor: old.executor, binding: binding || null, model: old.model || null,
|
|
64
|
+
reason: old.reason, costUsd: old.est_cost_usd ?? null },
|
|
65
|
+
planner: { candidate, reason: assignment?.reason || decision.waiting.find(a => key(a) === key(card))?.reasons.join(';'),
|
|
66
|
+
expectedMs: assignment?.expectedMs ?? null, estimates: assignment?.estimates || [] } };
|
|
67
|
+
});
|
|
68
|
+
return sanitize({ snapshotId: snapshot.id, policyVersion: policy.version, asOfMs: snapshot.asOfMs,
|
|
69
|
+
companionId, companion, policyFingerprint, decision, comparisons });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function shadowSummary(ticks, ratings = [], throughMs = Infinity) {
|
|
73
|
+
const first = new Map();
|
|
74
|
+
for (const tick of [...ticks].sort((a, b) => a.atMs - b.atMs || a.id.localeCompare(b.id))) {
|
|
75
|
+
if (tick.atMs > throughMs) continue;
|
|
76
|
+
for (const row of tick.comparisons) if (!first.has(key(row))) first.set(key(row), { ...row, tickId: tick.id, atMs: tick.atMs });
|
|
77
|
+
}
|
|
78
|
+
const rows = [...first.values()].map(row => ({ ...row, rating: ratings.find(r => r.tickId === row.tickId && r.card === row.card && r.project === row.project)?.rating || null }));
|
|
79
|
+
const disagreements = rows.filter(r => r.category === 'disagreement');
|
|
80
|
+
const agreements = rows.filter(r => r.category === 'agreement').length;
|
|
81
|
+
const notComparable = rows.filter(r => r.category === 'not-comparable').length;
|
|
82
|
+
const unrated = disagreements.filter(r => r.rating == null).length;
|
|
83
|
+
const fingerprints = [...new Set(ticks.map(t => t.policyFingerprint))];
|
|
84
|
+
const atLeastAsGood = disagreements.filter(r => r.rating === 'at-least-as-good').length;
|
|
85
|
+
const activeDays = new Set(rows.map(r => Math.floor(r.atMs / DAY))).size;
|
|
86
|
+
const eligibleRows = rows.filter(r => r.category !== 'not-comparable');
|
|
87
|
+
const comparableActiveDays = new Set(eligibleRows.map(r => Math.floor(r.atMs / DAY))).size;
|
|
88
|
+
const startedAtMs = eligibleRows.length ? Math.min(...eligibleRows.map(r => r.atMs)) : null;
|
|
89
|
+
const weekComplete = startedAtMs != null && throughMs - startedAtMs >= 7 * DAY;
|
|
90
|
+
return { rows, policyFingerprint: fingerprints.length === 1 ? fingerprints[0] : null, cards: rows.length, activeDays, comparableActiveDays, startedAtMs, throughMs, weekComplete,
|
|
91
|
+
agreements, disagreements: disagreements.length, notComparable, unrated, atLeastAsGood,
|
|
92
|
+
agreementFraction: agreements + disagreements.length ? agreements / (agreements + disagreements.length) : null,
|
|
93
|
+
ratedGoodFraction: disagreements.length ? atLeastAsGood / disagreements.length : 1,
|
|
94
|
+
eligible: rows.length - notComparable >= 20 && comparableActiveDays >= 5 && weekComplete && unrated === 0
|
|
95
|
+
&& (!disagreements.length || atLeastAsGood / disagreements.length >= 0.8),
|
|
96
|
+
exclusions: { notComparable, repeatedCards: ticks.reduce((n, tick) => n + tick.comparisons.length, 0) - rows.length } };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function records(client, orgId, action) {
|
|
100
|
+
return (await client.query("SELECT row FROM dispatcher_audit WHERE org_id=$1 AND row->>'action'=$2 ORDER BY at_ms,(row->>'sequence')::bigint NULLS FIRST,id", [orgId, action])).rows.map(r => r.row);
|
|
101
|
+
}
|
|
102
|
+
const safetyEpoch = rows => canonicalHash(rows.filter(r => r.result === 'fail').map(r => r.id).sort());
|
|
103
|
+
|
|
104
|
+
export async function validateRolloutApproval(client, orgId, approval) {
|
|
105
|
+
const rollout = RolloutApprovalSchema.parse(approval.rollout);
|
|
106
|
+
const cohorts = await records(client, orgId, 'rollout-frozen');
|
|
107
|
+
const cohort = cohorts.find(c => c.id === rollout.cohortId);
|
|
108
|
+
if (!cohort?.summary.eligible) reject('shadow_evidence_required', 403);
|
|
109
|
+
const baseline = (await records(client, orgId, 'rollout-baseline')).find(b => b.id === rollout.baselineId);
|
|
110
|
+
if (!baseline || baseline.project !== cohort.project || baseline.throughMs - baseline.fromMs < 7 * DAY) reject('baseline_required', 403);
|
|
111
|
+
const drills = await records(client, orgId, 'rollout-drill');
|
|
112
|
+
for (const id of FIRST_WAVE_DRILLS) {
|
|
113
|
+
const receipts = drills.filter(d => d.drill === id);
|
|
114
|
+
const latest = receipts.at(-1);
|
|
115
|
+
const failure = receipts.filter(r => r.result === 'fail').at(-1);
|
|
116
|
+
if (failure && failure.testedSha === latest?.testedSha) reject('drill_new_artifact_required', 403);
|
|
117
|
+
if (!latest || latest.result !== 'pass' || latest.testedSha !== rollout.testedSha
|
|
118
|
+
|| !approval.drills.some(d => d.id === id && d.evidenceRef === latest.evidenceRef)) reject('drill_evidence_required', 403);
|
|
119
|
+
}
|
|
120
|
+
return { safetyEpoch: safetyEpoch(drills), cohortId: cohort.id, testedSha: rollout.testedSha };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function currentAdvisorWorld(project) {
|
|
124
|
+
const world = loadWorld();
|
|
125
|
+
world.record = await loadSeatRecord({ project });
|
|
126
|
+
return world;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function createRolloutOperations({ service, requireRole, clock, advisorWorld = currentAdvisorWorld }) {
|
|
130
|
+
const { store } = service;
|
|
131
|
+
const owner = (client, orgId, actor) => requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
132
|
+
const audit = async (client, orgId, action, payload, actor) => {
|
|
133
|
+
const sequence = Number((await client.query('SELECT count(*) AS n FROM dispatcher_audit WHERE org_id=$1', [orgId])).rows[0].n);
|
|
134
|
+
const record = sanitize({ action, ...payload, actor: actor.pubkey, atMs: clock(), sequence });
|
|
135
|
+
record.id = canonicalHash(record);
|
|
136
|
+
await store.audit(client, orgId, record);
|
|
137
|
+
return record;
|
|
138
|
+
};
|
|
139
|
+
const summary = async (client, orgId, project, policyVersion) => shadowSummary(
|
|
140
|
+
(await records(client, orgId, 'rollout-shadow')).filter(t => t.project === project && (!policyVersion || t.policyVersion === policyVersion)),
|
|
141
|
+
await records(client, orgId, 'rollout-rating'), clock());
|
|
142
|
+
const stop = async (client, orgId, reason, actor) => {
|
|
143
|
+
await client.query(`INSERT INTO dispatcher_control VALUES($1,'*',true,$2)
|
|
144
|
+
ON CONFLICT(org_id,scope) DO UPDATE SET enabled=true,row=EXCLUDED.row`,
|
|
145
|
+
[orgId, { project: null, enabled: true, reason, actor: actor.pubkey, atMs: clock() }]);
|
|
146
|
+
const live = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1
|
|
147
|
+
AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId])).rows;
|
|
148
|
+
for (const { id } of live) await fenceExecution(client, orgId, await executionRows(client, orgId, id), reason, clock());
|
|
149
|
+
return live.length;
|
|
150
|
+
};
|
|
151
|
+
return {
|
|
152
|
+
async shadowTick(orgId, input, actor) {
|
|
153
|
+
const request = z.strictObject({ project: text, snapshotId: text.optional() }).parse(input);
|
|
154
|
+
return store.locked(orgId, async client => {
|
|
155
|
+
await owner(client, orgId, actor);
|
|
156
|
+
const authority = await service.readAdvice(client, { orgId, request });
|
|
157
|
+
const cards = authority.snapshot.readyQueue.filter(c => c.project === request.project);
|
|
158
|
+
const tasks = (await client.query('SELECT id,title FROM tasks WHERE org_id=$1 AND project=$2', [orgId, request.project])).rows;
|
|
159
|
+
const packages = cards.map(card => {
|
|
160
|
+
const task = tasks.find(t => Number(t.id) === card.card);
|
|
161
|
+
if (!task) reject('card_stale');
|
|
162
|
+
return { title: task.title, difficulty: card.difficulty, kind: card.kind };
|
|
163
|
+
});
|
|
164
|
+
const captured = captureShadow({ ...authority, cards, packages, world: await advisorWorld(request.project) });
|
|
165
|
+
return audit(client, orgId, 'rollout-shadow', { project: request.project, ...captured }, actor);
|
|
166
|
+
});
|
|
167
|
+
},
|
|
168
|
+
async rolloutReport(orgId, input, actor) {
|
|
169
|
+
const { project, policyVersion } = z.strictObject({ project: text, policyVersion: text.optional() }).parse(input);
|
|
170
|
+
return store.locked(orgId, async client => {
|
|
171
|
+
await owner(client, orgId, actor);
|
|
172
|
+
const baseline = (await records(client, orgId, 'rollout-baseline')).filter(b => b.project === project).at(-1);
|
|
173
|
+
const latestShadow = (await records(client, orgId, 'rollout-shadow')).filter(r => r.project === project).at(-1);
|
|
174
|
+
const lastSnapshot = latestShadow ? (await client.query('SELECT row FROM dispatcher_snapshots WHERE org_id=$1 AND id=$2', [orgId, latestShadow.snapshotId])).rows[0]?.row : null;
|
|
175
|
+
const trial = await storedCohort(client, orgId, project, { fromMs: baseline?.throughMs ?? 0, throughMs: clock() });
|
|
176
|
+
return { schemaVersion: 1, shadow: await summary(client, orgId, project, policyVersion),
|
|
177
|
+
baseline: baseline || null, trial, cohortComparison: compareCohorts(baseline?.cohort, trial),
|
|
178
|
+
operationalMetrics: { status: 'not-established', activeSeatsVsFeasible: lastSnapshot ? { asOfMs: lastSnapshot.asOfMs,
|
|
179
|
+
activeSeats: lastSnapshot.machines.reduce((n, m) => n + m.activeSeats, 0),
|
|
180
|
+
feasiblePlanned: latestShadow.decision.assignments.filter(a => a.candidate).length } : null, canaryLatencyMs: null,
|
|
181
|
+
eligibleWindowUse: null, oversubscribedAdmissions: null, permissionBreaches: null },
|
|
182
|
+
drills: await records(client, orgId, 'rollout-drill'), deferred: ['D12'] };
|
|
183
|
+
});
|
|
184
|
+
},
|
|
185
|
+
async rateShadow(orgId, input, actor) {
|
|
186
|
+
const request = z.strictObject({ tickId: text, project: text, card: integer.min(1),
|
|
187
|
+
rating: z.enum(['at-least-as-good', 'worse']), reason: text }).parse(input);
|
|
188
|
+
return store.locked(orgId, async client => {
|
|
189
|
+
await owner(client, orgId, actor);
|
|
190
|
+
const row = (await summary(client, orgId, request.project)).rows.find(r => r.tickId === request.tickId && r.card === request.card);
|
|
191
|
+
if (!row || row.category !== 'disagreement' || row.rating) reject('rating_conflict');
|
|
192
|
+
return audit(client, orgId, 'rollout-rating', request, actor);
|
|
193
|
+
});
|
|
194
|
+
},
|
|
195
|
+
async freezeRollout(orgId, input, actor) {
|
|
196
|
+
const request = z.strictObject({ project: text, policyVersion: text.optional() }).parse(input);
|
|
197
|
+
return store.locked(orgId, async client => {
|
|
198
|
+
await owner(client, orgId, actor);
|
|
199
|
+
return audit(client, orgId, 'rollout-frozen', { project: request.project, summary: await summary(client, orgId, request.project, request.policyVersion) }, actor);
|
|
200
|
+
});
|
|
201
|
+
},
|
|
202
|
+
async freezeBaseline(orgId, input, actor) {
|
|
203
|
+
const request = z.strictObject({ project: text, fromMs: integer, throughMs: integer }).parse(input);
|
|
204
|
+
if (request.throughMs > clock() || request.throughMs - request.fromMs < 7 * DAY) reject('baseline_period_invalid', 422);
|
|
205
|
+
return store.locked(orgId, async client => {
|
|
206
|
+
await owner(client, orgId, actor);
|
|
207
|
+
const promoted = (await client.query(`SELECT p.row FROM dispatcher_policies p JOIN dispatcher_audit a
|
|
208
|
+
ON a.org_id=p.org_id AND a.row->>'version'=p.version
|
|
209
|
+
WHERE p.org_id=$1 AND a.row->>'action'='policy-activated'`, [orgId])).rows;
|
|
210
|
+
if (promoted.some(p => p.row.modeByProject[request.project] === 'admit')) reject('baseline_already_promoted');
|
|
211
|
+
const cohort = await storedCohort(client, orgId, request.project, request);
|
|
212
|
+
return audit(client, orgId, 'rollout-baseline', { ...request, cohort }, actor);
|
|
213
|
+
});
|
|
214
|
+
},
|
|
215
|
+
async recordDrill(orgId, input, actor) {
|
|
216
|
+
const request = z.strictObject({ drill: z.enum([...FIRST_WAVE_DRILLS, 'D12']), result: z.enum(['pass','fail','deferred']),
|
|
217
|
+
testedSha: z.string().regex(/^[a-f0-9]{40}$/), evidenceRef: text, reason: text }).parse(input);
|
|
218
|
+
if ((request.drill === 'D12') !== (request.result === 'deferred')) reject('drill_scope_invalid', 422);
|
|
219
|
+
return store.locked(orgId, async client => {
|
|
220
|
+
await owner(client, orgId, actor);
|
|
221
|
+
const stopped = request.result === 'fail' ? await stop(client, orgId, `failed:${request.drill}`, actor) : 0;
|
|
222
|
+
return audit(client, orgId, 'rollout-drill', { ...request, stopped, scope: 'first-wave-crew' }, actor);
|
|
223
|
+
});
|
|
224
|
+
},
|
|
225
|
+
async rollbackPolicy(orgId, input, actor) {
|
|
226
|
+
const request = z.strictObject({ expectedVersion: text, version: text, reason: text }).parse(input);
|
|
227
|
+
return store.locked(orgId, async client => {
|
|
228
|
+
await owner(client, orgId, actor);
|
|
229
|
+
const current = (await client.query('SELECT policy_version FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
230
|
+
if (current?.policy_version !== request.expectedVersion) reject('policy_stale');
|
|
231
|
+
const previous = (await records(client, orgId, 'policy-activated')).find(r => r.version === request.version);
|
|
232
|
+
if (!previous) reject('rollback_policy_unknown');
|
|
233
|
+
const stopped = await stop(client, orgId, request.reason, actor);
|
|
234
|
+
await client.query('UPDATE dispatcher_authority_state SET revision=revision+1,policy_version=$2 WHERE org_id=$1', [orgId, request.version]);
|
|
235
|
+
return audit(client, orgId, 'policy-rollback', { ...request, stopped }, actor);
|
|
236
|
+
});
|
|
237
|
+
},
|
|
238
|
+
async clearControl(orgId, input, actor) {
|
|
239
|
+
const control = KillSchema.parse(input);
|
|
240
|
+
if (control.enabled) reject('schema_invalid', 422);
|
|
241
|
+
return store.locked(orgId, async client => {
|
|
242
|
+
await requireRole(client, orgId, actor, control.project || '*', ['owner'], control.project == null);
|
|
243
|
+
const policy = (await client.query(`SELECT p.row FROM dispatcher_policies p JOIN dispatcher_authority_state s
|
|
244
|
+
ON s.org_id=p.org_id AND s.policy_version=p.version WHERE p.org_id=$1`, [orgId])).rows[0]?.row;
|
|
245
|
+
if (policy && Object.entries(policy.modeByProject).some(([project, mode]) => mode === 'admit' && (control.project == null || project === control.project))) {
|
|
246
|
+
const activated = (await records(client, orgId, 'policy-activated')).filter(r => r.version === policy.version).at(-1);
|
|
247
|
+
if (!activated) reject('promotion_reapproval_required', 403);
|
|
248
|
+
const approval = await service.evidence(client, orgId, 'promotion', activated.approvalId);
|
|
249
|
+
await service.checkApproval(client, orgId, approval, activated.approvalId);
|
|
250
|
+
if (approval.policyHash !== policy.hash) reject('promotion_unapproved', 403);
|
|
251
|
+
}
|
|
252
|
+
await client.query(`INSERT INTO dispatcher_control VALUES($1,$2,false,$3)
|
|
253
|
+
ON CONFLICT(org_id,scope) DO UPDATE SET enabled=false,row=EXCLUDED.row`,
|
|
254
|
+
[orgId, control.project || '*', { ...control, actor: actor.pubkey, atMs: clock() }]);
|
|
255
|
+
await audit(client, orgId, 'kill-control', control, actor);
|
|
256
|
+
return { enabled: false, stopped: 0 };
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
async checkApproval(client, orgId, approval, approvalId) {
|
|
260
|
+
const epoch = safetyEpoch(await records(client, orgId, 'rollout-drill'));
|
|
261
|
+
const approvals = await records(client, orgId, 'rollout-approved');
|
|
262
|
+
const registered = approvals.find(r => r.approvalId === approvalId && r.approvalHash === canonicalHash(approval) && r.safetyEpoch === epoch);
|
|
263
|
+
if (!registered) reject('promotion_reapproval_required', 403);
|
|
264
|
+
return validateRolloutApproval(client, orgId, approval);
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const median = values => {
|
|
270
|
+
if (!values.length) return null;
|
|
271
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
272
|
+
const middle = Math.floor(sorted.length / 2);
|
|
273
|
+
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
274
|
+
};
|
|
275
|
+
function cost(attempt) {
|
|
276
|
+
if (!attempt.usage.length) return null;
|
|
277
|
+
const usage = resolveUsage(attempt.usage.reduce((register, event) => ingestEvent(register, event).register, newRegister()));
|
|
278
|
+
let amount = 0;
|
|
279
|
+
for (const request of Object.values(usage.requests)) {
|
|
280
|
+
const dollars = Object.values(request.windows).filter(w => w.unit === 'usdMicros');
|
|
281
|
+
if (!dollars.length || dollars.some(w => w.unbounded || w.unknown || w.resolved == null)) return null;
|
|
282
|
+
amount += Math.max(...dollars.map(w => w.resolved));
|
|
283
|
+
}
|
|
284
|
+
return amount;
|
|
285
|
+
}
|
|
286
|
+
export function acceptedCohort(rows, { fromMs, throughMs }) {
|
|
287
|
+
const grouped = new Map();
|
|
288
|
+
for (const { attempt, card, policy } of rows) {
|
|
289
|
+
if (attempt.createdAtMs > throughMs) continue;
|
|
290
|
+
const id = key(attempt);
|
|
291
|
+
const previous = grouped.get(id) || { project: attempt.project, card: attempt.card, readyAtMs: null,
|
|
292
|
+
acceptedAtMs: null, attempts: 0, failures: 0, cancelled: 0, bounces: 0, costMicros: 0, unknownCost: false,
|
|
293
|
+
stratum: card ? { kind: card.kind, difficulty: card.difficulty, size: card.size, effectClass: card.effectClass,
|
|
294
|
+
machine: policy.placementByKind[card.kind] || policy.placementByKind.default || null } : null };
|
|
295
|
+
if (card?.readySinceMs != null) previous.readyAtMs = Math.min(previous.readyAtMs ?? Infinity, card.readySinceMs);
|
|
296
|
+
previous.attempts++;
|
|
297
|
+
if (attempt.endedAtMs != null && attempt.endedAtMs <= throughMs && (attempt.state === 'failed' || attempt.acceptance?.result === 'fail')) previous.failures++;
|
|
298
|
+
if (attempt.state === 'cancelled' && attempt.endedAtMs != null && attempt.endedAtMs <= throughMs) previous.cancelled++;
|
|
299
|
+
if (attempt.acceptance?.result === 'fail' && attempt.acceptance.atMs <= throughMs) previous.bounces++;
|
|
300
|
+
const amount = cost({ ...attempt, usage: attempt.usage.filter(e => e.receivedAtMs <= throughMs) });
|
|
301
|
+
if (amount == null) previous.unknownCost = true;
|
|
302
|
+
else previous.costMicros += amount;
|
|
303
|
+
if (attempt.state === 'accepted' && attempt.acceptance?.result === 'pass' && attempt.acceptance.atMs <= throughMs) {
|
|
304
|
+
previous.acceptedAtMs = Math.min(previous.acceptedAtMs ?? Infinity, attempt.acceptance.atMs);
|
|
305
|
+
}
|
|
306
|
+
grouped.set(id, previous);
|
|
307
|
+
}
|
|
308
|
+
const cards = [...grouped.values()].filter(c => c.readyAtMs != null && c.readyAtMs >= fromMs && c.readyAtMs < throughMs)
|
|
309
|
+
.map(c => ({ ...c, costMicros: c.unknownCost ? null : c.costMicros,
|
|
310
|
+
cycleMs: c.acceptedAtMs == null ? null : c.acceptedAtMs - c.readyAtMs }));
|
|
311
|
+
const groups = new Map();
|
|
312
|
+
for (const card of cards) {
|
|
313
|
+
const stratumKey = canonicalJson(card.stratum);
|
|
314
|
+
const group = groups.get(stratumKey) || [];
|
|
315
|
+
group.push(card);
|
|
316
|
+
groups.set(stratumKey, group);
|
|
317
|
+
}
|
|
318
|
+
return { fromMs, throughMs, cards, admittedCards: cards.length,
|
|
319
|
+
pendingCards: cards.filter(c => c.acceptedAtMs == null).length,
|
|
320
|
+
unknownReadyCards: [...grouped.values()].filter(c => c.readyAtMs == null).length,
|
|
321
|
+
strata: [...groups].map(([id, entries]) => {
|
|
322
|
+
const accepted = entries.filter(c => c.acceptedAtMs != null);
|
|
323
|
+
const attempts = entries.reduce((n, c) => n + c.attempts, 0);
|
|
324
|
+
return { id, stratum: entries[0].stratum, admitted: entries.length, accepted: accepted.length,
|
|
325
|
+
pending: entries.length - accepted.length, attempts,
|
|
326
|
+
failures: entries.reduce((n, c) => n + c.failures, 0), cancelled: entries.reduce((n, c) => n + c.cancelled, 0),
|
|
327
|
+
bounces: entries.reduce((n, c) => n + c.bounces, 0),
|
|
328
|
+
medianCycleMs: median(accepted.map(c => c.cycleMs)),
|
|
329
|
+
costPerAcceptedMicros: accepted.length && entries.every(c => c.costMicros != null)
|
|
330
|
+
? entries.reduce((n, c) => n + c.costMicros, 0) / accepted.length : null,
|
|
331
|
+
batchWallMs: accepted.length === entries.length ? Math.max(...accepted.map(c => c.acceptedAtMs)) - Math.min(...entries.map(c => c.readyAtMs)) : null };
|
|
332
|
+
}) };
|
|
333
|
+
}
|
|
334
|
+
export function compareCohorts(baseline, trial) {
|
|
335
|
+
return trial.strata.map(group => {
|
|
336
|
+
const previous = baseline?.strata.find(b => b.id === group.id);
|
|
337
|
+
const established = previous && group.stratum != null && previous.accepted >= 20 && group.accepted >= 20
|
|
338
|
+
&& previous.medianCycleMs > 0 && group.medianCycleMs != null
|
|
339
|
+
&& previous.costPerAcceptedMicros != null && group.costPerAcceptedMicros != null;
|
|
340
|
+
return { stratum: group.stratum, baseline: previous || null, trial: group,
|
|
341
|
+
matchedAccepted: previous ? Math.min(previous.accepted, group.accepted) : 0,
|
|
342
|
+
status: established ? 'measured' : 'not-established',
|
|
343
|
+
cycleTargetMet: established ? group.medianCycleMs <= previous.medianCycleMs * 0.6 : null,
|
|
344
|
+
costTargetMet: established ? group.costPerAcceptedMicros <= previous.costPerAcceptedMicros : null,
|
|
345
|
+
failureTargetMet: established ? group.failures / group.attempts <= previous.failures / previous.attempts : null,
|
|
346
|
+
bounceTargetMet: established ? group.bounces / group.attempts <= previous.bounces / previous.attempts : null };
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
async function storedCohort(client, orgId, project, period) {
|
|
350
|
+
const rows = (await client.query(`SELECT a.row AS attempt,s.row AS snapshot,p.row AS policy FROM dispatcher_attempts a
|
|
351
|
+
JOIN dispatcher_decisions d ON d.org_id=a.org_id AND d.id=a.decision_id
|
|
352
|
+
JOIN dispatcher_snapshots s ON s.org_id=d.org_id AND s.id=d.snapshot_id
|
|
353
|
+
JOIN dispatcher_policies p ON p.org_id=s.org_id AND p.version=s.policy_version
|
|
354
|
+
WHERE a.org_id=$1 AND a.project=$2`, [orgId, project])).rows;
|
|
355
|
+
return acceptedCohort(rows.map(row => ({ attempt: row.attempt, policy: row.policy,
|
|
356
|
+
card: row.snapshot.readyQueue.find(c => key(c) === key(row.attempt)) })), period);
|
|
357
|
+
}
|
|
@@ -77,6 +77,7 @@ export const CandidateScoreSchema = CandidateSchema.extend({
|
|
|
77
77
|
export const WorkCardSchema = object({
|
|
78
78
|
project: text, card: positive, revision: integer, kind: text, difficulty, subsystem: text,
|
|
79
79
|
size: z.enum(['s', 'm', 'l']), deps: list(object({ project: text, card: positive })),
|
|
80
|
+
depsBasis: z.literal('board').optional(),
|
|
80
81
|
resources: list(ResourceRequestSchema), needs: strings, features: strings,
|
|
81
82
|
effectClass: z.enum(['read-only', 'workspace', 'external']), artifactKind,
|
|
82
83
|
drillSpecId: text, featureRegistryHash: text, drill: text, readySinceMs: nullable(integer),
|
|
@@ -77,7 +77,7 @@ export async function currentEvidence(client, orgId, nowMs) {
|
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
// All inputs are read under the admission lock. Empty observations stay empty, never funded defaults.
|
|
80
|
-
export async function buildStoredSnapshot(client, orgId, nowMs) {
|
|
80
|
+
export async function buildStoredSnapshot(client, orgId, nowMs, degraded = []) {
|
|
81
81
|
const state = (await client.query('SELECT * FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
82
82
|
const policyRow = state?.policy_version && (await client.query(
|
|
83
83
|
'SELECT row FROM dispatcher_policies WHERE org_id=$1 AND version=$2', [orgId, state.policy_version])).rows[0];
|
|
@@ -98,10 +98,14 @@ export async function buildStoredSnapshot(client, orgId, nowMs) {
|
|
|
98
98
|
const readyQueue = [];
|
|
99
99
|
for (const record of cards) {
|
|
100
100
|
const card = WorkCardSchema.parse(record.row);
|
|
101
|
-
const
|
|
102
|
-
|
|
101
|
+
const board = card.depsBasis === 'board';
|
|
102
|
+
const ready = board
|
|
103
|
+
? record.status === 'todo' && policy.modeByProject[card.project] === 'shadow'
|
|
104
|
+
&& record.ready_since_ms != null
|
|
105
|
+
: ['todo', 'doing', 'testing'].includes(record.status)
|
|
106
|
+
&& card.deps.every(dep => dependencies.some(d => d.project === dep.project && d.card === dep.card));
|
|
103
107
|
const readySinceMs = ready ? record.ready_since_ms == null ? nowMs : Number(record.ready_since_ms) : null;
|
|
104
|
-
if (readySinceMs !== (record.ready_since_ms == null ? null : Number(record.ready_since_ms))) {
|
|
108
|
+
if (!board && readySinceMs !== (record.ready_since_ms == null ? null : Number(record.ready_since_ms))) {
|
|
105
109
|
await client.query('UPDATE dispatcher_cards SET ready_since_ms=$4 WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
106
110
|
[orgId, card.project, card.card, readySinceMs]);
|
|
107
111
|
}
|
|
@@ -116,7 +120,7 @@ export async function buildStoredSnapshot(client, orgId, nowMs) {
|
|
|
116
120
|
claims: (await client.query('SELECT row FROM dispatcher_claims WHERE org_id=$1', [orgId])).rows.map(r => r.row),
|
|
117
121
|
fitness: values('fitness'), projectScheduling: values('projectSchedule'), readyQueue,
|
|
118
122
|
schedulingCounters: scheduling, acceptedDependencies: dependencies,
|
|
119
|
-
degraded: ['account', 'machine', 'seat', 'model'].filter(kind => !values(kind).length).map(kind => `${kind}_unknown`) });
|
|
123
|
+
degraded: [...degraded, ...['account', 'machine', 'seat', 'model'].filter(kind => !values(kind).length).map(kind => `${kind}_unknown`)] });
|
|
120
124
|
await client.query(`INSERT INTO dispatcher_snapshots VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(org_id,id) DO NOTHING`,
|
|
121
125
|
[orgId, snapshot.id, snapshot.hash, policy.version, nowMs, snapshot]);
|
|
122
126
|
return { snapshot, policy };
|
package/lib/dispatcher/store.mjs
CHANGED
|
@@ -185,6 +185,21 @@ CREATE TABLE IF NOT EXISTS dispatcher_idempotency (
|
|
|
185
185
|
PRIMARY KEY(org_id, project, route, key)
|
|
186
186
|
);
|
|
187
187
|
CREATE UNIQUE INDEX IF NOT EXISTS identities_org_pubkey ON identities(org_id, pubkey);
|
|
188
|
+
CREATE TABLE IF NOT EXISTS dispatcher_bridge_grants (
|
|
189
|
+
org_id TEXT NOT NULL, grant_id TEXT NOT NULL, approved_by TEXT NOT NULL,
|
|
190
|
+
expires_at_ms BIGINT, revoked_at_ms BIGINT, row JSONB NOT NULL,
|
|
191
|
+
PRIMARY KEY(org_id, grant_id),
|
|
192
|
+
FOREIGN KEY(org_id, approved_by) REFERENCES identities(org_id, pubkey)
|
|
193
|
+
);
|
|
194
|
+
CREATE TABLE IF NOT EXISTS dispatcher_evidence (
|
|
195
|
+
org_id TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, revision BIGINT NOT NULL CHECK(revision>0),
|
|
196
|
+
source TEXT NOT NULL, source_ref TEXT NOT NULL, observed_at_ms BIGINT NOT NULL,
|
|
197
|
+
expires_at_ms BIGINT NOT NULL, registered_by TEXT NOT NULL, registered_at_ms BIGINT NOT NULL,
|
|
198
|
+
hash TEXT NOT NULL, row JSONB NOT NULL, PRIMARY KEY(org_id,kind,id,revision),
|
|
199
|
+
FOREIGN KEY(org_id,registered_by) REFERENCES identities(org_id,pubkey),
|
|
200
|
+
CHECK(expires_at_ms>observed_at_ms)
|
|
201
|
+
);
|
|
202
|
+
ALTER TABLE dispatcher_evidence ADD COLUMN IF NOT EXISTS grant_id TEXT;
|
|
188
203
|
CREATE TABLE IF NOT EXISTS dispatcher_verifier_grants (
|
|
189
204
|
org_id TEXT NOT NULL, id TEXT NOT NULL, identity_id TEXT NOT NULL,
|
|
190
205
|
project TEXT NOT NULL, machine TEXT NOT NULL, allowed_drill_spec_ids JSONB NOT NULL,
|