cornfield 0.17.0 → 0.18.0

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.
@@ -38,7 +38,7 @@
38
38
  *
39
39
  * @typedef {'code' | 'summary' | 'brief' | 'proposal'} RunKind
40
40
  * @typedef {{ issue?: number, proposal?: string, pull?: number, thread?: number }} RunRefs
41
- * @typedef {{ minutes?: number, turns?: number, cost?: number }} RunLimits
41
+ * @typedef {{ minutes?: number, turns?: number, cost?: number, tokens?: number }} RunLimits
42
42
  * @typedef {{ version: 1, runId: string, kind: RunKind, profile?: string, refs: RunRefs, branch?: string, brief: string,
43
43
  * limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
44
44
  * @typedef {'claimed' | 'working' | 'waiting' | 'done' | 'failed' | 'stopped'} ReportState
@@ -94,7 +94,7 @@ const TRIGGER_KEYS = ['event', 'by', 'ref'];
94
94
  /** The events an opt-in trigger may fire on (`agents.on`, spec 0005 D10): each is something a maintainer did */
95
95
  export const TRIGGER_EVENTS = Object.freeze(['spec.approved', 'build.opened', 'thread.message']);
96
96
  const REF_KEYS = ['issue', 'proposal', 'pull', 'thread'];
97
- const LIMIT_KEYS = ['minutes', 'turns', 'cost'];
97
+ const LIMIT_KEYS = ['minutes', 'turns', 'cost', 'tokens'];
98
98
  const REPORT_KEYS = ['state', 'note', 'url', 'tokens', 'cost'];
99
99
  const STOP_KEYS = ['state', 'note'];
100
100
  const ANSWER_KEYS = ['state', 'action', 'text'];
@@ -333,7 +333,7 @@ export function validateRequest(body, { profiles } = {}) {
333
333
  }
334
334
 
335
335
  if (body.limits !== undefined) {
336
- if (!isObject(body.limits)) return no('"limits" is { minutes, turns, cost }.');
336
+ if (!isObject(body.limits)) return no('"limits" is { minutes, turns, cost, tokens }.');
337
337
  const limitKeys = keyProblem(body.limits, LIMIT_KEYS, '"limits"');
338
338
  if (limitKeys) return no(limitKeys);
339
339
  for (const field of LIMIT_KEYS) {
@@ -341,6 +341,7 @@ export function validateRequest(body, { profiles } = {}) {
341
341
  if (n === undefined) continue;
342
342
  if (typeof n !== 'number' || !Number.isFinite(n) || n <= 0) return no(`"limits.${field}" is a number above zero.`);
343
343
  if (field === 'turns' && !Number.isInteger(n)) return no('"limits.turns" is a whole number.');
344
+ if (field === 'tokens' && !Number.isSafeInteger(n)) return no('"limits.tokens" is a whole number.');
344
345
  }
345
346
  }
346
347
 
@@ -158,6 +158,11 @@
158
158
  "cost": {
159
159
  "type": "number",
160
160
  "exclusiveMinimum": 0
161
+ },
162
+ "tokens": {
163
+ "type": "integer",
164
+ "exclusiveMinimum": 0,
165
+ "maximum": 9007199254740991
161
166
  }
162
167
  }
163
168
  },
package/core/config.js CHANGED
@@ -399,6 +399,8 @@ function agentRunProblems(a) {
399
399
  if (!Array.isArray(a.profiles) || a.profiles.length > MAX_PROFILES || !a.profiles.every((p) => typeof p === 'string' && PROFILE_NAME.test(p)) || new Set(a.profiles).size !== a.profiles.length) {
400
400
  out.push(`agents.profiles is a list of at most ${MAX_PROFILES} different names ("claude", "local-qwen"): letters, digits and . _ -, at most 64 characters each. The runner maps each to a model; cornfield only knows the name.`);
401
401
  }
402
+ // agents.limits keys a profile's own limits by its name, so a profile may not be named like a limit
403
+ else for (const p of a.profiles) if (LIMIT_NAMES.includes(p)) out.push(`agents.profiles ${JSON.stringify(p)} is the name of a limit (${LIMIT_NAMES.join(', ')}); name the profile something else.`);
402
404
  }
403
405
  if (a.runners !== undefined) {
404
406
  if (!Array.isArray(a.runners) || a.runners.length > MAX_RUNNERS || !a.runners.every((r) => isText(r) && r === r.trim() && !/[\s,]/.test(r))) {
@@ -418,14 +420,51 @@ function agentRunProblems(a) {
418
420
  else if (ms > RUNNER_QUIET_MAX_MS) out.push(`agents.runnerQuietAfter ${JSON.stringify(a.runnerQuietAfter)} is over the ceiling of 1h; use "60m" or less.`);
419
421
  }
420
422
  if (a.on !== undefined) out.push(...triggerProblems(a));
421
- if (a.limits !== undefined) {
422
- if (!isObject(a.limits)) out.push('agents.limits is { minutes?, turns?, cost? }: hints the runner may enforce.');
423
- else {
424
- for (const k of Object.keys(a.limits)) if (!['minutes', 'turns', 'cost'].includes(k)) out.push(`agents.limits.${k}: the keys are minutes, turns, cost.`);
425
- for (const k of ['minutes', 'cost']) if (a.limits[k] !== undefined && !(typeof a.limits[k] === 'number' && Number.isFinite(a.limits[k]) && a.limits[k] > 0)) out.push(`agents.limits.${k} is a number above zero.`);
426
- if (a.limits.turns !== undefined && !(Number.isInteger(a.limits.turns) && a.limits.turns > 0 && a.limits.turns <= MAX_NUMBER)) out.push('agents.limits.turns is a whole number above zero.');
423
+ if (a.limits !== undefined) out.push(...limitProblems(a));
424
+ return out;
425
+ }
426
+
427
+ /** The keys of a request's `limits`, in the contract's order (core/agent-contract.js) */
428
+ export const LIMIT_NAMES = Object.freeze(['minutes', 'turns', 'cost', 'tokens']);
429
+
430
+ /** What is wrong with `agents.limits`, as lines: the flat limits for every profile, and the profiles' own (`{ claude: { cost: 5 } }`) */
431
+ function limitProblems(a) {
432
+ const out = [];
433
+ const say = 'agents.limits is { minutes?, turns?, cost?, tokens? } for every profile, and { <profile>: { minutes?, turns?, cost?, tokens? } } for one: hints the runner may enforce.';
434
+ if (!isObject(a.limits)) return [say];
435
+ const profiles = Array.isArray(a.profiles) ? a.profiles : [];
436
+ const check = (set, at) => {
437
+ for (const k of Object.keys(set)) if (!LIMIT_NAMES.includes(k)) out.push(`${at}.${k}: the keys are ${LIMIT_NAMES.join(', ')}.`);
438
+ for (const k of LIMIT_NAMES) {
439
+ const n = set[k];
440
+ if (n === undefined) continue;
441
+ const whole = k === 'turns' || k === 'tokens';
442
+ if (!(typeof n === 'number' && Number.isFinite(n) && n > 0 && (!whole || (Number.isInteger(n) && n <= MAX_NUMBER)))) out.push(`${at}.${k} is a ${whole ? 'whole number' : 'number'} above zero.`);
427
443
  }
444
+ };
445
+ const flat = {};
446
+ for (const [k, v] of Object.entries(a.limits)) {
447
+ if (LIMIT_NAMES.includes(k)) { flat[k] = v; continue; }
448
+ if (!isObject(v)) { out.push(`agents.limits.${k}: the keys are ${LIMIT_NAMES.join(', ')}, or the name of a profile with its own limits.`); continue; }
449
+ if (!profiles.includes(k)) { out.push(`agents.limits.${k} is not one of agents.profiles (${profiles.join(', ') || 'none listed'}).`); continue; }
450
+ check(v, `agents.limits.${k}`);
428
451
  }
452
+ check(flat, 'agents.limits');
453
+ return out;
454
+ }
455
+
456
+ /**
457
+ * The limits a request starts from: the flat `agents.limits`, then the profile's own over them key by key. A request's explicit limits are
458
+ * laid over this by the caller. Returns a new object (empty when nothing is configured).
459
+ * @param {Record<string, any> | undefined} limits `agents.limits`
460
+ * @param {string | undefined} profile
461
+ */
462
+ export function limitDefaults(limits, profile) {
463
+ const out = {};
464
+ if (!isObject(limits)) return out;
465
+ for (const k of LIMIT_NAMES) if (limits[k] !== undefined) out[k] = limits[k];
466
+ const own = typeof profile === 'string' && !LIMIT_NAMES.includes(profile) ? limits[profile] : undefined;
467
+ if (isObject(own)) for (const k of LIMIT_NAMES) if (own[k] !== undefined) out[k] = own[k];
429
468
  return out;
430
469
  }
431
470
 
@@ -69,9 +69,9 @@ import { relativeTime } from './review-model.js';
69
69
  import { LAYER_DEFS, toggleLayer } from './layers.js';
70
70
  import { WORK_URL, groupWork, filterGroups, groupWords, workStatus, markWords } from './agents-model.js';
71
71
  import {
72
- RUNS_URL, runsUrl, stopUrl, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, handLines, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
72
+ RUNS_URL, runsUrl, stopUrl, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines, limitsWords, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
73
73
  } from './runs-model.js';
74
- import { runsHtml } from './runs-view.js';
74
+ import { runsHtml, totalsHtml } from './runs-view.js';
75
75
  import { setRunsOnMap, clearRunsOnMap } from './runs-map.js';
76
76
  import {
77
77
  STATES, defaultFilters, listUrl, pullUrl, serverState, filterItems, facetsOf, stateWords, metaWords, checkWords, checksWords, litFor, errorWords,
@@ -1133,6 +1133,12 @@ function paintRuns() {
1133
1133
  trig.hidden = !skipped;
1134
1134
  trig.textContent = skipped;
1135
1135
  }
1136
+ const totals = $('forge-runs-totals');
1137
+ if (totals) {
1138
+ const lines = data ? totalsLines(data.totals) : [];
1139
+ totals.hidden = !lines.length;
1140
+ totals.innerHTML = totalsHtml(viewContext(), lines);
1141
+ }
1136
1142
  const hand = $('forge-runs-hand');
1137
1143
  if (hand) {
1138
1144
  const lines = data ? handLines(data) : [];
@@ -1454,6 +1460,7 @@ async function openAgent(ref, opener) {
1454
1460
  $('agent-kind').innerHTML = KINDS.map(([v, l]) => option(v, l, v === 'code')).join('');
1455
1461
  $('agent-profile').innerHTML = option('', 'No profile', true) + profiles.map((p) => option(p, p, false)).join('');
1456
1462
  $('agent-profile-field').hidden = !profiles.length;
1463
+ paintLimits();
1457
1464
  $('agent-brief').value = '';
1458
1465
  $('agent-force').checked = false;
1459
1466
  $('agent-force-field').hidden = true;
@@ -1470,6 +1477,15 @@ async function openAgent(ref, opener) {
1470
1477
  announce(`Start an agent on ${aboutWords(refs)}. ${confirmStartWords(refs, forgeName())}`);
1471
1478
  }
1472
1479
 
1480
+ /** The limits the request will carry for the chosen profile, read-only under the select; the server fills them in */
1481
+ function paintLimits() {
1482
+ const el = $('agent-limits');
1483
+ if (!el) return;
1484
+ const words = limitsWords(ui.runs && ui.runs.data && ui.runs.data.limits, $('agent-profile-field').hidden ? '' : $('agent-profile').value);
1485
+ el.hidden = !words;
1486
+ el.textContent = words;
1487
+ }
1488
+
1473
1489
  /** Closes the dialog; the focus goes back to the button that opened it unless told not to */
1474
1490
  function closeAgent({ restoreFocus = true } = {}) {
1475
1491
  const el = agentEl();
@@ -1849,6 +1865,7 @@ export function initForgePanel(config, opts = {}) {
1849
1865
  agent.addEventListener('click', onAgentClick);
1850
1866
  agent.addEventListener('keydown', onAgentKey);
1851
1867
  agent.querySelector('form').addEventListener('submit', submitAgent);
1868
+ $('agent-profile').addEventListener('change', paintLimits);
1852
1869
  }
1853
1870
  const confirm = confirmEl();
1854
1871
  if (confirm) {
@@ -281,6 +281,7 @@
281
281
  <p id="forge-runs-runner" class="hx-forge-meta" hidden></p>
282
282
  <p id="forge-runs-note" class="hx-forge-notice" hidden></p>
283
283
  <p id="forge-runs-trigger" class="hx-forge-notice" hidden></p>
284
+ <div id="forge-runs-totals" role="group" aria-label="Tokens and cost the runners reported" hidden></div>
284
285
  <ul id="forge-runs-hand" class="hx-forge-meta" aria-label="Requests written by hand that started nothing" hidden></ul>
285
286
  <ul id="forge-runs-list" class="hx-forge-files" aria-label="Runs"></ul>
286
287
  </section>
@@ -367,6 +368,7 @@
367
368
  <form id="agent-start-form" class="hx-forge-confirm" novalidate>
368
369
  <label class="hx-forge-field">Kind of run<select id="agent-kind" class="hx-forge-select"></select></label>
369
370
  <label id="agent-profile-field" class="hx-forge-field" hidden>Profile<select id="agent-profile" class="hx-forge-select"></select></label>
371
+ <p id="agent-limits" class="hx-forge-meta" hidden></p>
370
372
  <label class="hx-forge-field">Brief for the runner<textarea id="agent-brief" class="hx-forge-preview" rows="6" maxlength="20000" spellcheck="true"></textarea></label>
371
373
  <label id="agent-force-field" class="hx-forge-toggle" hidden><input type="checkbox" id="agent-force" /> Ask for another run on purpose</label>
372
374
  <p id="agent-start-words" class="hx-confirm-note"></p>
@@ -126,6 +126,26 @@ export function runsStatus(data) {
126
126
  return `${data.open} open of ${data.maxOpen} allowed, ${n} ${n === 1 ? 'run' : 'runs'}`;
127
127
  }
128
128
 
129
+ /** "1200 tokens, cost 0.42", or '' when nothing was reported: the numbers as sent, never estimated; the cost to 2 decimals (the API keeps it raw) */
130
+ function saidWords(t) {
131
+ return [t.tokens != null && `${t.tokens} tokens`, typeof t.cost === 'number' && `cost ${t.cost.toFixed(2)}`].filter(Boolean).join(', ');
132
+ }
133
+
134
+ /**
135
+ * The totals of what runners reported, as plain lines: all runs, then per proposal, then per day (UTC). Empty when nothing was reported.
136
+ * `totals` is the server's `{ all, byProposal, byDay }` (each entry `{ runs, tokens, cost }`).
137
+ * @returns {string[]}
138
+ */
139
+ export function totalsLines(totals) {
140
+ if (!totals || !totals.all) return [];
141
+ const runs = (t) => `${t.runs} ${t.runs === 1 ? 'run' : 'runs'}`;
142
+ const out = [`Reported in all: ${saidWords(totals.all)} over ${runs(totals.all)}.`];
143
+ const list = (head, rows, name) => { if (rows && rows.length) out.push(`${head}: ${rows.map((r) => `${name(r)} ${saidWords(r)} (${runs(r)})`).join('; ')}.`); };
144
+ list('Per proposal', totals.byProposal, (r) => r.proposal);
145
+ list('Per day (UTC)', totals.byDay, (r) => r.day);
146
+ return out;
147
+ }
148
+
129
149
  /** "20 s", "5 min", "2 h": how long ago, short enough for a line */
130
150
  function agoShort(ms) {
131
151
  const s = Math.max(0, Math.round(ms / 1000));
@@ -165,6 +185,22 @@ export function startBody({ kind, profile, brief, refs, force }) {
165
185
  return out;
166
186
  }
167
187
 
188
+ const LIMIT_WORDS = [['minutes', (n) => `${n} ${n === 1 ? 'minute' : 'minutes'}`], ['turns', (n) => `${n} ${n === 1 ? 'turn' : 'turns'}`], ['cost', (n) => `cost ${n}`], ['tokens', (n) => `${n} tokens`]];
189
+
190
+ /**
191
+ * The limits a request for `profile` will carry, in one line for the Start dialog: the config's flat `agents.limits`, then the profile's own
192
+ * over them key by key (as core/config.js `limitDefaults`; the server fills them in, this only shows them). '' when the config sets none.
193
+ * @param {Record<string, any> | undefined} limits the `limits` of `GET /api/agent-runs`
194
+ * @param {string} profile '' for none
195
+ */
196
+ export function limitsWords(limits, profile) {
197
+ if (!limits || typeof limits !== 'object' || !Object.keys(limits).length) return '';
198
+ const names = LIMIT_WORDS.map(([k]) => k);
199
+ const own = profile && !names.includes(profile) && limits[profile] && typeof limits[profile] === 'object' ? limits[profile] : {};
200
+ const said = LIMIT_WORDS.map(([k, say]) => { const n = own[k] ?? limits[k]; return typeof n === 'number' ? say(n) : ''; }).filter(Boolean);
201
+ return said.length ? `Limits it will carry (hints for the runner): ${said.join(', ')}.` : 'It will carry no limits.';
202
+ }
203
+
168
204
  /** What a start came to, in words */
169
205
  export function startWords(status, body) {
170
206
  if (status === null) return 'cornfield did not answer; nothing was asked.';
@@ -76,6 +76,11 @@ function answerHtml(ctx, run) {
76
76
  <div class="hx-run-actions"><button type="button" class="hx-btn hx-forge-act" data-run-answer="reply" data-run-id="${id}" aria-label="Send reply to run ${id}"${off}>Reply</button></div>`;
77
77
  }
78
78
 
79
+ /** The totals as plain lines (see `totalsLines`), escaped; '' when there are none */
80
+ export function totalsHtml(ctx, lines) {
81
+ return lines.map((l) => `<p class="hx-forge-meta">${ctx.esc(l)}</p>`).join('');
82
+ }
83
+
79
84
  /** One run */
80
85
  export function runHtml(ctx, run, all) {
81
86
  const lit = ctx.selected === run.runId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
@@ -111,7 +111,7 @@ import { createHash } from 'node:crypto';
111
111
  import path from 'node:path';
112
112
  import { ForgeError, isMaintainer } from './forge.js';
113
113
  import { createRequest, findRunId, fencedBlocks, formatRunComment, isRunId, newRunId, runAuthors, runBlocksOf, runIdFromBranch, validateAnswer, validateReport, validateRequest, CONTRACT_VERSION, EDIT_GRACE_MS, MAX_BLOCKS, MAX_BLOCK_CHARS, MAX_NOTE_CHARS, MAX_TEXT_CHARS, RUN_TAG } from '../core/agent-contract.js';
114
- import { handWrittenMode, ideaLabel, quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
114
+ import { handWrittenMode, ideaLabel, limitDefaults, quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
115
115
  import { runnerPresence } from './runner-presence.js';
116
116
  import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
117
117
  import { readTopology } from '../core/validate.js';
@@ -520,9 +520,9 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
520
520
  if (force !== undefined && typeof force !== 'boolean') throw new Refused(400, '"force" is true or false: whether to ask for another run on an issue or proposal that has an open one.', 'invalid');
521
521
  const build = (login, pull) => {
522
522
  // The config's limits are hints the request starts from; what the person sent wins key by key
523
- const base = agents.limits || {};
523
+ const base = limitDefaults(agents.limits, typeof fields.profile === 'string' ? fields.profile : undefined);
524
524
  let limits = fields.limits;
525
- if (limits === undefined) limits = Object.keys(base).length ? { ...base } : undefined;
525
+ if (limits === undefined) limits = Object.keys(base).length ? base : undefined;
526
526
  else if (isObject(limits)) limits = { ...base, ...limits };
527
527
  // The brief is required by the contract and may be empty; the spec PR that holds a proposal is named beside it
528
528
  const refs = pull != null && isObject(fields.refs) ? { ...fields.refs, pull } : fields.refs;
@@ -845,6 +845,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
845
845
  // The dashboard's notice for triggers that did nothing (server/triggers.js writes a `trigger-skipped` row each time): the last day's, by reason
846
846
  const skipped = /** @type {{ at: string, answer: string | null }[]} */ (db.prepare("SELECT at, answer FROM actions WHERE action = 'trigger-skipped' AND (target = ? OR target LIKE ?) AND at > ? ORDER BY id DESC LIMIT 200").all(repo, `${repo}#%`, iso(at - 24 * 3_600_000)));
847
847
  const extras = extrasFor(db, rows, at);
848
+ const openNow = openRows(db, at);
848
849
  const reasons = {};
849
850
  for (const r of skipped) {
850
851
  let why = 'error';
@@ -852,13 +853,35 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
852
853
  reasons[why] = (reasons[why] || 0) + 1;
853
854
  }
854
855
  return {
855
- runs: rows.map((r) => publicRun(r, at, quietMs, extras.get(r.run_id))), open: openRows(db, at).length, maxOpen: cap, profiles, limits: agents.limits || {}, quietAfter: agents.quietAfter, runners: [...runnerSet].length,
856
+ runs: rows.map((r) => publicRun(r, at, quietMs, extras.get(r.run_id))), open: openNow.length, maxOpen: cap, profiles, limits: agents.limits || {}, quietAfter: agents.quietAfter, runners: [...runnerSet].length,
856
857
  triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
857
- refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
858
+ totals: totalsOf(db, at, openNow), refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
858
859
  handWritten: { mode: handMode, refused: discovers ? handRefused(db, at) : [] },
859
860
  };
860
861
  }
861
862
 
863
+ /**
864
+ * What the runners reported, added up as sent (never estimated): all runs, per proposal and per UTC day of the run's latest report (cost
865
+ * is incurred when the runner works, not when it was asked). A run counts its latest report once, even one smaller than the last (a
866
+ * runner that restarted its counter). `null` for a number nothing reported. The caps never drop today or the proposal of an open run.
867
+ */
868
+ function totalsOf(db, at, open) {
869
+ const sum = (rows) => rows.map((r) => ({ ...(r.proposal !== undefined ? { proposal: r.proposal } : {}), ...(r.day !== undefined ? { day: r.day } : {}), runs: r.runs, tokens: r.tokens, cost: r.cost === null ? null : Math.round(r.cost * 1e9) / 1e9 }));
870
+ const from = `FROM runs WHERE repo = ? AND ${POSTED} AND (tokens IS NOT NULL OR cost IS NOT NULL)`;
871
+ const cols = 'COUNT(*) AS runs, SUM(tokens) AS tokens, SUM(cost) AS cost';
872
+ const [all] = sum(db.prepare(`SELECT ${cols} ${from}`).all(repo));
873
+ // 50 proposals, those with an open run first so the cap never drops them; listed by their latest request
874
+ const live = [...new Set(open.map((r) => r.proposal).filter((p) => p != null))];
875
+ const proposals = db.prepare(`SELECT proposal, MAX(requested_at) AS last, ${cols} ${from} AND proposal IS NOT NULL GROUP BY proposal
876
+ ORDER BY proposal IN (SELECT value FROM json_each(?)) DESC, last DESC LIMIT ?`).all(repo, JSON.stringify(live), Math.max(50, live.length))
877
+ .sort((x, y) => (x.last < y.last ? 1 : x.last > y.last ? -1 : 0));
878
+ // The day of the latest report, in UTC (a forge may stamp a comment with an offset; date() converts it); today is never cut
879
+ const today = iso(at).slice(0, 10);
880
+ const days = db.prepare(`SELECT date(reported_at) AS day, ${cols} ${from} AND reported_at IS NOT NULL GROUP BY day ORDER BY day = ? DESC, day DESC LIMIT 30`).all(repo, today)
881
+ .sort((x, y) => (x.day < y.day ? 1 : x.day > y.day ? -1 : 0));
882
+ return { all: all.runs ? all : null, byProposal: sum(proposals.map(({ last, ...r }) => r)), byDay: sum(days) };
883
+ }
884
+
862
885
  /** One run, or null */
863
886
  async function get(runId) {
864
887
  const db = await auth.store();