trantor 0.18.146 → 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.
Files changed (57) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/advise.mjs +23 -7
  4. package/bin/capacity.mjs +18 -2
  5. package/bin/cli.mjs +6 -2
  6. package/bin/connect.mjs +10 -3
  7. package/bin/crew/state.mjs +1 -1
  8. package/bin/crew-runner.mjs +29 -4
  9. package/bin/dispatch.mjs +78 -0
  10. package/bin/docker-seat.mjs +33 -0
  11. package/bin/heavy-gate-shim/docker +2 -0
  12. package/bin/integrate.mjs +14 -2
  13. package/bin/migrate-dispatcher.mjs +50 -0
  14. package/bin/review.mjs +35 -0
  15. package/hooks/sessionstart.mjs +4 -1
  16. package/hub/auth.mjs +3 -3
  17. package/hub/routes/capacity.mjs +30 -23
  18. package/hub/routes/cards.mjs +13 -1
  19. package/hub/routes/dispatcher-operations.mjs +122 -0
  20. package/hub/routes/dispatcher.mjs +106 -0
  21. package/hub/routes/insights.mjs +68 -4
  22. package/hub/routes/worktree-status.mjs +56 -0
  23. package/hub/store.mjs +20 -0
  24. package/hub.mjs +17 -1
  25. package/kimi.plugin.json +1 -1
  26. package/lib/capacity.mjs +94 -16
  27. package/lib/dispatcher/acceptance.mjs +314 -0
  28. package/lib/dispatcher/accounts.mjs +442 -0
  29. package/lib/dispatcher/admission.mjs +731 -0
  30. package/lib/dispatcher/breakers.mjs +70 -0
  31. package/lib/dispatcher/executor.mjs +486 -0
  32. package/lib/dispatcher/forecast.mjs +391 -0
  33. package/lib/dispatcher/harness/boundary-linux.mjs +246 -0
  34. package/lib/dispatcher/harness/boundary-macos.mjs +237 -0
  35. package/lib/dispatcher/harness/contract.mjs +198 -0
  36. package/lib/dispatcher/harness/crew.mjs +463 -0
  37. package/lib/dispatcher/harness/publication.mjs +188 -0
  38. package/lib/dispatcher/migrate-attempts.mjs +51 -0
  39. package/lib/dispatcher/operations.mjs +401 -0
  40. package/lib/dispatcher/planner.mjs +516 -0
  41. package/lib/dispatcher/policy.mjs +9 -0
  42. package/lib/dispatcher/preflight.mjs +249 -0
  43. package/lib/dispatcher/resources.mjs +44 -0
  44. package/lib/dispatcher/schemas.mjs +3 -1
  45. package/lib/dispatcher/snapshot.mjs +72 -1
  46. package/lib/dispatcher/spend.mjs +319 -0
  47. package/lib/dispatcher/store.mjs +207 -2
  48. package/lib/dispatcher/verifier.mjs +246 -0
  49. package/lib/docker-janitor.mjs +24 -14
  50. package/lib/fitness.mjs +227 -41
  51. package/lib/review-gate.mjs +63 -0
  52. package/lib/store-contract.mjs +57 -0
  53. package/lib/store-pg.mjs +38 -3
  54. package/lib/telemetry-ship.mjs +8 -7
  55. package/lib/worktree-status.mjs +216 -0
  56. package/mcp.mjs +53 -7
  57. package/package.json +1 -1
@@ -0,0 +1,391 @@
1
+ // #14679 (B10a): dispatcher pacing calculations — the §7 forecast/§7.1 weekly prepaid-proposal
2
+ // rules of docs/TDD-dispatcher.md, calculation half of D14/D25. Pure: callers pass nowMs and
3
+ // injected B3 plan/B5 lease facts as arguments. Money is integer microdollars on B1's shapes;
4
+ // unknown stays null and never reads as zero. Projections are data, never reservations.
5
+
6
+ import { createHash } from 'node:crypto';
7
+
8
+ const DAY_MS = 86400e3;
9
+ const HOUR_MS = 3600e3;
10
+
11
+ // §7 pacing constants: one-minute buckets, a 15m EWMA (alpha 2/16), the 3/5 alert hysteresis
12
+ // with its 10% clear headroom, and the 80%-of-limit + cash-below-$5 joint warning trigger.
13
+ export const MINUTE_MS = 60_000;
14
+ export const EWMA_ALPHA = 2 / 16;
15
+ export const EWMA_MINUTES = 15;
16
+ export const ALERT_SAMPLES = 3;
17
+ export const CLEAR_SAMPLES = 5;
18
+ export const CLEAR_HEADROOM_PPM = 100_000;
19
+ export const LOW_CASH_MICROS = 5_000_000;
20
+
21
+ // §7.1 proposal constants: R/7 runway cap, the .75L..1.25L clamp on 1.25*P90, cent flooring and
22
+ // the $0.25 minimum that only a supporting R/7 may raise to.
23
+ export const MICRO_USD = 1_000_000;
24
+ export const CENT_MICROS = 10_000;
25
+ export const PROPOSAL_FLOOR_MICROS = 250_000;
26
+ export const DEFAULT_RESERVE_FRACTION_PPM = 150_000;
27
+
28
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
29
+
30
+ function utcDateOf(ms) {
31
+ const d = new Date(Number(ms));
32
+ const pad = (n) => String(n).padStart(2, '0');
33
+ return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`;
34
+ }
35
+
36
+ // ---- §7 pacing: buckets, rates, EWMA ----------------------------------------------------------------
37
+
38
+ // One-minute usage buckets over [fromMs, toMs) from B1-shaped receipts ({ts, usdMicros,
39
+ // confidence}). A bucket with no receipts is unknown (null) unless a confirmedNoUsage interval
40
+ // fully covers it; an unknown-amount receipt makes its bucket unknown, never zero.
41
+ export function usageBuckets({ receipts = [], fromMs, toMs, bucketMs = MINUTE_MS, confirmedNoUsage = [] }) {
42
+ const count = Math.max(0, Math.ceil((toMs - fromMs) / bucketMs));
43
+ const buckets = [];
44
+ for (let index = 0; index < count; index++) {
45
+ const startMs = fromMs + index * bucketMs;
46
+ buckets.push({ startMs, endMs: startMs + bucketMs, usdMicros: null, calls: 0,
47
+ observed: false, confirmedIdle: false });
48
+ }
49
+ for (const bucket of buckets) {
50
+ bucket.confirmedIdle = (confirmedNoUsage || []).some(([from, to]) => bucket.startMs >= from
51
+ && bucket.endMs <= to);
52
+ }
53
+ const unknowns = new Set();
54
+ for (const receipt of receipts || []) {
55
+ const ts = Number(receipt?.ts);
56
+ if (!Number.isFinite(ts) || ts < fromMs || ts >= toMs) continue;
57
+ const bucket = buckets[Math.min(count - 1, Math.floor((ts - fromMs) / bucketMs))];
58
+ bucket.calls += 1;
59
+ bucket.observed = true;
60
+ if (receipt.confidence === 'unknown' || receipt.usdMicros == null) {
61
+ unknowns.add(bucket);
62
+ continue;
63
+ }
64
+ bucket.usdMicros = (bucket.usdMicros == null ? 0 : bucket.usdMicros) + (Number(receipt.usdMicros) || 0);
65
+ }
66
+ for (const bucket of buckets) {
67
+ if (unknowns.has(bucket)) { bucket.usdMicros = null; continue; }
68
+ if (bucket.observed) continue;
69
+ bucket.usdMicros = bucket.confirmedIdle ? 0 : null;
70
+ }
71
+ return { fromMs, toMs, bucketMs, buckets };
72
+ }
73
+
74
+ // The published rates of §7: 1h and 24h spend and per-hour rates plus the 15m EWMA of the
75
+ // per-minute usage. Any unknown bucket inside a span makes that span's numbers null (unknown,
76
+ // not zero); the EWMA folds only the trailing fifteen one-minute buckets.
77
+ export function publishRates({ receipts = [], nowMs, confirmedNoUsage = [], bucketMs = MINUTE_MS }) {
78
+ const oneHour = usageBuckets({ receipts, fromMs: nowMs - HOUR_MS, toMs: nowMs, bucketMs, confirmedNoUsage });
79
+ const twentyFour = usageBuckets({ receipts, fromMs: nowMs - 24 * HOUR_MS, toMs: nowMs, bucketMs, confirmedNoUsage });
80
+ const span = (buckets) => (buckets.some((b) => b.usdMicros == null) ? null
81
+ : buckets.reduce((acc, b) => acc + b.usdMicros, 0));
82
+ const oneHourSpend = span(oneHour.buckets);
83
+ const twentyFourSpend = span(twentyFour.buckets);
84
+ const ewmaBuckets = oneHour.buckets.slice(-EWMA_MINUTES);
85
+ let ewma = null;
86
+ if (ewmaBuckets.length === EWMA_MINUTES && ewmaBuckets.every((b) => b.usdMicros != null)) {
87
+ ewma = ewmaBuckets[0].usdMicros;
88
+ for (const bucket of ewmaBuckets.slice(1)) ewma += EWMA_ALPHA * (bucket.usdMicros - ewma);
89
+ }
90
+ return {
91
+ oneHour: { spendMicros: oneHourSpend, perHourMicros: oneHourSpend },
92
+ twentyFourHour: { spendMicros: twentyFourSpend,
93
+ perHourMicros: twentyFourSpend == null ? null : twentyFourSpend / 24 },
94
+ ewma15m: { perMinuteMicros: ewma, alpha: EWMA_ALPHA, minutes: EWMA_MINUTES },
95
+ };
96
+ }
97
+
98
+ // The forecast to the account reset (§7): current burn for the remaining hours plus the planned
99
+ // ready-card spend against the known remaining. Null inputs yield a reason, never a number.
100
+ export function forecastToReset({ nowMs, resetsAtMs, remainingMicros, burnPerHourMicros, plannedSpendMicros = 0 }) {
101
+ if (resetsAtMs == null || resetsAtMs <= nowMs) return { valid: false, reason: 'reset_unknown_or_passed' };
102
+ if (remainingMicros == null) return { valid: false, reason: 'remaining_unknown' };
103
+ if (burnPerHourMicros == null) return { valid: false, reason: 'burn_unknown' };
104
+ if (plannedSpendMicros == null) return { valid: false, reason: 'planned_spend_unknown' };
105
+ const hoursToReset = (resetsAtMs - nowMs) / HOUR_MS;
106
+ const projectedSpendMicros = burnPerHourMicros * hoursToReset + plannedSpendMicros;
107
+ const projectedRemainingMicros = remainingMicros - projectedSpendMicros;
108
+ return {
109
+ valid: true, hoursToReset, projectedSpendMicros, projectedRemainingMicros,
110
+ runsOutBeforeReset: projectedRemainingMicros < 0,
111
+ headroomPpm: remainingMicros > 0
112
+ ? Math.floor((projectedRemainingMicros * 1e6) / remainingMicros) : null,
113
+ };
114
+ }
115
+
116
+ // The D14 alert hysteresis: alert after three consecutive one-minute runs-out forecasts, clear
117
+ // after five consecutive safe samples (not running out AND >=10% headroom). A thin-headroom
118
+ // sample is not safe and never counts toward clearing.
119
+ export function initialPacingState() {
120
+ return { status: 'ok', consecutiveRunsOut: 0, consecutiveSafe: 0, alertedAtMs: null, clearedAtMs: null };
121
+ }
122
+
123
+ export function pacingHysteresis({ state, sample }) {
124
+ const merged = { ...initialPacingState(), ...state };
125
+ const runsOut = sample?.runsOutBeforeReset === true;
126
+ const safe = !runsOut && sample?.headroomPpm != null && sample.headroomPpm >= CLEAR_HEADROOM_PPM;
127
+ let changed = null;
128
+ if (merged.status === 'ok') {
129
+ if (runsOut) {
130
+ merged.consecutiveRunsOut += 1;
131
+ merged.consecutiveSafe = 0;
132
+ if (merged.consecutiveRunsOut >= ALERT_SAMPLES) { merged.status = 'alert'; merged.alertedAtMs = sample.atMs; changed = 'alert'; }
133
+ } else {
134
+ merged.consecutiveRunsOut = 0;
135
+ merged.consecutiveSafe += 1;
136
+ }
137
+ } else if (safe) {
138
+ merged.consecutiveSafe += 1;
139
+ merged.consecutiveRunsOut = 0;
140
+ if (merged.consecutiveSafe >= CLEAR_SAMPLES) {
141
+ merged.status = 'ok'; merged.clearedAtMs = sample.atMs; changed = 'cleared';
142
+ merged.consecutiveSafe = 0; merged.consecutiveRunsOut = 0;
143
+ }
144
+ } else {
145
+ merged.consecutiveSafe = 0;
146
+ if (runsOut) merged.consecutiveRunsOut += 1;
147
+ }
148
+ return { state: merged, changed };
149
+ }
150
+
151
+ // The §7 warning at 80% of the daily limit AND cash below $5, deduplicated to one per
152
+ // account/day or per new threshold crossing, carrying a top-up action. Unknown figures never
153
+ // trigger: the exhausted-limit/unknown-account classes are the immediate-alert half, not this.
154
+ export function lowBalanceWarning({ nowMs, dailyLimitMicros, spentTodayMicros, cashMicros, previous = {} }) {
155
+ const day = utcDateOf(nowMs);
156
+ const limit = Number(dailyLimitMicros);
157
+ const spent = spentTodayMicros == null ? null : Number(spentTodayMicros);
158
+ const cash = cashMicros == null ? null : Number(cashMicros);
159
+ const trigger = Number.isFinite(limit) && limit > 0 && spent != null && cash != null
160
+ && spent * 5 >= limit * 4 && cash < LOW_CASH_MICROS;
161
+ const sameDay = previous.day === day;
162
+ const alreadyWarned = sameDay && previous.warned === true;
163
+ const wasActive = sameDay && previous.triggerActive === true;
164
+ const emit = trigger && (!alreadyWarned || !wasActive);
165
+ return {
166
+ emit,
167
+ warning: emit ? { day, dailyLimitMicros: limit, spentTodayMicros: spent, cashMicros: cash,
168
+ usedPpm: Math.floor((spent * 1e6) / limit), action: 'top-up' } : null,
169
+ state: { day, warned: alreadyWarned || emit, triggerActive: trigger },
170
+ };
171
+ }
172
+
173
+ // ---- §7.1 weekly prepaid proposals ------------------------------------------------------------------
174
+
175
+ // ISO-8601 week of an instant (Monday first day, week one holds the year's first Thursday).
176
+ export function isoWeekOf(ms) {
177
+ const d = new Date(Number(ms));
178
+ const weekday = d.getUTCDay() || 7;
179
+ const thursdayMs = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 4 - weekday);
180
+ const t = new Date(thursdayMs);
181
+ const isoYear = t.getUTCFullYear();
182
+ const jan1Ms = Date.UTC(isoYear, 0, 1);
183
+ const isoWeek = Math.ceil(((thursdayMs - jan1Ms) / DAY_MS + 1) / 7);
184
+ return { isoYear, isoWeek, id: `${isoYear}-W${String(isoWeek).padStart(2, '0')}` };
185
+ }
186
+
187
+ // The durable job's firing instant: Monday 09:00 UTC of the named ISO week.
188
+ export function weeklyRunMs({ isoYear, isoWeek }) {
189
+ const jan4Ms = Date.UTC(isoYear, 0, 4);
190
+ const jan4Weekday = new Date(jan4Ms).getUTCDay() || 7;
191
+ const week1MondayMs = jan4Ms - (jan4Weekday - 1) * DAY_MS;
192
+ return week1MondayMs + (isoWeek - 1) * 7 * DAY_MS + 9 * HOUR_MS;
193
+ }
194
+
195
+ // The preceding seven complete UTC days of a run: the seven civil dates before the run's date.
196
+ export function evidenceDates(runAtMs) {
197
+ const d = new Date(Number(runAtMs));
198
+ const runDayMs = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
199
+ const dates = [];
200
+ for (let back = 7; back >= 1; back--) dates.push(utcDateOf(runDayMs - back * DAY_MS));
201
+ return dates;
202
+ }
203
+
204
+ // Daily totals from B1's resolveUsage output: sums resolved billed/estimated micros per
205
+ // daily:UTC:<date> window. Unknown or unbounded request windows mark the day uncovered; days
206
+ // with no requests stay uncovered until the caller confirms them (no usage is not zero).
207
+ export function dailyTotalsFromUsage(resolved = {}, { dates = [] }) {
208
+ const byDate = new Map(dates.map((date) => [date, emptyDay(date)]));
209
+ for (const entry of Object.values(resolved.requests || {})) {
210
+ for (const [windowId, window] of Object.entries(entry.windows || {})) {
211
+ const date = windowId.startsWith('daily:UTC:') ? windowId.slice('daily:UTC:'.length) : null;
212
+ if (!date || !byDate.has(date)) continue;
213
+ const row = byDate.get(date);
214
+ row.requests += 1;
215
+ if (window.unbounded || window.resolved == null) { row.unboundedCount += 1; continue; }
216
+ if (Number(window.unknown) > 0) { row.unknownCount += 1; continue; }
217
+ row.billedMicros += Number(window.billed) || 0;
218
+ row.estimatedMicros += Number(window.estimated) || 0;
219
+ }
220
+ }
221
+ return dates.map((date) => byDate.get(date));
222
+ }
223
+
224
+ // Daily totals from B1's scroogeReceipts-shaped rows ({ts, usdMicros, confidence}): billed and
225
+ // estimated amounts sum per UTC civil date; unknown amounts count, never sum. A date with no
226
+ // receipts is data-less, not zero — the caller confirms genuinely idle dates.
227
+ export function dailyTotalsFromReceipts(receipts = [], { dates = [] }) {
228
+ const byDate = new Map(dates.map((date) => [date, emptyDay(date)]));
229
+ for (const receipt of receipts || []) {
230
+ const ts = Number(receipt?.ts);
231
+ if (!Number.isFinite(ts)) continue;
232
+ const date = utcDateOf(ts);
233
+ if (!byDate.has(date)) continue;
234
+ const row = byDate.get(date);
235
+ row.requests += 1;
236
+ if (receipt.confidence === 'unknown' || receipt.usdMicros == null) { row.unknownCount += 1; continue; }
237
+ if (receipt.confidence === 'billed') row.billedMicros += Number(receipt.usdMicros) || 0;
238
+ else row.estimatedMicros += Number(receipt.usdMicros) || 0;
239
+ }
240
+ return dates.map((date) => byDate.get(date));
241
+ }
242
+
243
+ // Combine daily-total lists (register days, receipt days) into one auditable week: sums
244
+ // billed/estimated, accumulates unknown/unbounded counts, sorted by date.
245
+ export function mergeDailyTotals(...lists) {
246
+ const byDate = new Map();
247
+ for (const list of lists) {
248
+ for (const row of list || []) {
249
+ const date = String(row?.date || '');
250
+ if (!date) continue;
251
+ const acc = byDate.get(date) || emptyDay(date);
252
+ acc.billedMicros += Number(row.billedMicros) || 0;
253
+ acc.estimatedMicros += Number(row.estimatedMicros) || 0;
254
+ acc.unknownCount += Number(row.unknownCount) || 0;
255
+ acc.unboundedCount += Number(row.unboundedCount) || 0;
256
+ acc.requests += Number(row.requests) || 0;
257
+ byDate.set(date, acc);
258
+ }
259
+ }
260
+ return [...byDate.values()].sort((a, b) => compare(a.date, b.date));
261
+ }
262
+
263
+ function emptyDay(date) {
264
+ return { date, billedMicros: 0, estimatedMicros: 0, unknownCount: 0, unboundedCount: 0, requests: 0 };
265
+ }
266
+
267
+ // Nearest-rank percentile (P90 of seven totals is the 7th of the sorted values).
268
+ export function nearestRank(values = [], percentile = 90) {
269
+ const sorted = [...values].sort((a, b) => a - b);
270
+ if (!sorted.length) return null;
271
+ const rank = Math.max(1, Math.min(sorted.length, Math.ceil((percentile / 100) * sorted.length)));
272
+ return sorted[rank - 1];
273
+ }
274
+
275
+ // The proposal identity: deterministic per (org, account, ISO week) so restarts re-derive the
276
+ // same row and exactly one auditable proposal exists per account and week (D25).
277
+ export function proposalId({ org, accountId, week }) {
278
+ return `wp-${createHash('sha256').update(`${String(org)}\u0000${String(accountId)}\u0000${String(week)}`).digest('hex').slice(0, 24)}`;
279
+ }
280
+
281
+ function evidenceHashOf({ org, accountId, week, policyVersion, currentLimitMicros, balanceMicros, days, unresolvedStopLoss }) {
282
+ const canonical = JSON.stringify({
283
+ v: 1, org: String(org ?? ''), accountId: String(accountId ?? ''), week: String(week ?? ''),
284
+ policyVersion: String(policyVersion ?? ''), currentLimitMicros: currentLimitMicros ?? null,
285
+ balanceMicros: balanceMicros ?? null, unresolvedStopLoss: unresolvedStopLoss === true,
286
+ days: days.map((day) => [day.date, day.billedMicros, day.estimatedMicros,
287
+ day.unknownCount, day.unboundedCount, day.requests, day.covered]),
288
+ });
289
+ return createHash('sha256').update(canonical).digest('hex');
290
+ }
291
+
292
+ function reserveForLimit(limitMicros, policy) {
293
+ if (limitMicros == null) return null;
294
+ const fractionPpm = Number(policy?.reserveFractionPpm) || DEFAULT_RESERVE_FRACTION_PPM;
295
+ const floorMicros = Number(policy?.prepaidReserveFloorMicros) || PROPOSAL_FLOOR_MICROS;
296
+ return Math.max(Math.floor((limitMicros * fractionPpm) / 1e6), floorMicros);
297
+ }
298
+
299
+ // The §7.1 weekly prepaid proposal: Monday 09:00 UTC of the run's ISO week over the preceding
300
+ // seven complete UTC days. Missing coverage, cash or a stop-loss publishes "insufficient spend
301
+ // evidence" with the missing days, never a number. Otherwise propose min(R/7, clamp(1.25*P90,
302
+ // .75L, 1.25L)) floored to cents, $0.25 minimum only when R/7 supports it, else pause/top-up.
303
+ export function weeklyProposal({ org, accountId, runAtMs, policyVersion, currentLimitMicros,
304
+ balanceMicros, dailyTotals = [], unresolvedStopLoss = false, confirmedNoSpendDates = [], policy = {} }) {
305
+ const week = isoWeekOf(runAtMs);
306
+ const dates = evidenceDates(runAtMs);
307
+ const byDate = new Map((dailyTotals || []).map((row) => [String(row?.date || ''), row]));
308
+ const confirmed = new Set(confirmedNoSpendDates || []);
309
+ const uncovered = [];
310
+ const days = dates.map((date) => {
311
+ const row = byDate.get(date);
312
+ const requests = row ? Number(row.requests) || 0 : 0;
313
+ const unknownCount = row ? Number(row.unknownCount) || 0 : 0;
314
+ const unboundedCount = row ? Number(row.unboundedCount) || 0 : 0;
315
+ let cause = null;
316
+ if (unknownCount > 0) cause = 'unknown_usage';
317
+ else if (unboundedCount > 0) cause = 'unbounded_usage';
318
+ else if (requests === 0 && !confirmed.has(date)) cause = 'no_data';
319
+ const covered = cause == null;
320
+ if (!covered) uncovered.push({ date, cause });
321
+ return { date, billedMicros: covered ? Number(row?.billedMicros) || 0 : null,
322
+ estimatedMicros: covered ? Number(row?.estimatedMicros) || 0 : null,
323
+ unknownCount, unboundedCount, requests, covered };
324
+ });
325
+ const limitKnown = currentLimitMicros != null && Number.isFinite(Number(currentLimitMicros))
326
+ && Number(currentLimitMicros) >= 0;
327
+ const cashKnown = balanceMicros != null && Number.isFinite(Number(balanceMicros));
328
+ const id = proposalId({ org, accountId, week: week.id });
329
+ const totals = days.filter((day) => day.covered).map((day) => day.billedMicros + day.estimatedMicros);
330
+ const p90Micros = nearestRank(totals, 90);
331
+ const evidenceHash = evidenceHashOf({ org, accountId, week: week.id, policyVersion,
332
+ currentLimitMicros, balanceMicros, days, unresolvedStopLoss });
333
+ const base = {
334
+ id, accountId: String(accountId ?? ''), week: week.id, policyVersion: String(policyVersion ?? ''),
335
+ evidenceHash, runAtMs, currentLimitMicros: limitKnown ? Number(currentLimitMicros) : null,
336
+ proposedLimitMicros: null, status: 'insufficient', kind: 'insufficiency', reason: 'insufficient spend evidence',
337
+ action: 'none', missingDays: uncovered.map((entry) => entry.date),
338
+ detail: { uncovered, cashKnown, limitKnown, unresolvedStopLoss: unresolvedStopLoss === true },
339
+ evidence: { dates, days, sampleCoverage: days.map((day) => ({ date: day.date, requests: day.requests,
340
+ billedMicros: day.billedMicros, estimatedMicros: day.estimatedMicros, covered: day.covered })),
341
+ totalSpendMicros: null, p90Micros, balanceMicros: cashKnown ? Number(balanceMicros) : null },
342
+ currentReserveMicros: reserveForLimit(limitKnown ? Number(currentLimitMicros) : null, policy),
343
+ proposedReserveMicros: null, projectedRunwayDays: null,
344
+ };
345
+ if (uncovered.length > 0 || !limitKnown || !cashKnown || unresolvedStopLoss) return base;
346
+
347
+ const limitMicros = Number(currentLimitMicros);
348
+ const cashMicros = Number(balanceMicros);
349
+ const totalSpendMicros = totals.reduce((acc, total) => acc + total, 0);
350
+ const runwayPerDayMicros = cashMicros / 7;
351
+ if (runwayPerDayMicros < PROPOSAL_FLOOR_MICROS) {
352
+ return { ...base, kind: 'pause_or_top_up', status: 'pending', reason: 'runway_below_floor',
353
+ action: 'pause_or_top_up', evidence: { ...base.evidence, totalSpendMicros,
354
+ runwayPerDayMicros } };
355
+ }
356
+ const lowerBoundMicros = 0.75 * limitMicros;
357
+ const upperBoundMicros = 1.25 * limitMicros;
358
+ const rawMicros = 1.25 * p90Micros;
359
+ const clampedMicros = Math.min(Math.max(rawMicros, lowerBoundMicros), upperBoundMicros);
360
+ const candidateMicros = Math.min(runwayPerDayMicros, clampedMicros);
361
+ const flooredMicros = Math.floor(candidateMicros / CENT_MICROS) * CENT_MICROS;
362
+ const minimumApplied = flooredMicros < PROPOSAL_FLOOR_MICROS;
363
+ const proposedLimitMicros = minimumApplied ? PROPOSAL_FLOOR_MICROS : flooredMicros;
364
+ return {
365
+ ...base, kind: 'proposal', status: 'pending', reason: 'formula', action: 'set_daily_limit',
366
+ proposedLimitMicros, evidence: { ...base.evidence, totalSpendMicros, runwayPerDayMicros,
367
+ clamp: { lowerBoundMicros, upperBoundMicros, rawMicros, clampedMicros, candidateMicros,
368
+ flooredMicros, minimumApplied } },
369
+ proposedReserveMicros: reserveForLimit(proposedLimitMicros, policy),
370
+ projectedRunwayDays: proposedLimitMicros > 0 ? Math.floor(cashMicros / proposedLimitMicros) : null,
371
+ };
372
+ }
373
+
374
+ // The §7.1 persistable row for a numerical or pause/top-up proposal. Insufficiency publications
375
+ // are notifications, not proposal rows; this module never sets accepted — only the owner's CAS
376
+ // route can, so no unattended activation exists here.
377
+ export function persistableProposal(artifact) {
378
+ if (!artifact || artifact.kind === 'insufficiency') return null;
379
+ return { id: artifact.id, accountId: artifact.accountId, week: artifact.week,
380
+ policyVersion: artifact.policyVersion, evidenceHash: artifact.evidenceHash,
381
+ currentLimit: artifact.currentLimitMicros, proposedLimit: artifact.proposedLimitMicros,
382
+ reason: artifact.reason, status: artifact.status };
383
+ }
384
+
385
+ // A policy or account update supersedes stale pending proposals (a limit change always rides a
386
+ // new policy version); decided rows keep their decision.
387
+ export function supersedeStaleProposals({ proposals = [], policyVersion }) {
388
+ return proposals.map((proposal) => proposal?.status === 'pending'
389
+ && String(proposal.policyVersion) !== String(policyVersion)
390
+ ? { ...proposal, status: 'superseded' } : proposal);
391
+ }
@@ -0,0 +1,246 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync,
3
+ realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { z } from "zod";
7
+ import { canonicalHash } from "../snapshot.mjs";
8
+ import { HarnessError } from "./contract.mjs";
9
+ import { canonicalManifest } from "./publication.mjs";
10
+
11
+ export const LINUX_BOUNDARY_VERSION = "linux-bwrap-cgroup-v1";
12
+ const text = z.string().min(1).max(8192);
13
+ const claim = z.strictObject({ kind: z.enum(["file", "tree"]), key: text,
14
+ mode: z.enum(["read", "write"]) });
15
+ export const LinuxBoundaryManifestSchema = z.strictObject({
16
+ root: text,
17
+ claims: z.array(claim).max(100_000),
18
+ scratchRoot: text,
19
+ cgroupRoot: text.default("/sys/fs/cgroup/trantor-dispatcher"),
20
+ });
21
+
22
+ function unavailable(message) {
23
+ return new HarnessError("dispatch_unavailable", `Linux boundary unavailable: ${message}`, 503);
24
+ }
25
+
26
+ function processIdentity(pid) {
27
+ try {
28
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
29
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
30
+ if (fields[0] === "Z") return null;
31
+ return { pid, startId: fields[19], bootId: readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() };
32
+ } catch { return null; }
33
+ }
34
+
35
+ function sameProcess(identity) {
36
+ if (!identity) return false;
37
+ const current = processIdentity(identity.pid);
38
+ return current?.startId === identity.startId && current?.bootId === identity.bootId;
39
+ }
40
+
41
+ function assertNoHardLinks(root, claims) {
42
+ for (const claim of claims.filter(item => item.mode === "write")) {
43
+ const target = resolve(root, claim.key);
44
+ if (!existsSync(target)) continue;
45
+ const stat = lstatSync(target);
46
+ if (claim.kind === "file" && (stat.nlink !== 1 || !stat.isFile())) {
47
+ throw new HarnessError("claims_invalid", "writable file must be a single-link regular file", 422);
48
+ }
49
+ if (claim.kind === "tree") {
50
+ if (!stat.isDirectory()) throw new HarnessError("claims_invalid", "tree claim is not a directory", 422);
51
+ const pending = [target];
52
+ while (pending.length) {
53
+ const directory = pending.pop();
54
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
55
+ const path = join(directory, entry.name);
56
+ if (entry.isDirectory()) pending.push(path);
57
+ else if (entry.isFile() && statSync(path).nlink !== 1) {
58
+ throw new HarnessError("claims_invalid", "writable tree contains a hard-linked file", 422);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ }
64
+ }
65
+
66
+ function runtimeBinds() {
67
+ return ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc/ld.so.cache"]
68
+ .filter(path => existsSync(path));
69
+ }
70
+
71
+ function bwrapArguments(root, claims, scratch) {
72
+ const args = ["--die-with-parent", "--new-session", "--unshare-all", "--cap-drop", "ALL",
73
+ "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--dir", "/scratch",
74
+ "--bind", scratch, "/scratch"];
75
+ for (const path of runtimeBinds()) args.push("--ro-bind", path, path);
76
+ args.push("--ro-bind", root, "/repo");
77
+ for (const item of claims.filter(claim => claim.mode === "write")) {
78
+ const source = resolve(root, item.key);
79
+ if (!existsSync(source)) {
80
+ throw new HarnessError("claims_invalid", `writable ${item.kind} must exist before launch; claim its parent tree for new files`, 422);
81
+ }
82
+ args.push("--bind", source, `/repo/${item.key}`);
83
+ }
84
+ args.push("--setenv", "HOME", "/scratch/home", "--setenv", "TMPDIR", "/scratch/tmp",
85
+ "--setenv", "PATH", "/usr/local/bin:/usr/bin:/bin", "--chdir", "/repo");
86
+ return args;
87
+ }
88
+
89
+ function enableController(parent, name) {
90
+ mkdirSync(parent, { recursive: true });
91
+ const controllers = readFileSync(join(parent, "cgroup.controllers"), "utf8").trim().split(/\s+/);
92
+ if (!controllers.includes(name)) throw unavailable(`cgroup v2 ${name} controller is not delegated`);
93
+ writeFileSync(join(parent, "cgroup.subtree_control"), `+${name}`);
94
+ }
95
+
96
+ const controllerSource = `
97
+ const { spawn } = require("node:child_process");
98
+ let input = "";
99
+ process.stdin.on("data", chunk => {
100
+ input += chunk;
101
+ const end = input.indexOf("\\n");
102
+ if (end < 0) return;
103
+ const command = JSON.parse(input.slice(0, end));
104
+ const child = spawn(command.executable, command.args, {
105
+ cwd: process.cwd(), env: command.env, stdio: ["ignore", "pipe", "pipe"]
106
+ });
107
+ let stdout = "", stderr = "";
108
+ child.stdout.on("data", chunk => { stdout += chunk; });
109
+ child.stderr.on("data", chunk => { stderr += chunk; });
110
+ child.on("error", error => {
111
+ process.stdout.write(JSON.stringify({ type: "error", message: error.message }) + "\\n");
112
+ process.exit(127);
113
+ });
114
+ child.on("exit", (code, signal) => {
115
+ process.stdout.write(JSON.stringify({ type: "exit", code, signal, stdout, stderr }) + "\\n");
116
+ process.exit(code === null ? 1 : code);
117
+ });
118
+ process.stdout.write(JSON.stringify({ type: "started", pid: child.pid }) + "\\n");
119
+ });
120
+ `;
121
+
122
+ async function stopContainment(cgroup, handles) {
123
+ const procs = join(cgroup, "cgroup.procs");
124
+ const kill = join(cgroup, "cgroup.kill");
125
+ try {
126
+ if (existsSync(kill)) writeFileSync(kill, "1");
127
+ else for (const pid of readFileSync(procs, "utf8").trim().split(/\s+/).filter(Boolean).map(Number)) {
128
+ try { process.kill(pid, "SIGKILL"); } catch (error) { if (error.code !== "ESRCH") throw error; }
129
+ }
130
+ } catch (error) {
131
+ if (error.code !== "ENOENT") throw error;
132
+ }
133
+ let empty = false;
134
+ for (let attempt = 0; attempt < 200; attempt++) {
135
+ if (!existsSync(procs) || !readFileSync(procs, "utf8").trim()) { empty = true; break; }
136
+ await delay(10);
137
+ }
138
+ const escaped = [...handles.values()].filter(handle => sameProcess(handle.identity));
139
+ return { stopped: empty && escaped.length === 0, containmentEmpty: empty,
140
+ escapedPids: escaped.map(handle => handle.identity.pid) };
141
+ }
142
+
143
+ export async function prepareBoundary(manifestInput, attemptId, generation) {
144
+ if (process.platform !== "linux") throw unavailable("host is not Linux");
145
+ const manifest = LinuxBoundaryManifestSchema.parse(manifestInput);
146
+ const version = spawnSync("bwrap", ["--version"], { encoding: "utf8" });
147
+ if (version.error || version.status !== 0) throw unavailable("bubblewrap is missing");
148
+ if (!existsSync("/sys/fs/cgroup/cgroup.controllers")) throw unavailable("cgroup v2 is missing");
149
+ const root = realpathSync(manifest.root);
150
+ const claims = canonicalManifest(root, manifest.claims);
151
+ assertNoHardLinks(root, claims);
152
+ const containmentId = `attempt-${attemptId}-${generation}`.replace(/[^A-Za-z0-9_.-]/g, "-");
153
+ const scratch = join(manifest.scratchRoot, containmentId);
154
+ const parent = manifest.cgroupRoot;
155
+ const cgroup = join(parent, containmentId);
156
+ mkdirSync(join(scratch, "home"), { recursive: true });
157
+ mkdirSync(join(scratch, "tmp"), { recursive: true });
158
+ mkdirSync(join(scratch, "build"), { recursive: true });
159
+ try {
160
+ enableController(parent, "pids");
161
+ mkdirSync(cgroup);
162
+ writeFileSync(join(cgroup, "pids.max"), "128");
163
+ } catch (error) {
164
+ rmSync(scratch, { recursive: true, force: true });
165
+ rmSync(cgroup, { recursive: true, force: true });
166
+ if (error instanceof HarnessError) throw error;
167
+ throw unavailable(error.message);
168
+ }
169
+ const handles = new Map();
170
+ const stop = async () => {
171
+ const proof = await stopContainment(cgroup, handles);
172
+ return { ...proof, backend: LINUX_BOUNDARY_VERSION, containmentId,
173
+ processes: [...handles.values()].map(handle => handle.identity) };
174
+ };
175
+ const start = (executable, args = [], { env = {} } = {}) => new Promise((resolveStart, rejectStart) => {
176
+ const child = spawn(process.execPath, ["-e", controllerSource], {
177
+ stdio: ["pipe", "pipe", "pipe"], env: { PATH: process.env.PATH || "/usr/bin:/bin" },
178
+ });
179
+ let buffer = "", stderr = "";
180
+ const handle = { controller: child, identity: processIdentity(child.pid), result: null };
181
+ child.stderr.on("data", chunk => { stderr += chunk; });
182
+ child.stdout.on("data", chunk => {
183
+ buffer += chunk;
184
+ let end;
185
+ while ((end = buffer.indexOf("\n")) >= 0) {
186
+ const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
187
+ const event = JSON.parse(line);
188
+ if (event.type === "started") {
189
+ handle.sandboxPid = event.pid;
190
+ handle.result = new Promise(resolveResult => { handle.finish = resolveResult; });
191
+ resolveStart({ pid: child.pid, sandboxPid: event.pid, containmentId,
192
+ identity: handle.identity, completion: handle.result });
193
+ } else if (event.type === "exit") {
194
+ handle.finish?.({ ...event, stderr: `${stderr}${event.stderr}` });
195
+ } else if (event.type === "error") {
196
+ rejectStart(unavailable(event.message));
197
+ }
198
+ }
199
+ });
200
+ child.on("error", rejectStart);
201
+ child.on("close", () => handle.finish?.({ code: 1, signal: null, stdout: "", stderr }));
202
+ try {
203
+ writeFileSync(join(cgroup, "cgroup.procs"), String(child.pid));
204
+ handles.set(child.pid, handle);
205
+ child.stdin.write(`${JSON.stringify({ executable: "bwrap",
206
+ args: [...bwrapArguments(root, claims, scratch), "--", executable, ...args],
207
+ env: { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/scratch/home",
208
+ TMPDIR: "/scratch/tmp", ...env } })}\n`);
209
+ } catch (error) {
210
+ try { child.kill("SIGKILL"); } catch {}
211
+ rejectStart(unavailable(`could not contain process: ${error.message}`));
212
+ }
213
+ });
214
+ const api = {
215
+ start,
216
+ async run(executable, args = [], options = {}) {
217
+ const handle = await start(executable, args, options);
218
+ return handle.completion;
219
+ },
220
+ stop,
221
+ async cleanup() {
222
+ const proof = await stop();
223
+ if (!proof.containmentEmpty) throw new HarnessError("attempt_conflict", "refusing cleanup with live contained processes");
224
+ rmSync(cgroup, { recursive: true, force: true });
225
+ rmSync(scratch, { recursive: true, force: true });
226
+ return proof;
227
+ },
228
+ };
229
+ try {
230
+ const probe = await api.run("/usr/bin/true");
231
+ if (probe.code !== 0) throw unavailable(`bubblewrap probe failed: ${JSON.stringify(probe)}`);
232
+ } catch (error) {
233
+ await stop();
234
+ rmSync(cgroup, { recursive: true, force: true });
235
+ rmSync(scratch, { recursive: true, force: true });
236
+ throw error;
237
+ }
238
+ const allowedPaths = claims.map(item => `${item.mode}:${item.kind}:${item.key}`);
239
+ const capabilityTestDigest = canonicalHash({ backend: LINUX_BOUNDARY_VERSION,
240
+ allowedPaths, namespaceProbe: "pass", cgroupProbe: "pass" });
241
+ return {
242
+ backend: "linux", version: LINUX_BOUNDARY_VERSION,
243
+ allowedPaths, containmentId, capabilityTestDigest, cgroup,
244
+ scratch, sandboxRoot: "/repo", ...api,
245
+ };
246
+ }