trantor 0.18.148 → 0.18.149
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/bin/crew/state.mjs +1 -1
- package/bin/crew-runner.mjs +4 -2
- package/bin/docker-seat.mjs +33 -0
- package/bin/heavy-gate-shim/docker +2 -0
- package/bin/migrate-dispatcher.mjs +50 -0
- package/hub/auth.mjs +3 -3
- package/hub/routes/cards.mjs +13 -1
- package/hub/routes/dispatcher-operations.mjs +122 -0
- package/hub/routes/dispatcher.mjs +18 -9
- package/hub/store.mjs +20 -0
- package/hub.mjs +16 -1
- package/kimi.plugin.json +1 -1
- package/lib/dispatcher/admission.mjs +15 -3
- package/lib/dispatcher/operations.mjs +401 -0
- package/lib/dispatcher/preflight.mjs +2 -0
- package/lib/dispatcher/snapshot.mjs +72 -1
- package/lib/dispatcher/verifier.mjs +246 -0
- package/lib/docker-janitor.mjs +24 -14
- package/lib/store-contract.mjs +57 -0
- package/lib/store-pg.mjs +38 -3
- package/package.json +1 -1
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
|
|
3
|
+
ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
|
|
4
|
+
import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
|
|
5
|
+
RepairAuthoritySchema, BindingSettlementSchema, ReplacementAuthoritySchema, requireIdentity,
|
|
6
|
+
storedScopeAllows, reject } from './admission.mjs';
|
|
7
|
+
import { createExecutor, executionRows } from './executor.mjs';
|
|
8
|
+
import { canonicalHash, canonicalJson, currentEvidence, buildStoredSnapshot, verifySnapshot, projectSnapshot } from './snapshot.mjs';
|
|
9
|
+
import { verifyPolicy } from './policy.mjs';
|
|
10
|
+
import { CREW_ADAPTER_VERSION } from './harness/contract.mjs';
|
|
11
|
+
import { taskFromRow } from '../store-pg.mjs';
|
|
12
|
+
import { fenceExecution } from './executor.mjs';
|
|
13
|
+
import { createVerifier } from './verifier.mjs';
|
|
14
|
+
import { plan } from './planner.mjs';
|
|
15
|
+
import { newRegister, ingestEvent, resolveUsage } from './spend.mjs';
|
|
16
|
+
import { MINUTE_MS, publishRates, forecastToReset, initialPacingState, pacingHysteresis,
|
|
17
|
+
lowBalanceWarning, weeklyProposal, weeklyRunMs, isoWeekOf, evidenceDates, dailyTotalsFromReceipts } from './forecast.mjs';
|
|
18
|
+
|
|
19
|
+
const text = z.string().min(1).max(8192);
|
|
20
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
21
|
+
const LaunchAuthoritySchema = AdmissionAuthoritySchema.pick({ adapter: true, launch: true,
|
|
22
|
+
producerIdentityIds: true, orchestrator: true }).extend({ project: text, card: integer.min(1),
|
|
23
|
+
cardRevision: integer, candidateId: text });
|
|
24
|
+
export const DrillSpecSchema = z.strictObject({ id: text, project: text, kind: z.enum(['manual', 'command']),
|
|
25
|
+
registryHash: text, probeIds: z.array(text), machine: text, argv: z.array(text),
|
|
26
|
+
environment: z.record(text, text), timeoutMs: integer.min(1), evidenceRequirements: z.array(text) });
|
|
27
|
+
export const EvidenceSchemas = {
|
|
28
|
+
account: AccountSchema, machine: MachineSchema, seat: SeatSchema, model: ModelEvidenceSchema,
|
|
29
|
+
fitness: FitnessCellSchema, projectSchedule: ProjectScheduleSchema, ledger: WindowLedgerSchema,
|
|
30
|
+
launch: LaunchAuthoritySchema, repair: RepairAuthoritySchema.omit({ collectorAuthorized: true, policyVersion: true }),
|
|
31
|
+
settlement: BindingSettlementSchema, replacement: ReplacementAuthoritySchema,
|
|
32
|
+
drill: DrillSpecSchema,
|
|
33
|
+
promotion: z.strictObject({ policyHash: text, result: z.literal('pass'), approvalId: text,
|
|
34
|
+
drills: z.array(z.strictObject({ id: text, result: z.literal('pass'), evidenceRef: text })) }),
|
|
35
|
+
};
|
|
36
|
+
const sources = { account: ['balances'], ledger: ['balances', 'attempt-receipt'], machine: ['machine-beat'],
|
|
37
|
+
seat: ['machine-beat'], model: ['machine-beat'], fitness: ['acceptance'], projectSchedule: ['owner'],
|
|
38
|
+
launch: ['adapter-record'], repair: ['collector'], settlement: ['adapter-record'],
|
|
39
|
+
replacement: ['adapter-record'], drill: ['owner'], promotion: ['owner'] };
|
|
40
|
+
export const RegisterEvidenceSchema = z.strictObject({ kind: z.enum(Object.keys(EvidenceSchemas)), id: text,
|
|
41
|
+
expectedRevision: integer, source: z.enum(['balances', 'attempt-receipt', 'machine-beat', 'adapter-record', 'acceptance', 'collector', 'owner']),
|
|
42
|
+
sourceRef: text, observedAtMs: integer, expiresAtMs: integer, record: z.json() });
|
|
43
|
+
|
|
44
|
+
export async function requireRole(client, orgId, actor, project, roles, wildcardOnly = false) {
|
|
45
|
+
const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
|
|
46
|
+
if (!identity || identity.revoked_at != null || !storedScopeAllows(identity, project, roles, wildcardOnly)) reject('permission_denied', 403);
|
|
47
|
+
return identity;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '' }) {
|
|
51
|
+
const store = durableStore.createDispatcherStore();
|
|
52
|
+
const evidence = async (client, orgId, kind, id) => {
|
|
53
|
+
const record = (await currentEvidence(client, orgId, clock())).find(e => e.kind === kind && e.id === id);
|
|
54
|
+
if (!record) reject(`${kind}_unknown`, 503);
|
|
55
|
+
return EvidenceSchemas[kind].parse(record.row);
|
|
56
|
+
};
|
|
57
|
+
const readAdvice = async (client, { orgId, request }) => {
|
|
58
|
+
if (request.snapshotId) {
|
|
59
|
+
const snapshotRow = (await client.query('SELECT row FROM dispatcher_snapshots WHERE org_id=$1 AND id=$2', [orgId, request.snapshotId])).rows[0];
|
|
60
|
+
if (!snapshotRow) reject('snapshot_gone', 410);
|
|
61
|
+
const snapshot = verifySnapshot(snapshotRow.row);
|
|
62
|
+
const policy = verifyPolicy((await client.query('SELECT row FROM dispatcher_policies WHERE org_id=$1 AND version=$2',
|
|
63
|
+
[orgId, snapshot.policyVersion])).rows[0]?.row);
|
|
64
|
+
return { snapshot, policy };
|
|
65
|
+
}
|
|
66
|
+
return buildStoredSnapshot(client, orgId, clock());
|
|
67
|
+
};
|
|
68
|
+
const readAuthority = async (client, { orgId, request }) => {
|
|
69
|
+
const authority = await buildStoredSnapshot(client, orgId, clock());
|
|
70
|
+
const card = authority.snapshot.readyQueue.find(c => c.project === request.project && c.card === request.card);
|
|
71
|
+
if (!card) reject('card_stale');
|
|
72
|
+
const records = await currentEvidence(client, orgId, clock());
|
|
73
|
+
const decision = request.decisionId ? (await client.query('SELECT row FROM dispatcher_decisions WHERE org_id=$1 AND id=$2 AND project=$3',
|
|
74
|
+
[orgId, request.decisionId, request.project])).rows[0]?.row : null;
|
|
75
|
+
const active = (await client.query(`SELECT row FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND card=$3
|
|
76
|
+
AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId, request.project, request.card])).rows[0]?.row;
|
|
77
|
+
const candidate = decision?.assignments.find(a => a.project === card.project && a.card === card.card)?.candidate || active?.candidate;
|
|
78
|
+
if (!candidate) reject('decision_stale');
|
|
79
|
+
if (!adapters.has(candidate.machine)) reject('adapter_unavailable', 503);
|
|
80
|
+
const launchRecord = records.filter(e => e.kind === 'launch').map(e => LaunchAuthoritySchema.parse(e.row))
|
|
81
|
+
.find(e => e.project === card.project && e.card === card.card && e.cardRevision === card.revision && e.candidateId === candidate.id);
|
|
82
|
+
if (!launchRecord || launchRecord.adapter.version !== CREW_ADAPTER_VERSION) reject('launch_unknown', 503);
|
|
83
|
+
const binding = (await client.query('SELECT account_id,frozen,row FROM dispatcher_account_bindings WHERE org_id=$1 AND seat_id=$2',
|
|
84
|
+
[orgId, candidate.seatId])).rows[0];
|
|
85
|
+
if (!binding) reject('account_binding_changed');
|
|
86
|
+
return AdmissionAuthoritySchema.parse({ ...authority, card,
|
|
87
|
+
binding: { accountId: binding.account_id, revision: binding.row.bindingRevision, frozen: binding.frozen },
|
|
88
|
+
windowLedgers: records.filter(e => e.kind === 'ledger').map(e => WindowLedgerSchema.parse(e.row)),
|
|
89
|
+
adapter: launchRecord.adapter, launch: launchRecord.launch,
|
|
90
|
+
producerIdentityIds: launchRecord.producerIdentityIds, orchestrator: launchRecord.orchestrator });
|
|
91
|
+
};
|
|
92
|
+
const readRepairAuthority = async (client, { orgId, seatId, request }) => {
|
|
93
|
+
const record = await evidence(client, orgId, 'repair', request.identityEvidenceId);
|
|
94
|
+
if (record.seat.seatId !== seatId) reject('evidence_unverified', 422);
|
|
95
|
+
const collector = (await client.query(`SELECT machine FROM dispatcher_collectors
|
|
96
|
+
WHERE org_id=$1 AND pubkey=$2 AND revoked_at_ms IS NULL`, [orgId, record.evidence.collectorPubkey])).rows[0];
|
|
97
|
+
const current = (await client.query('SELECT policy_version FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
98
|
+
return RepairAuthoritySchema.parse({ ...record, policyVersion: current?.policy_version,
|
|
99
|
+
collectorAuthorized: collector?.machine === record.seat.machine });
|
|
100
|
+
};
|
|
101
|
+
const readSettlement = async (client, { orgId, settlementId }) => {
|
|
102
|
+
const settlement = await evidence(client, orgId, 'settlement', settlementId);
|
|
103
|
+
const lease = (await client.query('SELECT attempt_id FROM dispatcher_leases WHERE org_id=$1 AND id=$2', [orgId, settlement.leaseId])).rows[0];
|
|
104
|
+
if (!lease) reject('evidence_unverified', 422);
|
|
105
|
+
const rows = await executionRows(client, orgId, lease.attempt_id);
|
|
106
|
+
if (!rows.generation.stopReceipt?.stopProof || !rows.generation.usageSettled) reject('evidence_unverified', 422);
|
|
107
|
+
for (const event of settlement.events) {
|
|
108
|
+
const stored = (await client.query('SELECT row FROM dispatcher_usage WHERE org_id=$1 AND event_id=$2', [orgId, event.id])).rows[0]?.row;
|
|
109
|
+
if (!stored || canonicalJson(stored) !== canonicalJson(event)) reject('evidence_unverified', 422);
|
|
110
|
+
}
|
|
111
|
+
return { verified: true, settlement };
|
|
112
|
+
};
|
|
113
|
+
const readReplacement = async (client, { orgId, previousAttemptId, candidate }) => {
|
|
114
|
+
const record = await evidence(client, orgId, 'replacement', previousAttemptId);
|
|
115
|
+
const rows = await executionRows(client, orgId, previousAttemptId);
|
|
116
|
+
if (!rows.generation.stopProof || !rows.generation.usageSettled || !rows.generation.stopReceipt?.recovery
|
|
117
|
+
|| rows.generation.checkpointRef !== record.checkpointRef || record.targetMachine !== candidate.machine) reject('handoff_unresolved');
|
|
118
|
+
return record;
|
|
119
|
+
};
|
|
120
|
+
const admission = createAdmission({ store, readAuthority, readReplacement, clock });
|
|
121
|
+
const executor = createExecutor({ store, readAuthority, clock, adapterFor: candidate => {
|
|
122
|
+
const adapter = adapters.get(candidate.machine);
|
|
123
|
+
if (!adapter) reject('adapter_unavailable', 503);
|
|
124
|
+
return adapter;
|
|
125
|
+
} });
|
|
126
|
+
const finance = createFinancialOperations({ store, readAuthority, readRepairAuthority, readSettlement, clock });
|
|
127
|
+
const verifier = createVerifier({ store, evidence, clock });
|
|
128
|
+
const service = {
|
|
129
|
+
store, admission, executor, finance, verifier, readAuthority, readAdvice, readRepairAuthority, readSettlement, readReplacement, evidence,
|
|
130
|
+
orgId(auth) { return auth?.identity?.orgId && auth.identity.orgId !== configuredOrg ? null : configuredOrg; },
|
|
131
|
+
projectDecision(decision, auth) {
|
|
132
|
+
const identity = auth.identity;
|
|
133
|
+
const assignments = decision.assignments.filter(a => storedScopeAllows(identity, a.project, ['read', 'write', 'approver', 'owner']));
|
|
134
|
+
const waiting = decision.waiting.filter(a => storedScopeAllows(identity, a.project, ['read', 'write', 'approver', 'owner']));
|
|
135
|
+
const visible = { ...decision, assignments, waiting, explanation: [], expectedWallMs: null,
|
|
136
|
+
expectedSpend: assignments.flatMap(a => a.estimates), snapshotHash: canonicalHash({ snapshotId: decision.snapshotId, assignments, waiting }) };
|
|
137
|
+
return visible;
|
|
138
|
+
},
|
|
139
|
+
async registerCard(orgId, input, actor) {
|
|
140
|
+
const request = z.strictObject({ card: WorkCardSchema, expectedRevision: integer.nullable() }).parse(input);
|
|
141
|
+
return store.locked(orgId, async client => {
|
|
142
|
+
await requireIdentity(client, orgId, actor, request.card.project);
|
|
143
|
+
const task = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND id=$2 FOR UPDATE', [orgId, request.card.card])).rows[0];
|
|
144
|
+
if (!task || task.project !== request.card.project) reject('card_missing', 404);
|
|
145
|
+
const previous = (await client.query('SELECT revision FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
146
|
+
[orgId, task.project, request.card.card])).rows[0];
|
|
147
|
+
if ((previous ? Number(previous.revision) : null) !== request.expectedRevision) reject('card_stale');
|
|
148
|
+
if (previous) reject('card_already_managed');
|
|
149
|
+
if (request.card.revision !== 0 || request.card.readySinceMs !== null
|
|
150
|
+
|| request.card.difficulty !== task.difficulty || request.card.drill !== task.extra?.drill
|
|
151
|
+
|| canonicalJson(request.card.deps) !== canonicalJson((task.deps || []).map(card => ({ project: task.project, card })))) reject('card_stale');
|
|
152
|
+
await client.query('INSERT INTO dispatcher_cards VALUES($1,$2,$3,0,$4,NULL,$5)',
|
|
153
|
+
[orgId, task.project, request.card.card, task.status, request.card]);
|
|
154
|
+
await client.query("SELECT set_config('trantor.dispatcher_card_write','on',true)");
|
|
155
|
+
await client.query("UPDATE tasks SET extra=extra || '{\"dispatcherRevision\":0}'::jsonb WHERE org_id=$1 AND id=$2", [orgId, request.card.card]);
|
|
156
|
+
await client.query('UPDATE dispatcher_authority_state SET revision=revision+1 WHERE org_id=$1', [orgId]);
|
|
157
|
+
await store.audit(client, orgId, { action: 'card-registered', actor: actor.pubkey, atMs: clock(), card: request.card.card });
|
|
158
|
+
return { card: request.card.card, revision: 0 };
|
|
159
|
+
});
|
|
160
|
+
},
|
|
161
|
+
async mutateCard(orgId, input, actor) {
|
|
162
|
+
const request = z.object({ id: integer.min(1), expectedRevision: integer, status: z.enum(['todo','doing','testing','failed','done','blocked','stale']).optional(),
|
|
163
|
+
title: text.optional(), note: text.optional(), by: text.optional(), assignee: text.optional(),
|
|
164
|
+
drill: text.optional(), deps: z.array(integer.min(1)).optional(), difficulty: z.enum(['easy','medium','hard']).optional(),
|
|
165
|
+
executionAttemptId: text.optional(), generation: integer.min(1).optional(), launchToken: text.optional(),
|
|
166
|
+
acceptanceId: text.optional() }).strict().parse(input);
|
|
167
|
+
return store.locked(orgId, async client => {
|
|
168
|
+
const task = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND id=$2 FOR UPDATE', [orgId, request.id])).rows[0];
|
|
169
|
+
if (!task) reject('card_missing', 404);
|
|
170
|
+
await requireIdentity(client, orgId, actor, task.project);
|
|
171
|
+
const managed = (await client.query('SELECT * FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
172
|
+
[orgId, task.project, request.id])).rows[0];
|
|
173
|
+
if (!managed || Number(managed.revision) !== request.expectedRevision) reject('card_stale');
|
|
174
|
+
const active = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND card=$3
|
|
175
|
+
AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId, task.project, request.id])).rows;
|
|
176
|
+
for (const { id } of active) {
|
|
177
|
+
const rows = await executionRows(client, orgId, id);
|
|
178
|
+
if (rows.attempt.producerIdentityIds.includes(actor.pubkey)
|
|
179
|
+
&& (request.executionAttemptId !== id || request.generation !== rows.attempt.generation
|
|
180
|
+
|| request.launchToken !== rows.attempt.launchToken || rows.fenced)) reject('attempt_conflict');
|
|
181
|
+
}
|
|
182
|
+
if (request.executionAttemptId && !active.some(a => a.id === request.executionAttemptId)) reject('attempt_conflict');
|
|
183
|
+
if (request.status === 'done') {
|
|
184
|
+
const acceptance = (await client.query(`SELECT a.row FROM dispatcher_acceptances a JOIN dispatcher_attempts t
|
|
185
|
+
ON t.org_id=a.org_id AND t.id=a.attempt_id JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id
|
|
186
|
+
WHERE a.org_id=$1 AND a.id=$2 AND t.project=$3 AND t.card=$4 AND j.state='passed' AND t.state='accepted'`,
|
|
187
|
+
[orgId, request.acceptanceId || '', task.project, request.id])).rows[0]?.row;
|
|
188
|
+
if (!acceptance || acceptance.result !== 'pass' || acceptance.cardRevision !== request.expectedRevision) reject('acceptance_required');
|
|
189
|
+
}
|
|
190
|
+
const card = WorkCardSchema.parse(managed.row);
|
|
191
|
+
if (request.drill !== undefined) card.drill = request.drill;
|
|
192
|
+
if (request.difficulty !== undefined) card.difficulty = request.difficulty;
|
|
193
|
+
if (request.deps !== undefined) card.deps = [...new Set(request.deps)].map(card => ({ project: task.project, card }));
|
|
194
|
+
const relevant = canonicalJson({ ...card, revision: 0, readySinceMs: null }) !== canonicalJson({ ...managed.row, revision: 0, readySinceMs: null })
|
|
195
|
+
|| request.assignee !== undefined && request.assignee !== task.assignee;
|
|
196
|
+
if (relevant) {
|
|
197
|
+
card.revision++;
|
|
198
|
+
for (const { id } of active) await fenceExecution(client, orgId, await executionRows(client, orgId, id), 'card-changed', clock());
|
|
199
|
+
}
|
|
200
|
+
const status = request.status || task.status;
|
|
201
|
+
const readySinceMs = relevant || !['todo','doing','testing'].includes(status) ? null : managed.ready_since_ms == null ? null : Number(managed.ready_since_ms);
|
|
202
|
+
card.readySinceMs = readySinceMs;
|
|
203
|
+
const extra = { ...task.extra, dispatcherRevision: card.revision, drill: card.drill };
|
|
204
|
+
if (request.note) extra.log = [...extra.log || [], { by: actor.pubkey, ts: clock(), text: request.note }].slice(-40);
|
|
205
|
+
if (request.acceptanceId) extra.acceptanceId = request.acceptanceId;
|
|
206
|
+
await client.query(`UPDATE dispatcher_cards SET revision=$4,status=$5,ready_since_ms=$6,row=$7 WHERE org_id=$1 AND project=$2 AND card=$3`,
|
|
207
|
+
[orgId, task.project, request.id, card.revision, status, readySinceMs, card]);
|
|
208
|
+
await client.query("SELECT set_config('trantor.dispatcher_card_write','on',true)");
|
|
209
|
+
const changed = (await client.query(`UPDATE tasks SET title=$3,status=$4,assignee=$5,difficulty=$6,deps=$7,extra=$8,updated=$9
|
|
210
|
+
WHERE org_id=$1 AND id=$2 RETURNING *`, [orgId, request.id, request.title || task.title, status,
|
|
211
|
+
request.assignee ?? task.assignee, card.difficulty, JSON.stringify(card.deps.map(d => d.card)), extra, clock()])).rows[0];
|
|
212
|
+
await client.query('UPDATE dispatcher_authority_state SET revision=revision+1 WHERE org_id=$1', [orgId]);
|
|
213
|
+
await store.audit(client, orgId, { action: 'card-mutated', actor: actor.pubkey, atMs: clock(), card: request.id, revision: card.revision, status });
|
|
214
|
+
await client.query(`INSERT INTO events(org_id,ts,type,project,by_session,task_id,payload) VALUES($1,$2,$3,$4,$5,$6,$7)`,
|
|
215
|
+
[orgId, clock(), status === task.status ? 'updated' : 'moved', task.project, actor.pubkey, request.id,
|
|
216
|
+
{ from: task.status, to: status, revision: card.revision }]);
|
|
217
|
+
await client.query("SELECT pg_notify('trantor_changes',$1)", [JSON.stringify({ src: source })]);
|
|
218
|
+
return taskFromRow(changed);
|
|
219
|
+
});
|
|
220
|
+
},
|
|
221
|
+
async capacity(orgId, request, actor) {
|
|
222
|
+
return store.locked(orgId, async client => {
|
|
223
|
+
const identity = await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
|
|
224
|
+
const { snapshot } = await readAdvice(client, { orgId, request });
|
|
225
|
+
const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project)))];
|
|
226
|
+
return projectSnapshot(snapshot, projects.filter(p => storedScopeAllows(identity, p, ['read', 'write', 'approver', 'owner'])));
|
|
227
|
+
});
|
|
228
|
+
},
|
|
229
|
+
async pacing(orgId, request, actor) {
|
|
230
|
+
return store.locked(orgId, async client => {
|
|
231
|
+
await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
|
|
232
|
+
const nowMs = clock();
|
|
233
|
+
const minute = Math.floor(nowMs / MINUTE_MS) * MINUTE_MS;
|
|
234
|
+
const records = await currentEvidence(client, orgId, nowMs);
|
|
235
|
+
let authority = null;
|
|
236
|
+
try { authority = await readAdvice(client, { orgId, request: {} }); }
|
|
237
|
+
catch (error) {
|
|
238
|
+
if (!['policy_missing', 'scheduling_missing'].includes(error.code)) throw error;
|
|
239
|
+
}
|
|
240
|
+
const decision = authority ? plan({ ...authority, cards: authority.snapshot.readyQueue }) : null;
|
|
241
|
+
const events = (await client.query('SELECT row FROM dispatcher_usage WHERE org_id=$1', [orgId])).rows.map(r => r.row);
|
|
242
|
+
const leases = (await client.query('SELECT row FROM dispatcher_leases WHERE org_id=$1', [orgId])).rows.map(r => r.row);
|
|
243
|
+
const accounts = [];
|
|
244
|
+
for (const record of records.filter(e => e.kind === 'account')) {
|
|
245
|
+
const account = AccountSchema.parse(record.row);
|
|
246
|
+
const previous = (await client.query(`SELECT row FROM dispatcher_audit WHERE org_id=$1
|
|
247
|
+
AND row->>'action'='pacing-sample' AND row->>'accountId'=$2 ORDER BY at_ms DESC LIMIT 1`,
|
|
248
|
+
[orgId, account.id])).rows[0]?.row;
|
|
249
|
+
const result = pacingAccount({ orgId, account, nowMs, minute, events, leases, authority, decision, previous });
|
|
250
|
+
const sample = { action: 'pacing-sample', accountId: account.id, atMs: minute, result };
|
|
251
|
+
await client.query(`INSERT INTO dispatcher_audit(org_id,id,at_ms,row) VALUES($1,$2,$3,$4)
|
|
252
|
+
ON CONFLICT(org_id,id) DO UPDATE SET row=EXCLUDED.row`,
|
|
253
|
+
[orgId, `pacing:${canonicalHash([account.id, minute])}`, minute, sample]);
|
|
254
|
+
accounts.push(result);
|
|
255
|
+
}
|
|
256
|
+
return { asOfMs: nowMs, accounts };
|
|
257
|
+
});
|
|
258
|
+
},
|
|
259
|
+
async registerEvidence(orgId, input, actor) {
|
|
260
|
+
const request = RegisterEvidenceSchema.parse(input);
|
|
261
|
+
const record = EvidenceSchemas[request.kind].parse(request.record);
|
|
262
|
+
if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
|
|
263
|
+
|| request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
|
|
264
|
+
return store.locked(orgId, async client => {
|
|
265
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
266
|
+
const previous = (await client.query(`SELECT revision,hash FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
|
|
267
|
+
ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
|
|
268
|
+
if (Number(previous?.revision || 0) !== request.expectedRevision) reject('evidence_stale');
|
|
269
|
+
if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
|
|
270
|
+
if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
|
|
271
|
+
const revision = request.expectedRevision + 1;
|
|
272
|
+
await client.query(`INSERT INTO dispatcher_evidence VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)`,
|
|
273
|
+
[orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
|
|
274
|
+
request.expiresAtMs, actor.pubkey, clock(), canonicalHash(record), record]);
|
|
275
|
+
if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
|
|
276
|
+
ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
|
|
277
|
+
[orgId, record.accountId, record.windowId, revision, record]);
|
|
278
|
+
await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
|
|
279
|
+
ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
|
|
280
|
+
await store.audit(client, orgId, { action: 'evidence-registered', actor: actor.pubkey, atMs: clock(),
|
|
281
|
+
kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
|
|
282
|
+
return { id: request.id, revision };
|
|
283
|
+
});
|
|
284
|
+
},
|
|
285
|
+
async registerCollector(orgId, input, actor) {
|
|
286
|
+
const request = z.strictObject({ pubkey: text, machine: text, revoked: z.boolean() }).parse(input);
|
|
287
|
+
return store.locked(orgId, async client => {
|
|
288
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
289
|
+
const identity = (await client.query('SELECT kind,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, request.pubkey])).rows[0];
|
|
290
|
+
if (!identity || identity.revoked_at != null || identity.kind !== 'tool') reject('permission_denied', 403);
|
|
291
|
+
await client.query(`INSERT INTO dispatcher_collectors VALUES($1,$2,$3,$4,$5)
|
|
292
|
+
ON CONFLICT(org_id,pubkey) DO UPDATE SET machine=EXCLUDED.machine,registered_by=EXCLUDED.registered_by,revoked_at_ms=EXCLUDED.revoked_at_ms`,
|
|
293
|
+
[orgId, request.pubkey, request.machine, actor.pubkey, request.revoked ? clock() : null]);
|
|
294
|
+
await store.audit(client, orgId, { action: 'collector-registered', actor: actor.pubkey, atMs: clock(), ...request });
|
|
295
|
+
return request;
|
|
296
|
+
});
|
|
297
|
+
},
|
|
298
|
+
async activatePolicy(orgId, input, actor) {
|
|
299
|
+
const request = z.strictObject({ expectedVersion: text.nullable(), policy: PolicySchema, reason: text, approvalId: text }).parse(input);
|
|
300
|
+
const policy = verifyPolicy(request.policy);
|
|
301
|
+
return store.locked(orgId, async client => {
|
|
302
|
+
await requireIdentity(client, orgId, actor, '', true);
|
|
303
|
+
const current = (await client.query('SELECT policy_version FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
304
|
+
if ((current?.policy_version || null) !== request.expectedVersion) reject('policy_stale');
|
|
305
|
+
if (Object.values(policy.modeByProject).includes('admit')) {
|
|
306
|
+
const approval = await evidence(client, orgId, 'promotion', request.approvalId);
|
|
307
|
+
const required = ['D1','D2','D3','D4','D5','D6','D7','D8','D9','D10','D11','D13','D14','D15','D16','D17','D18','D19','D20','D21','D22','D23','D24','D25'];
|
|
308
|
+
if (approval.policyHash !== policy.hash || required.some(id => !approval.drills.some(d => d.id === id))) reject('promotion_unapproved', 403);
|
|
309
|
+
}
|
|
310
|
+
const previous = (await client.query('SELECT hash FROM dispatcher_policies WHERE org_id=$1 AND version=$2', [orgId, policy.version])).rows[0];
|
|
311
|
+
if (previous && previous.hash !== policy.hash) reject('policy_stale');
|
|
312
|
+
await client.query('INSERT INTO dispatcher_policies VALUES($1,$2,$3,$4) ON CONFLICT(org_id,version) DO NOTHING', [orgId, policy.version, policy.hash, policy]);
|
|
313
|
+
await client.query(`INSERT INTO dispatcher_authority_state VALUES($1,1,$2) ON CONFLICT(org_id)
|
|
314
|
+
DO UPDATE SET revision=dispatcher_authority_state.revision+1,policy_version=EXCLUDED.policy_version`, [orgId, policy.version]);
|
|
315
|
+
await client.query(`INSERT INTO dispatcher_scheduling VALUES($1,0,0,$2) ON CONFLICT(org_id) DO NOTHING`,
|
|
316
|
+
[orgId, { schedulingRevision: 0, admissions: 0, accounts: [] }]);
|
|
317
|
+
await store.audit(client, orgId, { action: 'policy-activated', actor: actor.pubkey, atMs: clock(),
|
|
318
|
+
expectedVersion: request.expectedVersion, version: policy.version, reason: request.reason, approvalId: request.approvalId });
|
|
319
|
+
return { version: policy.version };
|
|
320
|
+
});
|
|
321
|
+
},
|
|
322
|
+
async recover(orgId) {
|
|
323
|
+
const complete = (await store.pool.query(`SELECT completed_at_ms FROM dispatcher_migrations WHERE id='dispatcher-v1'`)).rows[0];
|
|
324
|
+
if (!complete?.completed_at_ms) reject('migration_incomplete', 503);
|
|
325
|
+
const { snapshot, policy } = await store.locked(orgId, client => buildStoredSnapshot(client, orgId, clock()));
|
|
326
|
+
return executor.recover(orgId, { snapshotId: snapshot.id, policyVersion: policy.version });
|
|
327
|
+
},
|
|
328
|
+
async tick() {
|
|
329
|
+
await verifier.reconcile(configuredOrg);
|
|
330
|
+
await finance.expireAsks(configuredOrg);
|
|
331
|
+
await executor.expire(configuredOrg);
|
|
332
|
+
if (adapters.size && store.isReady(configuredOrg)) await executor.runOnce(configuredOrg, `hub:${process.pid}`);
|
|
333
|
+
},
|
|
334
|
+
};
|
|
335
|
+
service.admission = { ...admission, async dispatch(orgId, input, actor) {
|
|
336
|
+
const replay = await store.locked(orgId, async client => {
|
|
337
|
+
await requireIdentity(client, orgId, actor, input.project);
|
|
338
|
+
return (await client.query('SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND idempotency_key=$3',
|
|
339
|
+
[orgId, input.project, input.idempotencyKey])).rows.length > 0;
|
|
340
|
+
});
|
|
341
|
+
if (!replay && !store.isReady(orgId)) await service.recover(orgId);
|
|
342
|
+
return admission.dispatch(orgId, input, actor);
|
|
343
|
+
} };
|
|
344
|
+
return service;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function pacingAccount({ orgId, account, nowMs, minute, events, leases, authority, decision, previous }) {
|
|
348
|
+
const windows = account.windows.filter(w => w.unit === 'usdMicros');
|
|
349
|
+
const daily = windows.filter(w => w.kind === 'daily' && w.startsAtMs != null && w.startsAtMs <= nowMs && w.resetsAtMs > nowMs)
|
|
350
|
+
.sort((a, b) => a.resetsAtMs - b.resetsAtMs)[0];
|
|
351
|
+
const cash = windows.find(w => w.kind === 'prepaid');
|
|
352
|
+
const known = window => account.status === 'verified' && window?.remaining.status === 'ok'
|
|
353
|
+
&& window.remaining.observedAtMs != null && window.remaining.observedAtMs <= nowMs
|
|
354
|
+
&& authority && nowMs - window.remaining.observedAtMs <= authority.policy.balanceTtlMs
|
|
355
|
+
? window.remaining.value : null;
|
|
356
|
+
const remainingMicros = known(daily);
|
|
357
|
+
const cashMicros = known(cash);
|
|
358
|
+
const register = events.filter(e => e.accountId === account.id)
|
|
359
|
+
.reduce((acc, event) => ingestEvent(acc, event).register, newRegister());
|
|
360
|
+
const resolved = resolveUsage(register);
|
|
361
|
+
const receipts = Object.values(resolved.requests).map(entry => {
|
|
362
|
+
const candidates = Object.entries(entry.windows).filter(([, w]) => w.unit === 'usdMicros');
|
|
363
|
+
const selected = candidates.find(([id]) => id.startsWith('daily:UTC:'))
|
|
364
|
+
|| candidates.find(([id]) => id === daily?.id) || candidates.find(([id]) => id === cash?.id);
|
|
365
|
+
const amount = selected?.[1];
|
|
366
|
+
const event = register.events.filter(e => entry.eventIds.includes(e.id))
|
|
367
|
+
.sort((a, b) => b.requestSequence - a.requestSequence)[0];
|
|
368
|
+
return { ts: event?.occurredAtMs ?? null, usdMicros: amount?.resolved ?? null,
|
|
369
|
+
confidence: !amount || amount.unbounded || amount.unknown > 0 ? 'unknown' : 'estimated' };
|
|
370
|
+
});
|
|
371
|
+
const unknownTime = receipts.some(r => r.ts == null);
|
|
372
|
+
const rates = publishRates({ receipts: receipts.filter(r => r.ts != null), nowMs: minute });
|
|
373
|
+
const planned = decision && decision.waiting.length === 0
|
|
374
|
+
? decision.expectedSpend.filter(c => c.accountId === account.id && c.windowId === daily?.id && c.unit === 'usdMicros')
|
|
375
|
+
.reduce((sum, c) => sum + c.estimate, 0) : null;
|
|
376
|
+
const projection = forecastToReset({ nowMs: minute, resetsAtMs: daily?.resetsAtMs ?? null,
|
|
377
|
+
remainingMicros, burnPerHourMicros: unknownTime || rates.ewma15m.perMinuteMicros == null
|
|
378
|
+
? null : rates.ewma15m.perMinuteMicros * 60, plannedSpendMicros: planned });
|
|
379
|
+
let state = previous?.result.pacing || initialPacingState();
|
|
380
|
+
if (previous?.atMs !== minute && previous?.atMs !== minute - MINUTE_MS || !projection.valid) {
|
|
381
|
+
state = { ...state, consecutiveRunsOut: 0, consecutiveSafe: 0 };
|
|
382
|
+
}
|
|
383
|
+
if (projection.valid && previous?.atMs !== minute) state = pacingHysteresis({ state, sample: { ...projection, atMs: minute } }).state;
|
|
384
|
+
const lowBalance = lowBalanceWarning({ nowMs, dailyLimitMicros: daily?.capacity ?? null,
|
|
385
|
+
spentTodayMicros: remainingMicros == null || daily?.capacity == null ? null : Math.max(0, daily.capacity - remainingMicros),
|
|
386
|
+
cashMicros, previous: previous?.result.lowBalance.state });
|
|
387
|
+
// Keep the episode payload readable by every polling client, not just the first reader.
|
|
388
|
+
if (!lowBalance.warning && lowBalance.state.triggerActive) lowBalance.warning = previous?.result.lowBalance.warning ?? null;
|
|
389
|
+
let runAtMs = weeklyRunMs(isoWeekOf(nowMs));
|
|
390
|
+
if (runAtMs > nowMs) runAtMs -= 7 * 86400_000;
|
|
391
|
+
const unresolvedStopLoss = unknownTime || resolved.stopNewCalls || leases.some(l => l.accountId === account.id
|
|
392
|
+
&& ['stop-loss', 'unknown-usage'].includes(l.stopReason) && l.state !== 'released');
|
|
393
|
+
const proposal = cash ? weeklyProposal({ org: orgId, accountId: account.id, runAtMs,
|
|
394
|
+
policyVersion: authority?.policy.version, currentLimitMicros: daily?.capacity ?? null, balanceMicros: cashMicros,
|
|
395
|
+
dailyTotals: dailyTotalsFromReceipts(receipts.filter(r => r.ts != null), { dates: evidenceDates(runAtMs) }),
|
|
396
|
+
unresolvedStopLoss, policy: authority?.policy }) : null;
|
|
397
|
+
return { accountId: account.id, provider: account.provider, resetsAtMs: daily?.resetsAtMs ?? null,
|
|
398
|
+
remainingMicros, balanceMicros: cashMicros, balanceReason: cashMicros == null ? 'cash_unknown' : null,
|
|
399
|
+
pacing: state, forecast: projection.valid ? projection : null, forecastReason: projection.valid ? null : projection.reason,
|
|
400
|
+
lowBalance: { warning: lowBalance.warning, state: lowBalance.state }, proposal };
|
|
401
|
+
}
|
|
@@ -142,6 +142,8 @@ export async function readCapacity({ get, busDir, project, snapshotId = null, no
|
|
|
142
142
|
return { ...r.json, localOnly: false, versioned };
|
|
143
143
|
}
|
|
144
144
|
if (!unavailable(r)) return { refused: true, status: r.status, code: errorCode(r), localOnly: true };
|
|
145
|
+
// #14678: a reachable hub with no planning view (JSON store, auth off: 503/404 dispatch_unavailable) is unversioned, not offline.
|
|
146
|
+
if (!hubDown(r) && errorCode(r) === "dispatch_unavailable") return { versioned: false, localOnly: false, status: r.status, code: "dispatch_unavailable" };
|
|
145
147
|
const cached = path ? readJson(path) : null;
|
|
146
148
|
const base = { localOnly: true, reason: reasonOf(r), dispatchToken: null };
|
|
147
149
|
if (cached?.v !== CACHE_VERSION) return { ...base, sourceAgeMs: null, envelope: null };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import { SnapshotSchema, DecisionSchema, WorkCardSchema } from './schemas.mjs';
|
|
3
|
+
import { SnapshotSchema, DecisionSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
|
|
4
4
|
|
|
5
5
|
const unordered = new Set(['models', 'accounts', 'windows', 'machines', 'seats', 'breakers',
|
|
6
6
|
'claims', 'fitness', 'acceptedDependencies', 'degraded', 'capabilities', 'efforts', 'tools',
|
|
@@ -68,3 +68,74 @@ export function hashDecision(input) {
|
|
|
68
68
|
export function hashCards(cards) {
|
|
69
69
|
return canonicalHash(z.array(WorkCardSchema).max(200).parse(cards));
|
|
70
70
|
}
|
|
71
|
+
|
|
72
|
+
export async function currentEvidence(client, orgId, nowMs) {
|
|
73
|
+
const rows = (await client.query(`SELECT * FROM (
|
|
74
|
+
SELECT DISTINCT ON(kind,id) * FROM dispatcher_evidence WHERE org_id=$1
|
|
75
|
+
ORDER BY kind,id,revision DESC) latest WHERE expires_at_ms>$2 AND observed_at_ms<=$2`, [orgId, nowMs])).rows;
|
|
76
|
+
return rows.filter(record => canonicalHash(record.row) === record.hash);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// All inputs are read under the admission lock. Empty observations stay empty, never funded defaults.
|
|
80
|
+
export async function buildStoredSnapshot(client, orgId, nowMs) {
|
|
81
|
+
const state = (await client.query('SELECT * FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
82
|
+
const policyRow = state?.policy_version && (await client.query(
|
|
83
|
+
'SELECT row FROM dispatcher_policies WHERE org_id=$1 AND version=$2', [orgId, state.policy_version])).rows[0];
|
|
84
|
+
if (!policyRow) throw Object.assign(new Error('policy_missing'), { code: 'policy_missing', status: 503 });
|
|
85
|
+
const policy = PolicySchema.parse(policyRow.row);
|
|
86
|
+
const evidence = await currentEvidence(client, orgId, nowMs);
|
|
87
|
+
const values = kind => evidence.filter(e => e.kind === kind).map(e => e.row);
|
|
88
|
+
const acceptedDependencies = (await client.query(`SELECT a.row FROM dispatcher_acceptances a
|
|
89
|
+
JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id
|
|
90
|
+
WHERE a.org_id=$1 AND j.state='passed'`, [orgId])).rows.map(({ row }) => row);
|
|
91
|
+
const cards = (await client.query('SELECT * FROM dispatcher_cards WHERE org_id=$1 ORDER BY project,card', [orgId])).rows;
|
|
92
|
+
const accepted = cards.filter(card => card.status === 'done').flatMap(card => acceptedDependencies.filter(a => a.cardRevision === Number(card.revision))
|
|
93
|
+
.filter(a => a.attemptId).map(a => ({ card, acceptance: a })));
|
|
94
|
+
const attempts = (await client.query('SELECT row FROM dispatcher_attempts WHERE org_id=$1', [orgId])).rows.map(r => r.row);
|
|
95
|
+
const dependencies = accepted.filter(({ card, acceptance }) => attempts.some(a => a.id === acceptance.attemptId
|
|
96
|
+
&& a.project === card.project && a.card === Number(card.card))).map(({ card, acceptance }) => ({
|
|
97
|
+
project: card.project, card: Number(card.card), revision: Number(card.revision), acceptanceId: acceptance.id }));
|
|
98
|
+
const readyQueue = [];
|
|
99
|
+
for (const record of cards) {
|
|
100
|
+
const card = WorkCardSchema.parse(record.row);
|
|
101
|
+
const ready = ['todo', 'doing', 'testing'].includes(record.status)
|
|
102
|
+
&& card.deps.every(dep => dependencies.some(d => d.project === dep.project && d.card === dep.card));
|
|
103
|
+
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))) {
|
|
105
|
+
await client.query('UPDATE dispatcher_cards SET ready_since_ms=$4 WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
106
|
+
[orgId, card.project, card.card, readySinceMs]);
|
|
107
|
+
}
|
|
108
|
+
if (ready) readyQueue.push({ ...card, readySinceMs });
|
|
109
|
+
}
|
|
110
|
+
const scheduling = (await client.query('SELECT row FROM dispatcher_scheduling WHERE org_id=$1', [orgId])).rows[0]?.row;
|
|
111
|
+
if (!scheduling) throw Object.assign(new Error('scheduling_missing'), { code: 'scheduling_missing', status: 503 });
|
|
112
|
+
const snapshot = createSnapshot({ schemaVersion: 1, asOfMs: nowMs, revision: Number(state.revision),
|
|
113
|
+
policyVersion: policy.version, plannerVersion: policy.plannerVersion,
|
|
114
|
+
models: values('model'), accounts: values('account'), machines: values('machine'), seats: values('seat'),
|
|
115
|
+
breakers: (await client.query('SELECT row FROM dispatcher_breakers WHERE org_id=$1', [orgId])).rows.map(r => r.row),
|
|
116
|
+
claims: (await client.query('SELECT row FROM dispatcher_claims WHERE org_id=$1', [orgId])).rows.map(r => r.row),
|
|
117
|
+
fitness: values('fitness'), projectScheduling: values('projectSchedule'), readyQueue,
|
|
118
|
+
schedulingCounters: scheduling, acceptedDependencies: dependencies,
|
|
119
|
+
degraded: ['account', 'machine', 'seat', 'model'].filter(kind => !values(kind).length).map(kind => `${kind}_unknown`) });
|
|
120
|
+
await client.query(`INSERT INTO dispatcher_snapshots VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(org_id,id) DO NOTHING`,
|
|
121
|
+
[orgId, snapshot.id, snapshot.hash, policy.version, nowMs, snapshot]);
|
|
122
|
+
return { snapshot, policy };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function projectSnapshot(snapshot, readableProjects) {
|
|
126
|
+
const projects = [...new Set(readableProjects)].sort(compare);
|
|
127
|
+
const visible = project => projects.includes(project);
|
|
128
|
+
const payload = { accounts: snapshot.accounts, models: snapshot.models.map(({ invocation: _invocation, liveUse: _liveUse, ...model }) => model),
|
|
129
|
+
machines: snapshot.machines.map(({ id, health, maxSeats, activeSeats }) => ({ id, health, maxSeats, activeSeats })),
|
|
130
|
+
seats: [], claims: [], readyQueue: snapshot.readyQueue.filter(card => visible(card.project))
|
|
131
|
+
.map(card => ({ ...card, deps: card.deps.filter(dep => visible(dep.project)) })),
|
|
132
|
+
projectScheduling: snapshot.projectScheduling.filter(row => visible(row.project)),
|
|
133
|
+
acceptedDependencies: snapshot.acceptedDependencies.filter(row => visible(row.project)), degraded: snapshot.degraded };
|
|
134
|
+
const visibility = { projects, aggregates: ['budgets', 'machine-headroom'], redactionVersion: 1 };
|
|
135
|
+
const hashed = { schemaVersion: 1, projectionVersion: 1, snapshotId: snapshot.id, asOfMs: snapshot.asOfMs,
|
|
136
|
+
policyVersion: snapshot.policyVersion, plannerVersion: snapshot.plannerVersion, visibility, payload };
|
|
137
|
+
const projectionHash = canonicalHash(hashed);
|
|
138
|
+
return { schemaVersion: 1, snapshotId: snapshot.id, snapshotHash: projectionHash, projectionHash,
|
|
139
|
+
hashKind: 'projection', projectionVersion: 1, visibility, asOfMs: snapshot.asOfMs,
|
|
140
|
+
policyVersion: snapshot.policyVersion, localOnly: false, snapshot: payload, degraded: snapshot.degraded };
|
|
141
|
+
}
|