Files
stack/packages/bus/src/limits.mjs
T
jason.woltje ca15d73e9f limits: a daily token quota for the account the stack uses, and bus schema 3h to 3i (row 126, #1620)
The business file can name the account claude-code launches use,
`launch.account` = {name, credential}. `name` is an identifier and
`credential` names one login set's environment variables, never a value.
`launch.limits.tokens.daily.<account>` = {limit, since, reset, timeZone}
sets a daily quota for that account. A daily key that isn't the account's
name refuses the business read.

The new plug-in limit-check/daily-quota (interface 2, pure) starts a day at
the first instant at or after `reset` on that local date in `timeZone`. Across
DST that makes a 23- or 25-hour day, and a reset in a skipped hour starts at
the gap's end. It counts the account's known records of all four kinds since
the later of the day start and `since`, and counts unknown turns apart.

The launcher refuses account-credential-missing, account-credential-ambiguous
and account-is-credential (an account name equal to a session credential's
value). Messages name variables, never values. The account rides mayLaunch,
bindLaunch, the usage records, mustStop and the launch record. A pi launch
has no account, records NULL, and no daily quota covers it. `mosaic limits`
and the Console's Settings show one fixed line when a daily row shows:
"Daily quotas count only this stack's own use of the account, not its use
anywhere else."

Bus schema 3h to 3i: 3h reserved usage_records.account as
CHECK (account IS NULL). The new step 3h-3i.sql rebuilds the table in one
transaction, keeping every row's seq and the sqlite_sequence value, and
recreates the three append-only triggers. All of sqlite_master equals 3h's
apart from the account line. A 3h engine refuses a 3i store.
packages/bus/tests/account-migration.test.mjs covers all three, with a
step that fails partway and leaves 3h intact. 3i goes live only through
`stack-release.sh activate ... --migrate` with Jason present (P19 371); the
activate path takes the pre-migrate backup, and the way back is restoring
it (agents/dewey/work/queue-126/MIGRATION.md).

Mos's go mos-0835, six conditions: (1) one transaction, account-migration
test 2 and mutant D29; (2) sqlite_master against 3h, test 1 and mutant D28;
(3) account is never a credential, the launcher's account-is-credential
refusal (launch-account.test.mjs) and the business name pattern
(token-limit-settings.test.mjs); (4) MIGRATION.md, accepted by Mos in
mos-0837; (5) the packet's DESIGN.md "no schema change" line corrected;
(6) the public/ digest below.

The public/ change in bus.js (the daily line under the token-limit table)
carries Mos's decision 123 go mos-0833 on the +/- digest 03e6d9da...ba78,
unchanged at landing.

Owner Dewey, brief docs/plans/2026-10-14_prd-1.2-build.md, "Daily quota for
the credential the stack uses today". Review round 2 rebases the round 4
build onto 1df04f52f (row 167). Reviewer: Filbert approve 29068 on round 1
(manifest d18314f7...8e65); Filbert approve 29080 on
round 2 (manifest f332db76...6fa6).
Seat run on round 2: touched 158/0, singles 1388/0 with 1 esbuild skip,
test-land-work.sh 86/0, 30/30 mutants killed.
Sage gate on 54319f552: GATE_PASSED, 2474+422/0, all 15 packages, the queue
suite and 10 script selftests.

Nothing live.
2026-10-18 20:35:02 -05:00

190 lines
10 KiB
JavaScript

// Row 125 (#1619, REQ-LIMIT-3, REQ-LIMIT-4): core's side of the limit checks. It loads only the
// `limit-check` modules the organization file switches on, one loader per business, and asks
// them through the loader alone: mayLaunch before a launch, mustStop after each turn's usage end,
// report for Settings and `mosaic limits`. Each check gets a copy of the business's launch limits
// and its per-turn usage records (usage.mjs turnRecords).
//
// Fail closed (lead decision 150). A check that throws, answers in the wrong shape, answers with
// a promise, or is switched on but not loaded (a refused load keeps the old modules) refuses the
// launch, stops the session at the end of its turn, and shows every limit as `check failed`. An
// organization file that can't be read refuses and stops the same way, with check null; report
// then throws, as the verb's own read does.
//
// refresh, mayLaunch and mustStop are async: they re-read the file and reload first. report is
// sync, so the organization verbs stay sync; it uses the modules the last refresh loaded.
import { createLoader } from '../../plugins/src/loader.mjs';
import { turnRecords } from './usage.mjs';
const KIND = 'limit-check';
const KINDS = ['input', 'output', 'cacheWrite', 'cacheRead'];
const CODE = /^[a-z][a-z0-9-]*$/;
const own = (value, key) => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.hasOwn(value, key);
const plainObject = value => value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
const exact = (value, keys) => plainObject(value) && Object.keys(value).length === keys.length && keys.every(k => Object.hasOwn(value, k));
const amount = value => (Number.isSafeInteger(value) && value >= 0) || (typeof value === 'string' && /^(0|[1-9]\d*)$/.test(value));
const turns = value => Number.isSafeInteger(value) && value >= 0;
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// Every token limit in launch.limits, in file order, at its schema depth only: tokens.instances.X,
// tokens.providers.X, tokens.keys.X, tokens.models.P.M and tokens.daily.A (row 126). The agent limits (total, providers,
// models) are never checks' limits, whatever their names, so a provider called `limit` there isn't
// taken for one. The settings writer (business launch-settings.mjs) walks the same depths.
const DEPTH = { instances: 1, providers: 1, keys: 1, models: 2, daily: 1 };
export function limitLeaves(limits) {
const out = [];
const walk = (value, depth, path) => {
if (!plainObject(value)) return;
for (const [key, entry] of Object.entries(value)) {
if (depth > 1) walk(entry, depth - 1, [...path, key]);
else if (plainObject(entry)) out.push({ path: [...path, key], limit: entry.limit, since: entry.since });
}
};
const tokens = plainObject(limits) ? limits.tokens : undefined;
if (plainObject(tokens)) {
for (const [kind, value] of Object.entries(tokens)) if (Object.hasOwn(DEPTH, kind)) walk(value, DEPTH[kind], ['tokens', kind]);
}
return out;
}
class Failure extends Error {
constructor(code) { super(code); this.code = code; }
}
// makeLoader is the plug-in loader's factory; tests pass a scratch tree's copy to load fixture checks.
export function createLimits({ store, read, log, makeLoader = createLoader }) {
if (typeof read !== 'function' || typeof log !== 'function') throw new TypeError('createLimits needs read and log');
const loaders = new Map();
const loaderFor = business => {
if (!loaders.has(business)) loaders.set(business, makeLoader({ log }));
return loaders.get(business);
};
// What one business has now: its limits, its records, and its switched-on checks. A check the
// file switches on that the loader doesn't have (a refused load) is not loaded.
function state(business, b = undefined) {
if (b === undefined) {
try { b = read(business); } catch { throw new Failure('organization-unreadable'); }
}
const setting = b?.plugins?.[KIND] ?? [];
const loader = loaderFor(business);
// The loader seeds every kind with an empty list, so a kind never loaded, or refused on its
// first load, has nothing switched on.
const names = loader.loaded()[KIND];
const modules = loader.modules(KIND);
let records;
try { records = turnRecords(store, business); } catch { throw new Failure('records-unreadable'); }
return {
limits: b?.launch?.limits ?? {},
records,
checks: same(setting, names) ? names.map((name, i) => ({ name, module: modules[i] })) : null,
missing: setting.find(name => !names.includes(name)) ?? setting[0] ?? null,
};
}
async function refresh(business) {
let b;
try { b = read(business); } catch { return; }
await loaderFor(business).load({ [KIND]: b?.plugins?.[KIND] ?? [] });
}
// Ask one check one export. The answer comes back, or a code: the check's own code if it threw
// one in the plug-in code shape, check-threw for any other throw, malformed-answer otherwise.
function ask(business, check, name, args, valid) {
try {
const answer = check.module[name](structuredClone(args));
if (answer !== null && (typeof answer === 'object' || typeof answer === 'function') && typeof answer.then === 'function') {
Promise.resolve(answer).catch(() => {});
throw new Failure('malformed-answer');
}
if (!valid(answer)) throw new Failure('malformed-answer');
return { answer };
} catch (e) {
const code = e instanceof Failure ? e.code : typeof e?.code === 'string' && CODE.test(e.code) ? e.code : 'check-threw';
log({ event: 'limit-check-failed', business, check: check.name, export: name, code });
return { code };
}
}
const validHit = (hit, leaves) =>
exact(hit, ['path', 'limit', 'count', 'unknownTurns']) &&
leaves.some(l => same(l.path, hit.path) && l.limit === hit.limit) && amount(hit.count) && turns(hit.unknownTurns);
// mayLaunch and mustStop: every switched-on check is asked in order; the first refusal or
// stop wins. key is the answer's boolean (allow, stop) and go its value when nothing is hit.
async function decide(business, subject, name, key, go, halt) {
await refresh(business);
let st;
try { st = state(business); } catch (e) {
log({ event: 'limit-check-failed', business, check: null, export: name, code: e.code });
return halt({ check: null, code: e.code });
}
if (!st.checks) {
log({ event: 'limit-check-failed', business, check: st.missing, export: name, code: 'not-loaded' });
return halt({ check: st.missing, code: 'not-loaded' });
}
const leaves = limitLeaves(st.limits);
const args = { business, limits: st.limits, subject, records: st.records, now: new Date().toISOString() };
for (const check of st.checks) {
const { answer, code } = ask(business, check, name, args, a =>
exact(a, [key]) ? a[key] === go : exact(a, [key, 'hit']) && a[key] === !go && validHit(a.hit, leaves));
if (code) return halt({ check: check.name, code });
if (answer[key] !== go) {
log({ event: 'limit-reached', business, check: check.name, export: name, subject, ...answer.hit });
return halt({ check: check.name, hit: answer.hit });
}
}
return { [key]: go };
}
const subjectOf = ({ instance, provider = null, model = null, account = null }) => ({ instance, provider, model, account });
// { allow: true } | { allow: false, check, hit } | { allow: false, check, code }
const mayLaunch = (business, subject) =>
decide(business, subjectOf(subject), 'mayLaunch', 'allow', true, why => ({ allow: false, ...why }));
// { stop: false } | { stop: true, check, hit } | { stop: true, check, code }
const mustStop = (business, subject) =>
decide(business, subjectOf(subject), 'mustStop', 'stop', false, why => ({ stop: true, ...why }));
const validEntry = (e, leaves) => {
const leaf = plainObject(e) && Array.isArray(e.path) && leaves.find(l => same(l.path, e.path));
if (!leaf || e.limit !== leaf.limit || e.since !== leaf.since) return false;
if (exact(e, ['path', 'limit', 'since', 'notEnforced'])) return typeof e.notEnforced === 'string' && e.notEnforced.length > 0;
return exact(e, ['path', 'limit', 'since', 'count', 'kinds', 'unknownTurns']) && amount(e.count) &&
exact(e.kinds, KINDS) && KINDS.every(k => amount(e.kinds[k])) && turns(e.unknownTurns);
};
// One entry per limit, in file order:
// { path, limit, since, status: 'counted', check, count, kinds, unknownTurns }
// { path, limit, since, status: 'not-enforced', reason } (reason null when no check names it)
// { path, limit, since, status: 'check-failed', check, code }
// A failed check fails every limit, so a count never shows beside a check that couldn't answer.
function report(business) {
// An unreadable file fails the report, as it fails the verb's own read.
const b = read(business);
const leaves = limitLeaves(b?.launch?.limits ?? {});
const failedAll = (check, code) => leaves.map(({ path, limit, since }) => ({ path, limit, since, status: 'check-failed', check, code }));
let st;
try { st = state(business, b); } catch (e) { return failedAll(null, e.code); }
if (!st.checks) return failedAll(st.missing, 'not-loaded');
const answers = [];
for (const check of st.checks) {
const { answer, code } = ask(business, check, 'report', { business, limits: st.limits, records: st.records, now: new Date().toISOString() },
a => Array.isArray(a) && a.every(e => validEntry(e, leaves)) && new Set(a.map(e => JSON.stringify(e.path))).size === a.length);
if (code) return failedAll(check.name, code);
answers.push({ check: check.name, entries: answer });
}
return leaves.map(({ path, limit, since }) => {
const found = answers.flatMap(({ check, entries }) => entries.filter(e => same(e.path, path)).map(e => ({ check, e })));
const counted = found.find(({ e }) => Object.hasOwn(e, 'count'));
if (counted) {
const { count, kinds, unknownTurns } = counted.e;
return { path, limit, since, status: 'counted', check: counted.check, count, kinds, unknownTurns };
}
const named = found.find(({ e }) => Object.hasOwn(e, 'notEnforced'));
return { path, limit, since, status: 'not-enforced', reason: named ? named.e.notEnforced : null };
});
}
return { refresh, mayLaunch, mustStop, report };
}