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.
- 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/state.mjs +1 -1
- package/bin/crew-runner.mjs +9 -6
- package/bin/docker-seat.mjs +33 -0
- package/bin/heavy-gate-shim/docker +2 -0
- package/bin/integrate.mjs +38 -9
- package/bin/migrate-dispatcher.mjs +50 -0
- 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 +8 -3
- package/hub/routes/cards.mjs +13 -1
- package/hub/routes/dispatcher-operations.mjs +134 -0
- package/hub/routes/dispatcher.mjs +18 -9
- package/hub/routes/git-policy.mjs +35 -0
- package/hub/startup-config.mjs +14 -0
- package/hub/store.mjs +49 -0
- package/hub.mjs +19 -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 +16 -3
- package/lib/dispatcher/board-bridge.mjs +82 -0
- package/lib/dispatcher/evidence-bridge.mjs +283 -0
- package/lib/dispatcher/operations.mjs +527 -0
- package/lib/dispatcher/planner.mjs +4 -2
- package/lib/dispatcher/preflight.mjs +44 -7
- package/lib/dispatcher/rollout.mjs +357 -0
- package/lib/dispatcher/schemas.mjs +1 -0
- package/lib/dispatcher/snapshot.mjs +76 -1
- package/lib/dispatcher/store.mjs +15 -0
- package/lib/dispatcher/verifier.mjs +246 -0
- package/lib/docker-janitor.mjs +24 -14
- package/lib/git-guard.mjs +181 -0
- package/lib/integrate.mjs +10 -2
- package/lib/store-contract.mjs +63 -0
- package/lib/store-pg.mjs +38 -3
- package/mcp.mjs +4 -5
- package/package.json +3 -3
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { projectBoardCards } from './board-bridge.mjs';
|
|
3
|
+
import { createRolloutOperations, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
|
|
4
|
+
import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
|
|
5
|
+
ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
|
|
6
|
+
import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
|
|
7
|
+
RepairAuthoritySchema, BindingSettlementSchema, ReplacementAuthoritySchema, requireIdentity,
|
|
8
|
+
storedScopeAllows, reject } from './admission.mjs';
|
|
9
|
+
import { createExecutor, executionRows, KillSchema } from './executor.mjs';
|
|
10
|
+
import { canonicalHash, canonicalJson, currentEvidence, buildStoredSnapshot, verifySnapshot, projectSnapshot } from './snapshot.mjs';
|
|
11
|
+
import { verifyPolicy } from './policy.mjs';
|
|
12
|
+
import { CREW_ADAPTER_VERSION } from './harness/contract.mjs';
|
|
13
|
+
import { taskFromRow } from '../store-pg.mjs';
|
|
14
|
+
import { fenceExecution } from './executor.mjs';
|
|
15
|
+
import { createVerifier } from './verifier.mjs';
|
|
16
|
+
import { plan } from './planner.mjs';
|
|
17
|
+
import { newRegister, ingestEvent, resolveUsage } from './spend.mjs';
|
|
18
|
+
import { MINUTE_MS, publishRates, forecastToReset, initialPacingState, pacingHysteresis,
|
|
19
|
+
lowBalanceWarning, weeklyProposal, weeklyRunMs, isoWeekOf, evidenceDates, dailyTotalsFromReceipts } from './forecast.mjs';
|
|
20
|
+
|
|
21
|
+
const text = z.string().min(1).max(8192);
|
|
22
|
+
const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
23
|
+
const LaunchAuthoritySchema = AdmissionAuthoritySchema.pick({ adapter: true, launch: true,
|
|
24
|
+
producerIdentityIds: true, orchestrator: true }).extend({ project: text, card: integer.min(1),
|
|
25
|
+
cardRevision: integer, candidateId: text });
|
|
26
|
+
export const DrillSpecSchema = z.strictObject({ id: text, project: text, kind: z.enum(['manual', 'command']),
|
|
27
|
+
registryHash: text, probeIds: z.array(text), machine: text, argv: z.array(text),
|
|
28
|
+
environment: z.record(text, text), timeoutMs: integer.min(1), evidenceRequirements: z.array(text) });
|
|
29
|
+
export const EvidenceSchemas = {
|
|
30
|
+
account: AccountSchema, machine: MachineSchema, seat: SeatSchema, model: ModelEvidenceSchema,
|
|
31
|
+
fitness: FitnessCellSchema, projectSchedule: ProjectScheduleSchema, ledger: WindowLedgerSchema,
|
|
32
|
+
launch: LaunchAuthoritySchema, repair: RepairAuthoritySchema.omit({ collectorAuthorized: true, policyVersion: true }),
|
|
33
|
+
settlement: BindingSettlementSchema, replacement: ReplacementAuthoritySchema,
|
|
34
|
+
drill: DrillSpecSchema,
|
|
35
|
+
promotion: z.strictObject({ policyHash: text, result: z.literal('pass'), approvalId: text,
|
|
36
|
+
drills: z.array(z.strictObject({ id: text, result: z.literal('pass'), evidenceRef: text })),
|
|
37
|
+
rollout: RolloutApprovalSchema }),
|
|
38
|
+
};
|
|
39
|
+
const sources = { account: ['balances'], ledger: ['balances', 'attempt-receipt'], machine: ['machine-beat', 'machine-beats'],
|
|
40
|
+
seat: ['machine-beat', 'machine-beats', 'presence'], model: ['machine-beat', 'machine-beats', 'presence', 'discovery-catalog'], fitness: ['acceptance'], projectSchedule: ['owner'],
|
|
41
|
+
launch: ['adapter-record'], repair: ['collector'], settlement: ['adapter-record'],
|
|
42
|
+
replacement: ['adapter-record'], drill: ['owner'], promotion: ['owner'] };
|
|
43
|
+
export const RegisterEvidenceSchema = z.strictObject({ kind: z.enum(Object.keys(EvidenceSchemas)), id: text,
|
|
44
|
+
expectedRevision: integer.optional(), source: z.enum(['balances', 'attempt-receipt', 'machine-beat', 'machine-beats', 'presence', 'discovery-catalog', 'adapter-record', 'acceptance', 'collector', 'owner']),
|
|
45
|
+
sourceRef: text, observedAtMs: integer, expiresAtMs: integer, record: z.json() });
|
|
46
|
+
export const BridgeGrantSchema = z.strictObject({ grantId: text, scope: z.literal('org'),
|
|
47
|
+
kinds: z.array(z.enum(['account-window', 'machine', 'seat', 'model', 'card'])).min(1).max(5),
|
|
48
|
+
sources: z.array(z.enum(['balances', 'machine-beats', 'presence', 'discovery-catalog', 'board'])).min(1).max(5),
|
|
49
|
+
expiresAtMs: integer.nullable().optional(), revoked: z.boolean() });
|
|
50
|
+
|
|
51
|
+
async function evidenceActor(client, orgId, actor, request, nowMs) {
|
|
52
|
+
if (!actor?.grant) {
|
|
53
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
54
|
+
if (request.expectedRevision === undefined) reject('schema_invalid', 422);
|
|
55
|
+
return { approvedBy: actor.pubkey, grantId: null };
|
|
56
|
+
}
|
|
57
|
+
const { grant: grantId } = z.strictObject({ grant: text }).parse(actor);
|
|
58
|
+
const grant = (await client.query('SELECT * FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
|
|
59
|
+
[orgId, grantId])).rows[0];
|
|
60
|
+
const kind = ['account', 'ledger'].includes(request.kind) ? 'account-window' : request.kind;
|
|
61
|
+
if (!grant || grant.revoked_at_ms != null || grant.expires_at_ms != null && Number(grant.expires_at_ms) <= nowMs
|
|
62
|
+
|| grant.row.scope !== 'org' || !grant.row.kinds.includes(kind) || !grant.row.sources.includes(request.source)) reject('permission_denied', 403);
|
|
63
|
+
await requireRole(client, orgId, { pubkey: grant.approved_by }, '*', ['owner'], true);
|
|
64
|
+
return { approvedBy: grant.approved_by, grantId };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function observationContent(kind, row) {
|
|
68
|
+
const record = structuredClone(row);
|
|
69
|
+
const observations = kind === 'account' ? record.windows.map(window => window.remaining)
|
|
70
|
+
: kind === 'machine' ? [record.health]
|
|
71
|
+
: kind === 'model' ? [record.catalog, record.entitlement, record.invocation] : [];
|
|
72
|
+
for (const observation of observations) delete observation.receivedAtMs;
|
|
73
|
+
return record;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function requireRole(client, orgId, actor, project, roles, wildcardOnly = false) {
|
|
77
|
+
const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
|
|
78
|
+
if (!identity || identity.revoked_at != null || !storedScopeAllows(identity, project, roles, wildcardOnly)) reject('permission_denied', 403);
|
|
79
|
+
return identity;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '', advisorWorld,
|
|
83
|
+
evidenceSources, dispatcherBridgeGrant = process.env.RELAY_DISPATCHER_BRIDGE_GRANT || null }) {
|
|
84
|
+
const store = durableStore.createDispatcherStore();
|
|
85
|
+
const configuredGrant = text.nullable().parse(dispatcherBridgeGrant);
|
|
86
|
+
const bridgeBinding = async (client, orgId, nowMs) => {
|
|
87
|
+
const active = (await client.query(`SELECT grant_id FROM dispatcher_bridge_grants
|
|
88
|
+
WHERE org_id=$1 AND revoked_at_ms IS NULL AND (expires_at_ms IS NULL OR expires_at_ms>$2)
|
|
89
|
+
AND ($3::text IS NULL OR grant_id=$3) ORDER BY grant_id`,
|
|
90
|
+
[orgId, nowMs, configuredGrant])).rows;
|
|
91
|
+
if (active.length === 1) return { grant: active[0].grant_id, degraded: [] };
|
|
92
|
+
return { grant: null, degraded: [active.length ? 'bridge_grant_ambiguous' : 'bridge_grant_missing'] };
|
|
93
|
+
};
|
|
94
|
+
const snapshot = async (client, orgId, nowMs) => {
|
|
95
|
+
const binding = await bridgeBinding(client, orgId, nowMs);
|
|
96
|
+
return buildStoredSnapshot(client, orgId, nowMs, binding.degraded);
|
|
97
|
+
};
|
|
98
|
+
const evidence = async (client, orgId, kind, id) => {
|
|
99
|
+
const record = (await currentEvidence(client, orgId, clock())).find(e => e.kind === kind && e.id === id);
|
|
100
|
+
if (!record) reject(`${kind}_unknown`, 503);
|
|
101
|
+
return EvidenceSchemas[kind].parse(record.row);
|
|
102
|
+
};
|
|
103
|
+
const readAdvice = async (client, { orgId, request }) => {
|
|
104
|
+
if (request.snapshotId) {
|
|
105
|
+
const snapshotRow = (await client.query('SELECT row FROM dispatcher_snapshots WHERE org_id=$1 AND id=$2', [orgId, request.snapshotId])).rows[0];
|
|
106
|
+
if (!snapshotRow) reject('snapshot_gone', 410);
|
|
107
|
+
const snapshot = verifySnapshot(snapshotRow.row);
|
|
108
|
+
const policy = verifyPolicy((await client.query('SELECT row FROM dispatcher_policies WHERE org_id=$1 AND version=$2',
|
|
109
|
+
[orgId, snapshot.policyVersion])).rows[0]?.row);
|
|
110
|
+
return { snapshot, policy };
|
|
111
|
+
}
|
|
112
|
+
return snapshot(client, orgId, clock());
|
|
113
|
+
};
|
|
114
|
+
const readAuthority = async (client, { orgId, request }) => {
|
|
115
|
+
const authority = await snapshot(client, orgId, clock());
|
|
116
|
+
const card = authority.snapshot.readyQueue.find(c => c.project === request.project && c.card === request.card);
|
|
117
|
+
if (!card) reject('card_stale');
|
|
118
|
+
const records = await currentEvidence(client, orgId, clock());
|
|
119
|
+
const decision = request.decisionId ? (await client.query('SELECT row FROM dispatcher_decisions WHERE org_id=$1 AND id=$2 AND project=$3',
|
|
120
|
+
[orgId, request.decisionId, request.project])).rows[0]?.row : null;
|
|
121
|
+
const active = (await client.query(`SELECT row FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND card=$3
|
|
122
|
+
AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId, request.project, request.card])).rows[0]?.row;
|
|
123
|
+
const candidate = decision?.assignments.find(a => a.project === card.project && a.card === card.card)?.candidate || active?.candidate;
|
|
124
|
+
if (!candidate) reject('decision_stale');
|
|
125
|
+
if (!adapters.has(candidate.machine)) reject('adapter_unavailable', 503);
|
|
126
|
+
const launchRecord = records.filter(e => e.kind === 'launch').map(e => LaunchAuthoritySchema.parse(e.row))
|
|
127
|
+
.find(e => e.project === card.project && e.card === card.card && e.cardRevision === card.revision && e.candidateId === candidate.id);
|
|
128
|
+
if (!launchRecord || launchRecord.adapter.version !== CREW_ADAPTER_VERSION) reject('launch_unknown', 503);
|
|
129
|
+
const binding = (await client.query('SELECT account_id,frozen,row FROM dispatcher_account_bindings WHERE org_id=$1 AND seat_id=$2',
|
|
130
|
+
[orgId, candidate.seatId])).rows[0];
|
|
131
|
+
if (!binding) reject('account_binding_changed');
|
|
132
|
+
return AdmissionAuthoritySchema.parse({ ...authority, card,
|
|
133
|
+
binding: { accountId: binding.account_id, revision: binding.row.bindingRevision, frozen: binding.frozen },
|
|
134
|
+
windowLedgers: records.filter(e => e.kind === 'ledger').map(e => WindowLedgerSchema.parse(e.row)),
|
|
135
|
+
adapter: launchRecord.adapter, launch: launchRecord.launch,
|
|
136
|
+
producerIdentityIds: launchRecord.producerIdentityIds, orchestrator: launchRecord.orchestrator });
|
|
137
|
+
};
|
|
138
|
+
const readRepairAuthority = async (client, { orgId, seatId, request }) => {
|
|
139
|
+
const record = await evidence(client, orgId, 'repair', request.identityEvidenceId);
|
|
140
|
+
if (record.seat.seatId !== seatId) reject('evidence_unverified', 422);
|
|
141
|
+
const collector = (await client.query(`SELECT machine FROM dispatcher_collectors
|
|
142
|
+
WHERE org_id=$1 AND pubkey=$2 AND revoked_at_ms IS NULL`, [orgId, record.evidence.collectorPubkey])).rows[0];
|
|
143
|
+
const current = (await client.query('SELECT policy_version FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
144
|
+
return RepairAuthoritySchema.parse({ ...record, policyVersion: current?.policy_version,
|
|
145
|
+
collectorAuthorized: collector?.machine === record.seat.machine });
|
|
146
|
+
};
|
|
147
|
+
const readSettlement = async (client, { orgId, settlementId }) => {
|
|
148
|
+
const settlement = await evidence(client, orgId, 'settlement', settlementId);
|
|
149
|
+
const lease = (await client.query('SELECT attempt_id FROM dispatcher_leases WHERE org_id=$1 AND id=$2', [orgId, settlement.leaseId])).rows[0];
|
|
150
|
+
if (!lease) reject('evidence_unverified', 422);
|
|
151
|
+
const rows = await executionRows(client, orgId, lease.attempt_id);
|
|
152
|
+
if (!rows.generation.stopReceipt?.stopProof || !rows.generation.usageSettled) reject('evidence_unverified', 422);
|
|
153
|
+
for (const event of settlement.events) {
|
|
154
|
+
const stored = (await client.query('SELECT row FROM dispatcher_usage WHERE org_id=$1 AND event_id=$2', [orgId, event.id])).rows[0]?.row;
|
|
155
|
+
if (!stored || canonicalJson(stored) !== canonicalJson(event)) reject('evidence_unverified', 422);
|
|
156
|
+
}
|
|
157
|
+
return { verified: true, settlement };
|
|
158
|
+
};
|
|
159
|
+
const readReplacement = async (client, { orgId, previousAttemptId, candidate }) => {
|
|
160
|
+
const record = await evidence(client, orgId, 'replacement', previousAttemptId);
|
|
161
|
+
const rows = await executionRows(client, orgId, previousAttemptId);
|
|
162
|
+
if (!rows.generation.stopProof || !rows.generation.usageSettled || !rows.generation.stopReceipt?.recovery
|
|
163
|
+
|| rows.generation.checkpointRef !== record.checkpointRef || record.targetMachine !== candidate.machine) reject('handoff_unresolved');
|
|
164
|
+
return record;
|
|
165
|
+
};
|
|
166
|
+
const admission = createAdmission({ store, readAuthority, readReplacement, clock });
|
|
167
|
+
const executor = createExecutor({ store, readAuthority, clock, adapterFor: candidate => {
|
|
168
|
+
const adapter = adapters.get(candidate.machine);
|
|
169
|
+
if (!adapter) reject('adapter_unavailable', 503);
|
|
170
|
+
return adapter;
|
|
171
|
+
} });
|
|
172
|
+
const finance = createFinancialOperations({ store, readAuthority, readRepairAuthority, readSettlement, clock });
|
|
173
|
+
const verifier = createVerifier({ store, evidence, clock });
|
|
174
|
+
const service = {
|
|
175
|
+
store, admission, executor, finance, verifier, readAuthority, readAdvice, readRepairAuthority, readSettlement, readReplacement, evidence,
|
|
176
|
+
orgId(auth) { return auth?.identity?.orgId && auth.identity.orgId !== configuredOrg ? null : configuredOrg; },
|
|
177
|
+
projectDecision(decision, auth) {
|
|
178
|
+
const identity = auth.identity;
|
|
179
|
+
const assignments = decision.assignments.filter(a => storedScopeAllows(identity, a.project, ['read', 'write', 'approver', 'owner']));
|
|
180
|
+
const waiting = decision.waiting.filter(a => storedScopeAllows(identity, a.project, ['read', 'write', 'approver', 'owner']));
|
|
181
|
+
const visible = { ...decision, assignments, waiting, explanation: [], expectedWallMs: null,
|
|
182
|
+
expectedSpend: assignments.flatMap(a => a.estimates), snapshotHash: canonicalHash({ snapshotId: decision.snapshotId, assignments, waiting }) };
|
|
183
|
+
return visible;
|
|
184
|
+
},
|
|
185
|
+
async registerCard(orgId, input, actor) {
|
|
186
|
+
const request = z.strictObject({ card: WorkCardSchema, expectedRevision: integer.nullable() }).parse(input);
|
|
187
|
+
if (request.card.depsBasis === 'board') reject('board_projection_only');
|
|
188
|
+
return store.locked(orgId, async client => {
|
|
189
|
+
await requireIdentity(client, orgId, actor, request.card.project);
|
|
190
|
+
const task = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND id=$2 FOR UPDATE', [orgId, request.card.card])).rows[0];
|
|
191
|
+
if (!task || task.project !== request.card.project) reject('card_missing', 404);
|
|
192
|
+
const previous = (await client.query('SELECT revision FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
193
|
+
[orgId, task.project, request.card.card])).rows[0];
|
|
194
|
+
if ((previous ? Number(previous.revision) : null) !== request.expectedRevision) reject('card_stale');
|
|
195
|
+
if (previous) reject('card_already_managed');
|
|
196
|
+
if (request.card.revision !== 0 || request.card.readySinceMs !== null
|
|
197
|
+
|| request.card.difficulty !== task.difficulty || request.card.drill !== task.extra?.drill
|
|
198
|
+
|| canonicalJson(request.card.deps) !== canonicalJson((task.deps || []).map(card => ({ project: task.project, card })))) reject('card_stale');
|
|
199
|
+
await client.query('INSERT INTO dispatcher_cards VALUES($1,$2,$3,0,$4,NULL,$5)',
|
|
200
|
+
[orgId, task.project, request.card.card, task.status, request.card]);
|
|
201
|
+
await client.query("SELECT set_config('trantor.dispatcher_card_write','on',true)");
|
|
202
|
+
await client.query("UPDATE tasks SET extra=extra || '{\"dispatcherRevision\":0}'::jsonb WHERE org_id=$1 AND id=$2", [orgId, request.card.card]);
|
|
203
|
+
await client.query('UPDATE dispatcher_authority_state SET revision=revision+1 WHERE org_id=$1', [orgId]);
|
|
204
|
+
await store.audit(client, orgId, { action: 'card-registered', actor: actor.pubkey, atMs: clock(), card: request.card.card });
|
|
205
|
+
return { card: request.card.card, revision: 0 };
|
|
206
|
+
});
|
|
207
|
+
},
|
|
208
|
+
async mutateCard(orgId, input, actor) {
|
|
209
|
+
const request = z.object({ id: integer.min(1), expectedRevision: integer, status: z.enum(['todo','doing','testing','failed','done','blocked','stale']).optional(),
|
|
210
|
+
title: text.optional(), note: text.optional(), by: text.optional(), assignee: text.optional(),
|
|
211
|
+
drill: text.optional(), deps: z.array(integer.min(1)).optional(), difficulty: z.enum(['easy','medium','hard']).optional(),
|
|
212
|
+
executionAttemptId: text.optional(), generation: integer.min(1).optional(), launchToken: text.optional(),
|
|
213
|
+
acceptanceId: text.optional() }).strict().parse(input);
|
|
214
|
+
return store.locked(orgId, async client => {
|
|
215
|
+
const task = (await client.query('SELECT * FROM tasks WHERE org_id=$1 AND id=$2 FOR UPDATE', [orgId, request.id])).rows[0];
|
|
216
|
+
if (!task) reject('card_missing', 404);
|
|
217
|
+
await requireIdentity(client, orgId, actor, task.project);
|
|
218
|
+
const managed = (await client.query('SELECT * FROM dispatcher_cards WHERE org_id=$1 AND project=$2 AND card=$3',
|
|
219
|
+
[orgId, task.project, request.id])).rows[0];
|
|
220
|
+
if (!managed || managed.row.depsBasis === 'board' || Number(managed.revision) !== request.expectedRevision) reject('card_stale');
|
|
221
|
+
const active = (await client.query(`SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND card=$3
|
|
222
|
+
AND state NOT IN ('accepted','failed','cancelled','expired')`, [orgId, task.project, request.id])).rows;
|
|
223
|
+
for (const { id } of active) {
|
|
224
|
+
const rows = await executionRows(client, orgId, id);
|
|
225
|
+
if (rows.attempt.producerIdentityIds.includes(actor.pubkey)
|
|
226
|
+
&& (request.executionAttemptId !== id || request.generation !== rows.attempt.generation
|
|
227
|
+
|| request.launchToken !== rows.attempt.launchToken || rows.fenced)) reject('attempt_conflict');
|
|
228
|
+
}
|
|
229
|
+
if (request.executionAttemptId && !active.some(a => a.id === request.executionAttemptId)) reject('attempt_conflict');
|
|
230
|
+
if (request.status === 'done') {
|
|
231
|
+
const acceptance = (await client.query(`SELECT a.row FROM dispatcher_acceptances a JOIN dispatcher_attempts t
|
|
232
|
+
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
|
|
233
|
+
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'`,
|
|
234
|
+
[orgId, request.acceptanceId || '', task.project, request.id])).rows[0]?.row;
|
|
235
|
+
if (!acceptance || acceptance.result !== 'pass' || acceptance.cardRevision !== request.expectedRevision) reject('acceptance_required');
|
|
236
|
+
}
|
|
237
|
+
const card = WorkCardSchema.parse(managed.row);
|
|
238
|
+
if (request.drill !== undefined) card.drill = request.drill;
|
|
239
|
+
if (request.difficulty !== undefined) card.difficulty = request.difficulty;
|
|
240
|
+
if (request.deps !== undefined) card.deps = [...new Set(request.deps)].map(card => ({ project: task.project, card }));
|
|
241
|
+
const relevant = canonicalJson({ ...card, revision: 0, readySinceMs: null }) !== canonicalJson({ ...managed.row, revision: 0, readySinceMs: null })
|
|
242
|
+
|| request.assignee !== undefined && request.assignee !== task.assignee;
|
|
243
|
+
if (relevant) {
|
|
244
|
+
card.revision++;
|
|
245
|
+
for (const { id } of active) await fenceExecution(client, orgId, await executionRows(client, orgId, id), 'card-changed', clock());
|
|
246
|
+
}
|
|
247
|
+
const status = request.status || task.status;
|
|
248
|
+
const readySinceMs = relevant || !['todo','doing','testing'].includes(status) ? null : managed.ready_since_ms == null ? null : Number(managed.ready_since_ms);
|
|
249
|
+
card.readySinceMs = readySinceMs;
|
|
250
|
+
const extra = { ...task.extra, dispatcherRevision: card.revision, drill: card.drill };
|
|
251
|
+
if (request.note) extra.log = [...extra.log || [], { by: actor.pubkey, ts: clock(), text: request.note }].slice(-40);
|
|
252
|
+
if (request.acceptanceId) extra.acceptanceId = request.acceptanceId;
|
|
253
|
+
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`,
|
|
254
|
+
[orgId, task.project, request.id, card.revision, status, readySinceMs, card]);
|
|
255
|
+
await client.query("SELECT set_config('trantor.dispatcher_card_write','on',true)");
|
|
256
|
+
const changed = (await client.query(`UPDATE tasks SET title=$3,status=$4,assignee=$5,difficulty=$6,deps=$7,extra=$8,updated=$9
|
|
257
|
+
WHERE org_id=$1 AND id=$2 RETURNING *`, [orgId, request.id, request.title || task.title, status,
|
|
258
|
+
request.assignee ?? task.assignee, card.difficulty, JSON.stringify(card.deps.map(d => d.card)), extra, clock()])).rows[0];
|
|
259
|
+
await client.query('UPDATE dispatcher_authority_state SET revision=revision+1 WHERE org_id=$1', [orgId]);
|
|
260
|
+
await store.audit(client, orgId, { action: 'card-mutated', actor: actor.pubkey, atMs: clock(), card: request.id, revision: card.revision, status });
|
|
261
|
+
await client.query(`INSERT INTO events(org_id,ts,type,project,by_session,task_id,payload) VALUES($1,$2,$3,$4,$5,$6,$7)`,
|
|
262
|
+
[orgId, clock(), status === task.status ? 'updated' : 'moved', task.project, actor.pubkey, request.id,
|
|
263
|
+
{ from: task.status, to: status, revision: card.revision }]);
|
|
264
|
+
await client.query("SELECT pg_notify('trantor_changes',$1)", [JSON.stringify({ src: source })]);
|
|
265
|
+
return taskFromRow(changed);
|
|
266
|
+
});
|
|
267
|
+
},
|
|
268
|
+
async capacity(orgId, request, actor) {
|
|
269
|
+
return store.locked(orgId, async client => {
|
|
270
|
+
const identity = await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
|
|
271
|
+
const { snapshot } = await readAdvice(client, { orgId, request });
|
|
272
|
+
const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project)))];
|
|
273
|
+
return projectSnapshot(snapshot, projects.filter(p => storedScopeAllows(identity, p, ['read', 'write', 'approver', 'owner'])));
|
|
274
|
+
});
|
|
275
|
+
},
|
|
276
|
+
async pacing(orgId, request, actor) {
|
|
277
|
+
return store.locked(orgId, async client => {
|
|
278
|
+
await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
|
|
279
|
+
const nowMs = clock();
|
|
280
|
+
const minute = Math.floor(nowMs / MINUTE_MS) * MINUTE_MS;
|
|
281
|
+
const records = await currentEvidence(client, orgId, nowMs);
|
|
282
|
+
let authority = null;
|
|
283
|
+
try { authority = await readAdvice(client, { orgId, request: {} }); }
|
|
284
|
+
catch (error) {
|
|
285
|
+
if (!['policy_missing', 'scheduling_missing'].includes(error.code)) throw error;
|
|
286
|
+
}
|
|
287
|
+
const decision = authority ? plan({ ...authority, cards: authority.snapshot.readyQueue }) : null;
|
|
288
|
+
const events = (await client.query('SELECT row FROM dispatcher_usage WHERE org_id=$1', [orgId])).rows.map(r => r.row);
|
|
289
|
+
const leases = (await client.query('SELECT row FROM dispatcher_leases WHERE org_id=$1', [orgId])).rows.map(r => r.row);
|
|
290
|
+
const accounts = [];
|
|
291
|
+
for (const record of records.filter(e => e.kind === 'account')) {
|
|
292
|
+
const account = AccountSchema.parse(record.row);
|
|
293
|
+
const previous = (await client.query(`SELECT row FROM dispatcher_audit WHERE org_id=$1
|
|
294
|
+
AND row->>'action'='pacing-sample' AND row->>'accountId'=$2 ORDER BY at_ms DESC LIMIT 1`,
|
|
295
|
+
[orgId, account.id])).rows[0]?.row;
|
|
296
|
+
const result = pacingAccount({ orgId, account, nowMs, minute, events, leases, authority, decision, previous });
|
|
297
|
+
const sample = { action: 'pacing-sample', accountId: account.id, atMs: minute, result };
|
|
298
|
+
await client.query(`INSERT INTO dispatcher_audit(org_id,id,at_ms,row) VALUES($1,$2,$3,$4)
|
|
299
|
+
ON CONFLICT(org_id,id) DO UPDATE SET row=EXCLUDED.row`,
|
|
300
|
+
[orgId, `pacing:${canonicalHash([account.id, minute])}`, minute, sample]);
|
|
301
|
+
accounts.push(result);
|
|
302
|
+
}
|
|
303
|
+
return { asOfMs: nowMs, accounts };
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
async registerEvidence(orgId, input, actor) {
|
|
307
|
+
const request = RegisterEvidenceSchema.parse(input);
|
|
308
|
+
const record = EvidenceSchemas[request.kind].parse(request.record);
|
|
309
|
+
if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
|
|
310
|
+
|| request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
|
|
311
|
+
return store.locked(orgId, async client => {
|
|
312
|
+
const nowMs = clock();
|
|
313
|
+
const { approvedBy, grantId } = await evidenceActor(client, orgId, actor, request, nowMs);
|
|
314
|
+
if (request.expiresAtMs <= nowMs) reject('evidence_unverified', 422);
|
|
315
|
+
const previous = (await client.query(`SELECT * FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
|
|
316
|
+
ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
|
|
317
|
+
const previousRevision = Number(previous?.revision || 0);
|
|
318
|
+
if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
|
|
319
|
+
if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
|
|
320
|
+
if (grantId && previous) {
|
|
321
|
+
if (request.observedAtMs < Number(previous.observed_at_ms)) reject('evidence_stale');
|
|
322
|
+
if (request.observedAtMs === Number(previous.observed_at_ms)) {
|
|
323
|
+
if (previous.grant_id !== grantId || previous.registered_by !== approvedBy || previous.source !== request.source
|
|
324
|
+
|| previous.source_ref !== request.sourceRef
|
|
325
|
+
|| canonicalHash(observationContent(request.kind, previous.row)) !== canonicalHash(observationContent(request.kind, record))) reject('evidence_conflict');
|
|
326
|
+
return { id: request.id, revision: previousRevision, replayed: true };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
|
|
330
|
+
if (request.kind === 'promotion') {
|
|
331
|
+
if (record.approvalId !== request.id) reject('evidence_unverified', 422);
|
|
332
|
+
const validated = await validateRolloutApproval(client, orgId, record);
|
|
333
|
+
await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
|
|
334
|
+
approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
|
|
335
|
+
}
|
|
336
|
+
const revision = previousRevision + 1;
|
|
337
|
+
await client.query(`INSERT INTO dispatcher_evidence
|
|
338
|
+
(org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
|
|
339
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
|
|
340
|
+
[orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
|
|
341
|
+
request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
|
|
342
|
+
if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
|
|
343
|
+
ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
|
|
344
|
+
[orgId, record.accountId, record.windowId, revision, record]);
|
|
345
|
+
await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
|
|
346
|
+
ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
|
|
347
|
+
await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
|
|
348
|
+
kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
|
|
349
|
+
return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
|
|
350
|
+
});
|
|
351
|
+
},
|
|
352
|
+
async registerBridgeGrant(orgId, input, actor) {
|
|
353
|
+
const request = BridgeGrantSchema.parse(input);
|
|
354
|
+
return store.locked(orgId, async client => {
|
|
355
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
356
|
+
const nowMs = clock();
|
|
357
|
+
if (!request.revoked && request.expiresAtMs != null && request.expiresAtMs <= nowMs) reject('grant_expired', 422);
|
|
358
|
+
const row = { ...request, expiresAtMs: request.expiresAtMs ?? null, approvedBy: actor.pubkey };
|
|
359
|
+
await client.query(`INSERT INTO dispatcher_bridge_grants VALUES($1,$2,$3,$4,$5,$6)
|
|
360
|
+
ON CONFLICT(org_id,grant_id) DO UPDATE SET approved_by=EXCLUDED.approved_by,expires_at_ms=EXCLUDED.expires_at_ms,
|
|
361
|
+
revoked_at_ms=EXCLUDED.revoked_at_ms,row=EXCLUDED.row`,
|
|
362
|
+
[orgId, row.grantId, row.approvedBy, row.expiresAtMs, row.revoked ? nowMs : null, row]);
|
|
363
|
+
await store.audit(client, orgId, { action: 'bridge-grant-registered', actor: actor.pubkey, atMs: nowMs, ...row });
|
|
364
|
+
return row;
|
|
365
|
+
});
|
|
366
|
+
},
|
|
367
|
+
async registerCollector(orgId, input, actor) {
|
|
368
|
+
const request = z.strictObject({ pubkey: text, machine: text, revoked: z.boolean() }).parse(input);
|
|
369
|
+
return store.locked(orgId, async client => {
|
|
370
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
371
|
+
const identity = (await client.query('SELECT kind,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, request.pubkey])).rows[0];
|
|
372
|
+
if (!identity || identity.revoked_at != null || identity.kind !== 'tool') reject('permission_denied', 403);
|
|
373
|
+
await client.query(`INSERT INTO dispatcher_collectors VALUES($1,$2,$3,$4,$5)
|
|
374
|
+
ON CONFLICT(org_id,pubkey) DO UPDATE SET machine=EXCLUDED.machine,registered_by=EXCLUDED.registered_by,revoked_at_ms=EXCLUDED.revoked_at_ms`,
|
|
375
|
+
[orgId, request.pubkey, request.machine, actor.pubkey, request.revoked ? clock() : null]);
|
|
376
|
+
await store.audit(client, orgId, { action: 'collector-registered', actor: actor.pubkey, atMs: clock(), ...request });
|
|
377
|
+
return request;
|
|
378
|
+
});
|
|
379
|
+
},
|
|
380
|
+
async activatePolicy(orgId, input, actor) {
|
|
381
|
+
const request = z.strictObject({ expectedVersion: text.nullable(), policy: PolicySchema, reason: text, approvalId: text }).parse(input);
|
|
382
|
+
const policy = verifyPolicy(request.policy);
|
|
383
|
+
return store.locked(orgId, async client => {
|
|
384
|
+
await requireIdentity(client, orgId, actor, '', true);
|
|
385
|
+
const current = (await client.query('SELECT policy_version FROM dispatcher_authority_state WHERE org_id=$1', [orgId])).rows[0];
|
|
386
|
+
if ((current?.policy_version || null) !== request.expectedVersion) reject('policy_stale');
|
|
387
|
+
if (Object.values(policy.modeByProject).includes('admit')) {
|
|
388
|
+
const approval = await evidence(client, orgId, 'promotion', request.approvalId);
|
|
389
|
+
const validated = await service.checkApproval(client, orgId, approval, request.approvalId);
|
|
390
|
+
const cohort = (await client.query("SELECT row FROM dispatcher_audit WHERE org_id=$1 AND row->>'action'='rollout-frozen' AND row->>'id'=$2",
|
|
391
|
+
[orgId, validated.cohortId])).rows[0]?.row;
|
|
392
|
+
if (cohort?.summary.policyFingerprint !== rolloutPolicyHash(policy)) reject('shadow_policy_mismatch', 403);
|
|
393
|
+
if (policy.roster.some(r => r.enabled && r.harness !== 'crew')) reject('promotion_scope_invalid', 403);
|
|
394
|
+
if (Object.entries(policy.modeByProject).some(([project, mode]) => mode === 'admit' && project !== cohort?.project)) reject('promotion_scope_invalid', 403);
|
|
395
|
+
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'];
|
|
396
|
+
if (approval.policyHash !== policy.hash || required.some(id => !approval.drills.some(d => d.id === id))) reject('promotion_unapproved', 403);
|
|
397
|
+
}
|
|
398
|
+
const previous = (await client.query('SELECT hash FROM dispatcher_policies WHERE org_id=$1 AND version=$2', [orgId, policy.version])).rows[0];
|
|
399
|
+
if (previous && previous.hash !== policy.hash) reject('policy_stale');
|
|
400
|
+
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]);
|
|
401
|
+
await client.query(`INSERT INTO dispatcher_authority_state VALUES($1,1,$2) ON CONFLICT(org_id)
|
|
402
|
+
DO UPDATE SET revision=dispatcher_authority_state.revision+1,policy_version=EXCLUDED.policy_version`, [orgId, policy.version]);
|
|
403
|
+
await client.query(`INSERT INTO dispatcher_scheduling VALUES($1,0,0,$2) ON CONFLICT(org_id) DO NOTHING`,
|
|
404
|
+
[orgId, { schedulingRevision: 0, admissions: 0, accounts: [] }]);
|
|
405
|
+
await store.audit(client, orgId, { action: 'policy-activated', actor: actor.pubkey, atMs: clock(),
|
|
406
|
+
expectedVersion: request.expectedVersion, version: policy.version, reason: request.reason, approvalId: request.approvalId });
|
|
407
|
+
return { version: policy.version };
|
|
408
|
+
});
|
|
409
|
+
},
|
|
410
|
+
async recover(orgId) {
|
|
411
|
+
const complete = (await store.pool.query(`SELECT completed_at_ms FROM dispatcher_migrations WHERE id='dispatcher-v1'`)).rows[0];
|
|
412
|
+
if (!complete?.completed_at_ms) reject('migration_incomplete', 503);
|
|
413
|
+
const authority = await store.locked(orgId, client => snapshot(client, orgId, clock()));
|
|
414
|
+
return executor.recover(orgId, { snapshotId: authority.snapshot.id, policyVersion: authority.policy.version });
|
|
415
|
+
},
|
|
416
|
+
async tick() {
|
|
417
|
+
await store.locked(configuredOrg, async client => {
|
|
418
|
+
const binding = await bridgeBinding(client, configuredOrg, clock());
|
|
419
|
+
if (!binding.grant) return;
|
|
420
|
+
const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
|
|
421
|
+
[configuredOrg, binding.grant])).rows[0]?.row;
|
|
422
|
+
if (!grant?.kinds.includes('card') || !grant.sources.includes('board')) return;
|
|
423
|
+
const actor = await evidenceActor(client, configuredOrg, { grant: binding.grant }, { kind: 'card', source: 'board' }, clock());
|
|
424
|
+
const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
|
|
425
|
+
JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [configuredOrg])).rows[0]?.row;
|
|
426
|
+
if (!policy) reject('policy_missing', 503);
|
|
427
|
+
const changed = await projectBoardCards(client, configuredOrg, verifyPolicy(policy));
|
|
428
|
+
if (changed) await store.audit(client, configuredOrg, { action: 'board-projected', actor: actor.approvedBy,
|
|
429
|
+
grantId: binding.grant, atMs: clock(), changed });
|
|
430
|
+
});
|
|
431
|
+
if (evidenceSources) {
|
|
432
|
+
const binding = await store.locked(configuredOrg, async client => {
|
|
433
|
+
const selected = await bridgeBinding(client, configuredOrg, clock());
|
|
434
|
+
if (!selected.grant) return selected;
|
|
435
|
+
const grant = (await client.query('SELECT row FROM dispatcher_bridge_grants WHERE org_id=$1 AND grant_id=$2',
|
|
436
|
+
[configuredOrg, selected.grant])).rows[0]?.row;
|
|
437
|
+
if (grant?.kinds.every(kind => kind === 'card')) return { ...selected, grant: null };
|
|
438
|
+
const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
|
|
439
|
+
JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`,
|
|
440
|
+
[configuredOrg])).rows[0]?.row;
|
|
441
|
+
if (!policy) reject('policy_missing', 503);
|
|
442
|
+
return { ...selected, policy: verifyPolicy(policy) };
|
|
443
|
+
});
|
|
444
|
+
if (binding.grant) {
|
|
445
|
+
const { createEvidenceBridge } = await import('./evidence-bridge.mjs');
|
|
446
|
+
await createEvidenceBridge({ service, orgId: configuredOrg, grant: binding.grant,
|
|
447
|
+
sources: evidenceSources, clock, policy: binding.policy }).tick();
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
await verifier.reconcile(configuredOrg);
|
|
451
|
+
await finance.expireAsks(configuredOrg);
|
|
452
|
+
await executor.expire(configuredOrg);
|
|
453
|
+
if (adapters.size && store.isReady(configuredOrg)) await executor.runOnce(configuredOrg, `hub:${process.pid}`);
|
|
454
|
+
},
|
|
455
|
+
};
|
|
456
|
+
Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
|
|
457
|
+
service.executor = { ...executor, kill(orgId, input, actor) {
|
|
458
|
+
const control = KillSchema.parse(input);
|
|
459
|
+
return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);
|
|
460
|
+
} };
|
|
461
|
+
service.admission = { ...admission, async dispatch(orgId, input, actor) {
|
|
462
|
+
const replay = await store.locked(orgId, async client => {
|
|
463
|
+
await requireIdentity(client, orgId, actor, input.project);
|
|
464
|
+
return (await client.query('SELECT id FROM dispatcher_attempts WHERE org_id=$1 AND project=$2 AND idempotency_key=$3',
|
|
465
|
+
[orgId, input.project, input.idempotencyKey])).rows.length > 0;
|
|
466
|
+
});
|
|
467
|
+
if (!replay && !store.isReady(orgId)) await service.recover(orgId);
|
|
468
|
+
return admission.dispatch(orgId, input, actor);
|
|
469
|
+
} };
|
|
470
|
+
return service;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function pacingAccount({ orgId, account, nowMs, minute, events, leases, authority, decision, previous }) {
|
|
474
|
+
const windows = account.windows.filter(w => w.unit === 'usdMicros');
|
|
475
|
+
const daily = windows.filter(w => w.kind === 'daily' && w.startsAtMs != null && w.startsAtMs <= nowMs && w.resetsAtMs > nowMs)
|
|
476
|
+
.sort((a, b) => a.resetsAtMs - b.resetsAtMs)[0];
|
|
477
|
+
const cash = windows.find(w => w.kind === 'prepaid');
|
|
478
|
+
const known = window => account.status === 'verified' && window?.remaining.status === 'ok'
|
|
479
|
+
&& window.remaining.observedAtMs != null && window.remaining.observedAtMs <= nowMs
|
|
480
|
+
&& authority && nowMs - window.remaining.observedAtMs <= authority.policy.balanceTtlMs
|
|
481
|
+
? window.remaining.value : null;
|
|
482
|
+
const remainingMicros = known(daily);
|
|
483
|
+
const cashMicros = known(cash);
|
|
484
|
+
const register = events.filter(e => e.accountId === account.id)
|
|
485
|
+
.reduce((acc, event) => ingestEvent(acc, event).register, newRegister());
|
|
486
|
+
const resolved = resolveUsage(register);
|
|
487
|
+
const receipts = Object.values(resolved.requests).map(entry => {
|
|
488
|
+
const candidates = Object.entries(entry.windows).filter(([, w]) => w.unit === 'usdMicros');
|
|
489
|
+
const selected = candidates.find(([id]) => id.startsWith('daily:UTC:'))
|
|
490
|
+
|| candidates.find(([id]) => id === daily?.id) || candidates.find(([id]) => id === cash?.id);
|
|
491
|
+
const amount = selected?.[1];
|
|
492
|
+
const event = register.events.filter(e => entry.eventIds.includes(e.id))
|
|
493
|
+
.sort((a, b) => b.requestSequence - a.requestSequence)[0];
|
|
494
|
+
return { ts: event?.occurredAtMs ?? null, usdMicros: amount?.resolved ?? null,
|
|
495
|
+
confidence: !amount || amount.unbounded || amount.unknown > 0 ? 'unknown' : 'estimated' };
|
|
496
|
+
});
|
|
497
|
+
const unknownTime = receipts.some(r => r.ts == null);
|
|
498
|
+
const rates = publishRates({ receipts: receipts.filter(r => r.ts != null), nowMs: minute });
|
|
499
|
+
const planned = decision && decision.waiting.length === 0
|
|
500
|
+
? decision.expectedSpend.filter(c => c.accountId === account.id && c.windowId === daily?.id && c.unit === 'usdMicros')
|
|
501
|
+
.reduce((sum, c) => sum + c.estimate, 0) : null;
|
|
502
|
+
const projection = forecastToReset({ nowMs: minute, resetsAtMs: daily?.resetsAtMs ?? null,
|
|
503
|
+
remainingMicros, burnPerHourMicros: unknownTime || rates.ewma15m.perMinuteMicros == null
|
|
504
|
+
? null : rates.ewma15m.perMinuteMicros * 60, plannedSpendMicros: planned });
|
|
505
|
+
let state = previous?.result.pacing || initialPacingState();
|
|
506
|
+
if (previous?.atMs !== minute && previous?.atMs !== minute - MINUTE_MS || !projection.valid) {
|
|
507
|
+
state = { ...state, consecutiveRunsOut: 0, consecutiveSafe: 0 };
|
|
508
|
+
}
|
|
509
|
+
if (projection.valid && previous?.atMs !== minute) state = pacingHysteresis({ state, sample: { ...projection, atMs: minute } }).state;
|
|
510
|
+
const lowBalance = lowBalanceWarning({ nowMs, dailyLimitMicros: daily?.capacity ?? null,
|
|
511
|
+
spentTodayMicros: remainingMicros == null || daily?.capacity == null ? null : Math.max(0, daily.capacity - remainingMicros),
|
|
512
|
+
cashMicros, previous: previous?.result.lowBalance.state });
|
|
513
|
+
// Keep the episode payload readable by every polling client, not just the first reader.
|
|
514
|
+
if (!lowBalance.warning && lowBalance.state.triggerActive) lowBalance.warning = previous?.result.lowBalance.warning ?? null;
|
|
515
|
+
let runAtMs = weeklyRunMs(isoWeekOf(nowMs));
|
|
516
|
+
if (runAtMs > nowMs) runAtMs -= 7 * 86400_000;
|
|
517
|
+
const unresolvedStopLoss = unknownTime || resolved.stopNewCalls || leases.some(l => l.accountId === account.id
|
|
518
|
+
&& ['stop-loss', 'unknown-usage'].includes(l.stopReason) && l.state !== 'released');
|
|
519
|
+
const proposal = cash ? weeklyProposal({ org: orgId, accountId: account.id, runAtMs,
|
|
520
|
+
policyVersion: authority?.policy.version, currentLimitMicros: daily?.capacity ?? null, balanceMicros: cashMicros,
|
|
521
|
+
dailyTotals: dailyTotalsFromReceipts(receipts.filter(r => r.ts != null), { dates: evidenceDates(runAtMs) }),
|
|
522
|
+
unresolvedStopLoss, policy: authority?.policy }) : null;
|
|
523
|
+
return { accountId: account.id, provider: account.provider, resetsAtMs: daily?.resetsAtMs ?? null,
|
|
524
|
+
remainingMicros, balanceMicros: cashMicros, balanceReason: cashMicros == null ? 'cash_unknown' : null,
|
|
525
|
+
pacing: state, forecast: projection.valid ? projection : null, forecastReason: projection.valid ? null : projection.reason,
|
|
526
|
+
lowBalance: { warning: lowBalance.warning, state: lowBalance.state }, proposal };
|
|
527
|
+
}
|
|
@@ -169,8 +169,9 @@ function validateQueue(snapshot, cards) {
|
|
|
169
169
|
return [...queue.values()];
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
-
function readiness(card, snapshot, queue) {
|
|
172
|
+
function readiness(card, snapshot, queue, allowBoard) {
|
|
173
173
|
if (card.readySinceMs === null || card.readySinceMs > snapshot.asOfMs) return ['not_ready'];
|
|
174
|
+
if (allowBoard && card.depsBasis === 'board') return [];
|
|
174
175
|
return card.deps.filter(dep => !snapshot.acceptedDependencies.some(accepted =>
|
|
175
176
|
keyOf(dep) === keyOf(accepted) && (!queue.has(keyOf(dep))
|
|
176
177
|
|| queue.get(keyOf(dep)).revision === accepted.revision))).map(dep => `dependency_pending:${keyOf(dep)}`);
|
|
@@ -447,7 +448,8 @@ function solve(input, firstOnly) {
|
|
|
447
448
|
const assessments = new Map();
|
|
448
449
|
const schedules = new Map(snapshot.projectScheduling.map(project => [project.project, project]));
|
|
449
450
|
for (const card of queue) {
|
|
450
|
-
const reasons = readiness(card, snapshot, byKey);
|
|
451
|
+
const reasons = readiness(card, snapshot, byKey, !firstOnly && policy.modeByProject[card.project] === 'shadow');
|
|
452
|
+
if (firstOnly && card.depsBasis === 'board') reasons.push('board_projection_only');
|
|
451
453
|
if (!schedules.has(card.project)) reasons.push('project_schedule_unknown');
|
|
452
454
|
if (!Object.hasOwn(policy.modeByProject, card.project) || policy.modeByProject[card.project] === 'off') reasons.push('project_off');
|
|
453
455
|
if (policy.kill.fleet || policy.kill.projects.includes(card.project)) reasons.push('kill_switch');
|