cornfield 0.16.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.
- package/core/agent-contract.js +4 -3
- package/core/agent-contract.schema.json +5 -0
- package/core/config.js +60 -8
- package/explorer/forge-panel.js +25 -2
- package/explorer/index.html +3 -0
- package/explorer/runs-model.js +46 -1
- package/explorer/runs-view.js +5 -0
- package/package.json +1 -1
- package/server/agent-api.js +4 -1
- package/server/agent-runs.js +352 -12
- package/server/forge-forgejo.js +8 -0
- package/server/forge-github.js +7 -0
- package/server/forge.js +15 -2
- package/server/server.js +3 -1
- package/server/spec-poll.js +18 -2
package/core/agent-contract.js
CHANGED
|
@@ -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
|
|
package/core/config.js
CHANGED
|
@@ -159,7 +159,7 @@ export const DEFAULTS = Object.freeze({
|
|
|
159
159
|
personas: { roles: null, parent: 'root' },
|
|
160
160
|
cloud: { parent: 'root' },
|
|
161
161
|
releaseNotes: { breakingLabel: 'breaking' },
|
|
162
|
-
agents: { authors: [], labels: [], branchPrefixes: [], bots: true, transport: 'forge', maxOpen: DEFAULT_MAX_OPEN, profiles: [], runners: [], quietAfter: DEFAULT_QUIET_AFTER, runnerQuietAfter: DEFAULT_RUNNER_QUIET_AFTER, limits: {}, on: {}, refuseCollisions: false },
|
|
162
|
+
agents: { authors: [], labels: [], branchPrefixes: [], bots: true, transport: 'forge', maxOpen: DEFAULT_MAX_OPEN, profiles: [], runners: [], quietAfter: DEFAULT_QUIET_AFTER, runnerQuietAfter: DEFAULT_RUNNER_QUIET_AFTER, limits: {}, on: {}, refuseCollisions: false, handWritten: true },
|
|
163
163
|
hooks: [],
|
|
164
164
|
hookPoll: { specs: '5m' },
|
|
165
165
|
threads: { label: 'idea' },
|
|
@@ -175,7 +175,7 @@ export const PROPOSALS_KEYS = Object.freeze(['dir', 'approveLands']);
|
|
|
175
175
|
/** The keys of `worktrees` when it is an object: the folder, and how many days without a change leave a worktree out of the list (default: none is left out) */
|
|
176
176
|
export const WORKTREES_KEYS = Object.freeze(['dir', 'maxAgeDays']);
|
|
177
177
|
const MAX_WORKTREE_AGE_DAYS = 36500;
|
|
178
|
-
const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'runnerQuietAfter', 'limits', 'on', 'refuseCollisions'];
|
|
178
|
+
const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'runnerQuietAfter', 'limits', 'on', 'refuseCollisions', 'handWritten'];
|
|
179
179
|
const PROFILE_NAME = new RegExp(PROFILE_SOURCE);
|
|
180
180
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
181
181
|
const isText = (v) => typeof v === 'string' && v.trim() !== '';
|
|
@@ -249,6 +249,7 @@ export function configProblems(c) {
|
|
|
249
249
|
}
|
|
250
250
|
if (c.agents.bots !== undefined && typeof c.agents.bots !== 'boolean') out.push('agents.bots is true or false: whether a bot account ("[bot]" or the forge\'s Bot type) counts as an agent.');
|
|
251
251
|
out.push(...agentRunProblems(c.agents));
|
|
252
|
+
if (c.agents.handWritten === 'labeled' && c.threads === false) out.push('agents.handWritten is "labeled", which needs the threads label, and threads are off (threads: false): use true or false.');
|
|
252
253
|
if (isObject(c.agents.on) && c.agents.on['thread.message'] !== undefined && c.threads === false) out.push('agents.on["thread.message"] needs threads, which are off (threads: false): the /agent command is read in a thread.');
|
|
253
254
|
}
|
|
254
255
|
}
|
|
@@ -373,6 +374,17 @@ function triggerProblems(a) {
|
|
|
373
374
|
return out;
|
|
374
375
|
}
|
|
375
376
|
|
|
377
|
+
/**
|
|
378
|
+
* Which open issues and pull requests are read for `cornfield-run` request blocks a maintainer wrote by hand (`agents.handWritten`, issue #98):
|
|
379
|
+
* `'all'` (the default, `true`), `'labeled'` (only those carrying the threads label), or `false` for none.
|
|
380
|
+
* @param {{ agents?: { handWritten?: unknown } }} config
|
|
381
|
+
* @returns {false | 'all' | 'labeled'}
|
|
382
|
+
*/
|
|
383
|
+
export const handWrittenMode = (config) => {
|
|
384
|
+
const v = config.agents?.handWritten;
|
|
385
|
+
return v === false ? false : v === 'labeled' ? 'labeled' : 'all';
|
|
386
|
+
};
|
|
387
|
+
|
|
376
388
|
/** The triggers a config turns on, as `[event, { kind, profile?, brief? }]` (none when off, which is the default) */
|
|
377
389
|
export const triggersOf = (config) => Object.entries(isObject(config.agents?.on) ? config.agents.on : {}).filter(([e]) => TRIGGER_EVENTS.includes(e));
|
|
378
390
|
|
|
@@ -381,11 +393,14 @@ function agentRunProblems(a) {
|
|
|
381
393
|
const out = [];
|
|
382
394
|
if (a.transport !== undefined && !AGENT_TRANSPORTS.includes(a.transport)) out.push(`agents.transport is ${AGENT_TRANSPORTS.map((t) => JSON.stringify(t)).join(', ')}: where a request goes: "forge" posts it as a comment (the default), "push" sends it as an agent.requested hook event, "pull" keeps it for a runner to claim (docs/agents.md#transports).`);
|
|
383
395
|
if (a.refuseCollisions !== undefined && typeof a.refuseCollisions !== 'boolean') out.push('agents.refuseCollisions is true or false: whether a new request that names a node an open run is already changing is refused (false unless set).');
|
|
396
|
+
if (a.handWritten !== undefined && a.handWritten !== true && a.handWritten !== false && a.handWritten !== 'labeled') out.push('agents.handWritten is true (the default: a maintainer\'s hand-written request block on any open issue or pull request becomes a run), "labeled" (only on those with the threads label) or false (cornfield follows only the runs it asked for): docs/agents.md#requests-written-by-hand.');
|
|
384
397
|
if (a.maxOpen !== undefined && !(Number.isInteger(a.maxOpen) && a.maxOpen >= 1 && a.maxOpen <= MAX_OPEN_CEILING)) out.push(`agents.maxOpen is a whole number from 1 to ${MAX_OPEN_CEILING}: the most open runs cornfield asks for at once (${DEFAULT_MAX_OPEN} unless set).`);
|
|
385
398
|
if (a.profiles !== undefined) {
|
|
386
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) {
|
|
387
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.`);
|
|
388
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.`);
|
|
389
404
|
}
|
|
390
405
|
if (a.runners !== undefined) {
|
|
391
406
|
if (!Array.isArray(a.runners) || a.runners.length > MAX_RUNNERS || !a.runners.every((r) => isText(r) && r === r.trim() && !/[\s,]/.test(r))) {
|
|
@@ -405,14 +420,51 @@ function agentRunProblems(a) {
|
|
|
405
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.`);
|
|
406
421
|
}
|
|
407
422
|
if (a.on !== undefined) out.push(...triggerProblems(a));
|
|
408
|
-
if (a.limits !== undefined)
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
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.`);
|
|
414
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}`);
|
|
415
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];
|
|
416
468
|
return out;
|
|
417
469
|
}
|
|
418
470
|
|
package/explorer/forge-panel.js
CHANGED
|
@@ -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, 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,18 @@ 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
|
+
}
|
|
1142
|
+
const hand = $('forge-runs-hand');
|
|
1143
|
+
if (hand) {
|
|
1144
|
+
const lines = data ? handLines(data) : [];
|
|
1145
|
+
hand.hidden = !lines.length;
|
|
1146
|
+
hand.innerHTML = lines.map((l) => `<li>${escHtml(l)}</li>`).join('');
|
|
1147
|
+
}
|
|
1136
1148
|
const list = $('forge-runs-list');
|
|
1137
1149
|
if (!data) { list.innerHTML = ''; return; }
|
|
1138
1150
|
list.innerHTML = data.runs.length ? runsHtml(viewContext(), data.runs) : '<li class="hx-forge-empty hx-faint">No agent has been asked for yet. Start one from an issue or a proposal.</li>';
|
|
@@ -1448,6 +1460,7 @@ async function openAgent(ref, opener) {
|
|
|
1448
1460
|
$('agent-kind').innerHTML = KINDS.map(([v, l]) => option(v, l, v === 'code')).join('');
|
|
1449
1461
|
$('agent-profile').innerHTML = option('', 'No profile', true) + profiles.map((p) => option(p, p, false)).join('');
|
|
1450
1462
|
$('agent-profile-field').hidden = !profiles.length;
|
|
1463
|
+
paintLimits();
|
|
1451
1464
|
$('agent-brief').value = '';
|
|
1452
1465
|
$('agent-force').checked = false;
|
|
1453
1466
|
$('agent-force-field').hidden = true;
|
|
@@ -1464,6 +1477,15 @@ async function openAgent(ref, opener) {
|
|
|
1464
1477
|
announce(`Start an agent on ${aboutWords(refs)}. ${confirmStartWords(refs, forgeName())}`);
|
|
1465
1478
|
}
|
|
1466
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
|
+
|
|
1467
1489
|
/** Closes the dialog; the focus goes back to the button that opened it unless told not to */
|
|
1468
1490
|
function closeAgent({ restoreFocus = true } = {}) {
|
|
1469
1491
|
const el = agentEl();
|
|
@@ -1843,6 +1865,7 @@ export function initForgePanel(config, opts = {}) {
|
|
|
1843
1865
|
agent.addEventListener('click', onAgentClick);
|
|
1844
1866
|
agent.addEventListener('keydown', onAgentKey);
|
|
1845
1867
|
agent.querySelector('form').addEventListener('submit', submitAgent);
|
|
1868
|
+
$('agent-profile').addEventListener('change', paintLimits);
|
|
1846
1869
|
}
|
|
1847
1870
|
const confirm = confirmEl();
|
|
1848
1871
|
if (confirm) {
|
package/explorer/index.html
CHANGED
|
@@ -281,6 +281,8 @@
|
|
|
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>
|
|
285
|
+
<ul id="forge-runs-hand" class="hx-forge-meta" aria-label="Requests written by hand that started nothing" hidden></ul>
|
|
284
286
|
<ul id="forge-runs-list" class="hx-forge-files" aria-label="Runs"></ul>
|
|
285
287
|
</section>
|
|
286
288
|
<section id="forge-detail" class="hx-forge-detail" aria-label="Selected pull request" hidden></section>
|
|
@@ -366,6 +368,7 @@
|
|
|
366
368
|
<form id="agent-start-form" class="hx-forge-confirm" novalidate>
|
|
367
369
|
<label class="hx-forge-field">Kind of run<select id="agent-kind" class="hx-forge-select"></select></label>
|
|
368
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>
|
|
369
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>
|
|
370
373
|
<label id="agent-force-field" class="hx-forge-toggle" hidden><input type="checkbox" id="agent-force" /> Ask for another run on purpose</label>
|
|
371
374
|
<p id="agent-start-words" class="hx-confirm-note"></p>
|
package/explorer/runs-model.js
CHANGED
|
@@ -54,7 +54,7 @@ export function statusWhy(run) {
|
|
|
54
54
|
|
|
55
55
|
/** A line of facts: who asked and when, the profile, the limits asked for beside what the runner reported */
|
|
56
56
|
export function runMeta(run, nowMs) {
|
|
57
|
-
const parts = [`asked ${relativeTime(run.requestedAt, nowMs)} by ${run.requestedBy}`];
|
|
57
|
+
const parts = [`asked ${relativeTime(run.requestedAt, nowMs)} by ${run.requestedBy}${run.byHand ? ' (by hand)' : ''}`];
|
|
58
58
|
if (run.profile) parts.push(`profile ${run.profile}`);
|
|
59
59
|
const l = run.limits || {};
|
|
60
60
|
const limits = [l.minutes != null && `${l.minutes} min`, l.turns != null && `${l.turns} turns`, l.cost != null && `cost ${l.cost}`].filter(Boolean);
|
|
@@ -86,6 +86,15 @@ export function triggerNotice(data) {
|
|
|
86
86
|
return out.join(' ');
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/**
|
|
90
|
+
* The hand-written `cornfield-run` blocks that started nothing (`handWritten.refused`), one line each: who wrote it, where, and why. Empty when none.
|
|
91
|
+
* @returns {string[]}
|
|
92
|
+
*/
|
|
93
|
+
export function handLines(data) {
|
|
94
|
+
const list = data && data.handWritten && Array.isArray(data.handWritten.refused) ? data.handWritten.refused : [];
|
|
95
|
+
return list.map((r) => `Request by hand from ${r.by}${r.number ? ` on #${r.number}` : ''}${r.runId ? ` (${r.runId})` : ''} started nothing: ${r.reason || r.why}`);
|
|
96
|
+
}
|
|
97
|
+
|
|
89
98
|
/** Whether a Stop is offered: the run is open and nobody has asked it to stop yet */
|
|
90
99
|
export const canStop = (run) => run.open === true && !run.stopRequested;
|
|
91
100
|
|
|
@@ -117,6 +126,26 @@ export function runsStatus(data) {
|
|
|
117
126
|
return `${data.open} open of ${data.maxOpen} allowed, ${n} ${n === 1 ? 'run' : 'runs'}`;
|
|
118
127
|
}
|
|
119
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
|
+
|
|
120
149
|
/** "20 s", "5 min", "2 h": how long ago, short enough for a line */
|
|
121
150
|
function agoShort(ms) {
|
|
122
151
|
const s = Math.max(0, Math.round(ms / 1000));
|
|
@@ -156,6 +185,22 @@ export function startBody({ kind, profile, brief, refs, force }) {
|
|
|
156
185
|
return out;
|
|
157
186
|
}
|
|
158
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
|
+
|
|
159
204
|
/** What a start came to, in words */
|
|
160
205
|
export function startWords(status, body) {
|
|
161
206
|
if (status === null) return 'cornfield did not answer; nothing was asked.';
|
package/explorer/runs-view.js
CHANGED
|
@@ -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.
|
|
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)",
|
package/server/agent-api.js
CHANGED
|
@@ -184,7 +184,10 @@ export async function serveRunRoutes(req, res, reqPath, ctx) {
|
|
|
184
184
|
const url = new URL(req.url || '/', 'http://localhost');
|
|
185
185
|
if (url.searchParams.get('follow') === '1') {
|
|
186
186
|
try {
|
|
187
|
-
|
|
187
|
+
const forge = auth.forgeFor(session);
|
|
188
|
+
// Requests written by hand first, so a run just found is followed in the same look
|
|
189
|
+
await runs.discover(forge);
|
|
190
|
+
await runs.follow(forge);
|
|
188
191
|
} catch (err) {
|
|
189
192
|
console.error(`[cornfield] agent runs: the dashboard's look at the forge could not begin: ${err instanceof Error ? err.message : err}`);
|
|
190
193
|
}
|
package/server/agent-runs.js
CHANGED
|
@@ -41,6 +41,27 @@
|
|
|
41
41
|
* - the **timeline** is the request, the runner's reports, pushes, the pull request, its checks, how it ended, a stop request, and quiet: the first
|
|
42
42
|
* and last are worked out from the row, the rest are kept as they are seen (`run_events`, one row for each, so a second look adds none)
|
|
43
43
|
*
|
|
44
|
+
* ## Requests written by hand (`discover`, issue #98)
|
|
45
|
+
*
|
|
46
|
+
* A maintainer's own `cornfield-run` request block in a comment on an open issue or pull request becomes a run (`via: 'hand'`, the comment as its
|
|
47
|
+
* request and its record, sent on as `agents.transport` says like any run: on pull it is queued for a runner, on push it goes out as `agent.requested`).
|
|
48
|
+
* `discover` is called by the spec poll's tick just before `follow` (and by the dashboard's Refresh); it lists the open issues and pull requests that
|
|
49
|
+
* changed since the last look (`forge.changed`, one listing, the least recently changed first, from a cursor kept in `run_seen` as `hand-since:<time>` and
|
|
50
|
+
* never further back than `agents.quietAfter`), reads the comments of the ones whose update it has not read (`scan:<n>@<updatedAt>`; `agents.handWritten`:
|
|
51
|
+
* all of them, the ones with the threads label, or none), and judges each block once (`run_seen` key `h:…`, an `agent-hand` row in `actions`). The body
|
|
52
|
+
* of an issue or pull request is not read: anyone with write access may edit it, and the forge does not say when it was.
|
|
53
|
+
*
|
|
54
|
+
* - the author must be a maintainer now (the forge's answer for that login, never what the comment says) and the comment unedited (`runBlocksOf`);
|
|
55
|
+
* `requestedBy` and `requestedAt` in the block are claims, replaced by the comment's author and time. A request older than `agents.quietAfter`
|
|
56
|
+
* would be quiet at once and is not imported
|
|
57
|
+
* - a block whose run id a run already has is never imported: it is cornfield's own post (the same comment, or one still being posted), or a copy of it
|
|
58
|
+
* (refused as a duplicate). A fence without an id gets one from cornfield, the same on every look (`handRunId`), confirmed by a reply block in the
|
|
59
|
+
* thread that the poll's signed-in maintainer posts (the block's `requestedBy` is the author; the audit row names who posted it). A reply the forge
|
|
60
|
+
* refuses is posted on a later look; the run is kept meanwhile (on pull it may be claimed at once)
|
|
61
|
+
* - the cap and the one-run-per-subject rule are `reserve`'s, in the same transaction as the insert, so a hand-written request counts toward later
|
|
62
|
+
* cap checks and is refused when they say so; the rate limit guards people at the dashboard and does not apply
|
|
63
|
+
* - what started nothing (not a maintainer, edited, malformed with the contract's reason, duplicate, old, cap, subject) is kept in `actions` and shown by `list` as `handWritten.refused`
|
|
64
|
+
*
|
|
44
65
|
* ## Waiting, and the answer (issue #101)
|
|
45
66
|
*
|
|
46
67
|
* A runner may report `waiting` (a note and a link: "plan ready, approve to build"). The run stays open and is shown as Waiting. A maintainer answers
|
|
@@ -86,10 +107,11 @@
|
|
|
86
107
|
*/
|
|
87
108
|
|
|
88
109
|
import fs from 'node:fs';
|
|
110
|
+
import { createHash } from 'node:crypto';
|
|
89
111
|
import path from 'node:path';
|
|
90
112
|
import { ForgeError, isMaintainer } from './forge.js';
|
|
91
|
-
import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateAnswer, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
|
|
92
|
-
import { quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
|
|
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, limitDefaults, quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
|
|
93
115
|
import { runnerPresence } from './runner-presence.js';
|
|
94
116
|
import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
|
|
95
117
|
import { readTopology } from '../core/validate.js';
|
|
@@ -121,6 +143,15 @@ export const MAX_FILE_READS = 10;
|
|
|
121
143
|
export const MENTIONS_KEEP_MS = 3_600_000;
|
|
122
144
|
/** The queued requests a runner's listing answers at most, oldest first */
|
|
123
145
|
export const QUEUE_LIMIT = 50;
|
|
146
|
+
/** The open issues and pull requests listed for hand-written requests, each kind, newest activity first (`agents.handWritten`) */
|
|
147
|
+
export const HAND_TARGETS = 100;
|
|
148
|
+
/** The most conversations whose comments one look reads for hand-written requests; the rest wait for the next look */
|
|
149
|
+
export const MAX_HAND_READS = 30;
|
|
150
|
+
/** The most refused or ignored hand-written blocks the Runs view lists (newest first), and how far back */
|
|
151
|
+
export const HAND_SHOWN = 20;
|
|
152
|
+
export const HAND_SHOWN_MS = 7 * 24 * 3_600_000;
|
|
153
|
+
/** The most hand-written blocks one look judges, so a thread full of them cannot grow the audit table in one tick */
|
|
154
|
+
export const MAX_HAND_JUDGED = 50;
|
|
124
155
|
/** The runs that are over once the runner has said so */
|
|
125
156
|
/** The keys of a request as the API and the button send it: the contract's fields, less what cornfield writes, plus `force` */
|
|
126
157
|
export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'force']);
|
|
@@ -208,7 +239,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
|
208
239
|
return {
|
|
209
240
|
runId: row.run_id, kind: row.kind, profile: row.profile,
|
|
210
241
|
refs: { ...(row.issue != null ? { issue: row.issue } : {}), ...(row.proposal != null ? { proposal: row.proposal } : {}), ...(row.thread != null ? { thread: row.thread } : {}) },
|
|
211
|
-
status, open, requestedBy: row.requested_by, requestedAt: row.requested_at, via: row.via, transport: row.transport, target: row.target,
|
|
242
|
+
status, open, requestedBy: row.requested_by, requestedAt: row.requested_at, via: row.via, byHand: row.via === 'hand', transport: row.transport, target: row.target,
|
|
212
243
|
claimedAt: row.claimed_at,
|
|
213
244
|
comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
|
|
214
245
|
limits,
|
|
@@ -297,6 +328,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
297
328
|
const transport = /** @type {'forge' | 'push' | 'pull'} */ (agents.transport ?? 'forge');
|
|
298
329
|
const log = (what) => console.error(`[cornfield] agent runs: ${what}`);
|
|
299
330
|
let following = null;
|
|
331
|
+
let discovering = null;
|
|
300
332
|
|
|
301
333
|
const audit = async (entry) => {
|
|
302
334
|
try {
|
|
@@ -397,7 +429,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
397
429
|
}
|
|
398
430
|
|
|
399
431
|
/** Takes a place for a run: the cap and the one-per-subject rule are checked and the row inserted in one transaction. Throws a `Refused`. */
|
|
400
|
-
function reserve(db, request, { target, who, via, force, trigger = false, derived = null }) {
|
|
432
|
+
function reserve(db, request, { target, who, via, force, trigger = false, derived = null, hand = null }) {
|
|
401
433
|
const at = now();
|
|
402
434
|
const mine = subjectKeys(request.refs);
|
|
403
435
|
db.exec('BEGIN IMMEDIATE');
|
|
@@ -427,10 +459,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
427
459
|
throw new Refused(409, `${subjectWords(request.refs)} already has an open run${clash.profile ? ` under the profile ${clash.profile}` : ''}: ${clash.run_id} (${statusOf(clash, at, quietMs).status}). To ask for another on purpose, send "force": true${profiles.length ? ', or pick another profile' : ''}.`, 'run-open');
|
|
428
460
|
}
|
|
429
461
|
}
|
|
430
|
-
|
|
431
|
-
|
|
462
|
+
// A hand-written request is already on the forge: its row carries that comment (the record on every transport), and it travels as any request does
|
|
463
|
+
db.prepare(`INSERT INTO runs (run_id, repo, kind, profile, issue, proposal, thread, target, comment_id, comment_url, request, requested_by, requested_by_id, requested_at, via, last_activity, transport)
|
|
464
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
432
465
|
.run(request.runId, repo, request.kind, request.profile ?? null, request.refs.issue ?? null, request.refs.proposal ?? null, request.refs.thread ?? null,
|
|
433
|
-
target, JSON.stringify(request), request.requestedBy, String(who.userId), request.requestedAt, via ? 'api' : trigger ? 'trigger' : 'dashboard', iso(at), transport);
|
|
466
|
+
target, hand ? hand.comment.id : '', hand ? hand.comment.url : null, JSON.stringify(request), request.requestedBy, String(who.userId), request.requestedAt, hand ? 'hand' : via ? 'api' : trigger ? 'trigger' : 'dashboard', iso(at), transport);
|
|
434
467
|
db.exec('COMMIT');
|
|
435
468
|
} catch (err) {
|
|
436
469
|
try { db.exec('ROLLBACK'); } catch { /* nothing was begun */ }
|
|
@@ -487,9 +520,9 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
487
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');
|
|
488
521
|
const build = (login, pull) => {
|
|
489
522
|
// The config's limits are hints the request starts from; what the person sent wins key by key
|
|
490
|
-
const base = agents.limits
|
|
523
|
+
const base = limitDefaults(agents.limits, typeof fields.profile === 'string' ? fields.profile : undefined);
|
|
491
524
|
let limits = fields.limits;
|
|
492
|
-
if (limits === undefined) limits = Object.keys(base).length ?
|
|
525
|
+
if (limits === undefined) limits = Object.keys(base).length ? base : undefined;
|
|
493
526
|
else if (isObject(limits)) limits = { ...base, ...limits };
|
|
494
527
|
// The brief is required by the contract and may be empty; the spec PR that holds a proposal is named beside it
|
|
495
528
|
const refs = pull != null && isObject(fields.refs) ? { ...fields.refs, pull } : fields.refs;
|
|
@@ -812,6 +845,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
812
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
|
|
813
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)));
|
|
814
847
|
const extras = extrasFor(db, rows, at);
|
|
848
|
+
const openNow = openRows(db, at);
|
|
815
849
|
const reasons = {};
|
|
816
850
|
for (const r of skipped) {
|
|
817
851
|
let why = 'error';
|
|
@@ -819,12 +853,35 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
819
853
|
reasons[why] = (reasons[why] || 0) + 1;
|
|
820
854
|
}
|
|
821
855
|
return {
|
|
822
|
-
runs: rows.map((r) => publicRun(r, at, quietMs, extras.get(r.run_id))), open:
|
|
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,
|
|
823
857
|
triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
|
|
824
|
-
refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
|
|
858
|
+
totals: totalsOf(db, at, openNow), refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
|
|
859
|
+
handWritten: { mode: handMode, refused: discovers ? handRefused(db, at) : [] },
|
|
825
860
|
};
|
|
826
861
|
}
|
|
827
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
|
+
|
|
828
885
|
/** One run, or null */
|
|
829
886
|
async function get(runId) {
|
|
830
887
|
const db = await auth.store();
|
|
@@ -844,6 +901,289 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
844
901
|
return followable(await auth.store(), now()).length > 0;
|
|
845
902
|
}
|
|
846
903
|
|
|
904
|
+
// -------------------------------------------------------------------------
|
|
905
|
+
// Requests written by hand (issue #98)
|
|
906
|
+
// -------------------------------------------------------------------------
|
|
907
|
+
|
|
908
|
+
const handMode = handWrittenMode(config);
|
|
909
|
+
|
|
910
|
+
/** The refused and ignored hand-written blocks of the last days, newest first, for the Runs view: who wrote them, where, and why nothing started */
|
|
911
|
+
function handRefused(db, at) {
|
|
912
|
+
const rows = /** @type {{ at: string, login: string, target: string, request: string, answer: string | null }[]} */ (db.prepare("SELECT at, login, target, request, answer FROM actions WHERE action = 'agent-hand' AND (target = ? OR target LIKE ?) AND at > ? ORDER BY id DESC LIMIT 200")
|
|
913
|
+
.all(repo, `${repo}#%`, iso(at - HAND_SHOWN_MS)));
|
|
914
|
+
const out = [];
|
|
915
|
+
for (const r of rows) {
|
|
916
|
+
const a = safeJson(r.answer) ?? {};
|
|
917
|
+
if (a.accepted !== false) continue;
|
|
918
|
+
const q = safeJson(r.request) ?? {};
|
|
919
|
+
out.push({ at: r.at, by: r.login, number: Number(r.target.slice(r.target.indexOf('#') + 1)) || null, runId: typeof q.runId === 'string' ? q.runId : null, url: typeof a.url === 'string' ? a.url : null, why: typeof a.why === 'string' ? a.why : 'malformed', reason: typeof a.reason === 'string' ? a.reason : '' });
|
|
920
|
+
if (out.length >= HAND_SHOWN) break;
|
|
921
|
+
}
|
|
922
|
+
return out;
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* The request blocks of a comment that have no run id in their fence (a bare `cornfield-run` fence), the ones a maintainer writes by hand when
|
|
927
|
+
* cornfield is to assign the id: `{ ok, request | error }` for each, in order. The JSON may leave out `version`, `runId`, `requestedBy` and
|
|
928
|
+
* `requestedAt` (cornfield writes them: the author is the comment's, the time is when it was posted); everything else is checked as any request.
|
|
929
|
+
*/
|
|
930
|
+
function bareBlocks(text, login, postedAt, commentId) {
|
|
931
|
+
const out = [];
|
|
932
|
+
let index = 0;
|
|
933
|
+
if (typeof text !== 'string' || !text.includes(RUN_TAG)) return out;
|
|
934
|
+
for (const b of fencedBlocks(text.slice(0, MAX_TEXT_CHARS).replace(/\r\n?/g, '\n'))) {
|
|
935
|
+
if (b.fence !== '```' || !b.end || b.info.trim() !== RUN_TAG) continue;
|
|
936
|
+
if (out.length >= MAX_BLOCKS) break;
|
|
937
|
+
const id = handRunId(commentId, index++, postedAt);
|
|
938
|
+
if (b.body.length > MAX_BLOCK_CHARS) { out.push({ ok: false, error: `The block is longer than ${MAX_BLOCK_CHARS} characters.` }); continue; }
|
|
939
|
+
let json;
|
|
940
|
+
try { json = JSON.parse(b.body); } catch { out.push({ ok: false, error: 'The block is not JSON (it holds exactly one object).' }); continue; }
|
|
941
|
+
if (!isObject(json)) { out.push({ ok: false, error: 'A request is a JSON object.' }); continue; }
|
|
942
|
+
if (json.runId !== undefined && !isRunId(json.runId)) { out.push({ ok: false, error: '"runId" is "run-" and a 26 character ULID; leave it out and cornfield assigns one.' }); continue; }
|
|
943
|
+
const checked = validateRequest({ version: CONTRACT_VERSION, ...json, runId: json.runId ?? id, requestedBy: login, requestedAt: postedAt }, { profiles });
|
|
944
|
+
out.push(checked.ok ? { ok: true, request: checked.value, assigned: json.runId === undefined } : { ok: false, error: checked.error });
|
|
945
|
+
}
|
|
946
|
+
return out;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* The id cornfield assigns to a bare fence: the same for the same block on every look and after a restart (the time the comment was posted,
|
|
951
|
+
* then bits of a hash of the repo, the comment and the block's place in it), so a block is never taken twice under two ids
|
|
952
|
+
*/
|
|
953
|
+
function handRunId(commentId, index, postedAt) {
|
|
954
|
+
const ms = Date.parse(postedAt);
|
|
955
|
+
const digest = createHash('sha256').update(`${repo}\0${commentId}\0${index}`).digest();
|
|
956
|
+
return newRunId({ now: () => (Number.isSafeInteger(ms) && ms >= 0 ? ms : 0), random: () => digest.subarray(0, 10) });
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** Whether the engine looks for requests written by hand (`agents.handWritten`): the spec poll asks, so it runs even with no run to follow */
|
|
960
|
+
const discovers = handMode !== false;
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Reads the comments of the open issues and pull requests for `cornfield-run` request blocks a maintainer wrote by hand, and makes a run of
|
|
964
|
+
* each valid one (the steps in this module's header, "Requests written by hand"). One look reads at most `MAX_HAND_READS` conversations, the
|
|
965
|
+
* ones that moved earliest since they were last read; every block is judged once (`run_seen`, an audit row). Never throws.
|
|
966
|
+
* @param {import('./forge.js').Forge} forge a signed-in maintainer's
|
|
967
|
+
* @returns {Promise<{ read: number, imported: number, refused: number }>}
|
|
968
|
+
*/
|
|
969
|
+
function discover(forge) {
|
|
970
|
+
if (!discovers) return Promise.resolve({ read: 0, imported: 0, refused: 0 });
|
|
971
|
+
if (discovering) return discovering;
|
|
972
|
+
discovering = discoverRuns(forge)
|
|
973
|
+
.catch((err) => {
|
|
974
|
+
log(`a look for requests written by hand failed: ${words(err)}`);
|
|
975
|
+
return { read: 0, imported: 0, refused: 0 };
|
|
976
|
+
})
|
|
977
|
+
.finally(() => { discovering = null; });
|
|
978
|
+
return discovering;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
async function discoverRuns(forge) {
|
|
982
|
+
const out = { read: 0, imported: 0, refused: 0 };
|
|
983
|
+
const db = await auth.store();
|
|
984
|
+
const at = now();
|
|
985
|
+
const label = ideaLabel(config);
|
|
986
|
+
const wanted = (x) => handMode === 'all' || (label !== null && Array.isArray(x.labels) && x.labels.includes(label));
|
|
987
|
+
const seen = (key) => db.prepare("SELECT 1 FROM run_seen WHERE run_id = '' AND key = ?").get(key) !== undefined;
|
|
988
|
+
const mark = (key) => db.prepare("INSERT OR IGNORE INTO run_seen (run_id, key, at) VALUES ('', ?, ?)").run(key, iso(at));
|
|
989
|
+
// Where the last look got to (`hand-since:<time>`): only what changed since is listed, the least recently changed first, so a busy repo's
|
|
990
|
+
// oldest change is read before a newer one and none is starved. Never further back than agents.quietAfter: an older request would be refused as old
|
|
991
|
+
const cursorRow = /** @type {{ key: string } | undefined} */ (db.prepare("SELECT key FROM run_seen WHERE run_id = '' AND key LIKE 'hand-since:%'").get());
|
|
992
|
+
const since = Math.max(at - quietMs, cursorRow ? Date.parse(cursorRow.key.slice('hand-since:'.length)) || 0 : 0);
|
|
993
|
+
/** @type {{ number: number, updatedAt: string, labels: string[] }[]} */
|
|
994
|
+
let targets;
|
|
995
|
+
try {
|
|
996
|
+
// `since` is "at or after": what shares the second the cursor stopped at is listed again, and skipped by its key
|
|
997
|
+
targets = await forge.changed({ since: iso(since), limit: HAND_TARGETS });
|
|
998
|
+
} catch (err) {
|
|
999
|
+
log(`the open issues and pull requests could not be listed for requests written by hand: ${words(err)}`);
|
|
1000
|
+
return out;
|
|
1001
|
+
}
|
|
1002
|
+
let cursor = null;
|
|
1003
|
+
let held = false;
|
|
1004
|
+
const advance = (t) => { if (!held && Number.isFinite(Date.parse(t.updatedAt))) cursor = t.updatedAt; };
|
|
1005
|
+
const maintainerOf = new Map();
|
|
1006
|
+
const isMaintainerLogin = (login) => {
|
|
1007
|
+
const k = lower(login);
|
|
1008
|
+
if (!maintainerOf.has(k)) maintainerOf.set(k, forge.permission(repo, login).then(isMaintainer));
|
|
1009
|
+
return maintainerOf.get(k);
|
|
1010
|
+
};
|
|
1011
|
+
let poster = null;
|
|
1012
|
+
const posterLogin = async () => (poster ??= await forge.me().then((m) => m.login, () => null));
|
|
1013
|
+
let judged = 0;
|
|
1014
|
+
let fresh = 0;
|
|
1015
|
+
for (const t of targets) {
|
|
1016
|
+
if (!wanted(t)) { advance(t); continue; }
|
|
1017
|
+
const scanKey = `scan:${t.number}@${t.updatedAt}`;
|
|
1018
|
+
if (seen(scanKey)) { advance(t); continue; }
|
|
1019
|
+
fresh += 1;
|
|
1020
|
+
// The rest wait for the next look, which starts here
|
|
1021
|
+
if (out.read >= MAX_HAND_READS || judged >= MAX_HAND_JUDGED) break;
|
|
1022
|
+
let comments;
|
|
1023
|
+
try {
|
|
1024
|
+
comments = await forge.comments(t.number);
|
|
1025
|
+
} catch (err) {
|
|
1026
|
+
log(`the comments on #${t.number} could not be read for requests written by hand: ${words(err)}`);
|
|
1027
|
+
held = true;
|
|
1028
|
+
continue;
|
|
1029
|
+
}
|
|
1030
|
+
out.read += 1;
|
|
1031
|
+
const standing = new Map();
|
|
1032
|
+
try {
|
|
1033
|
+
for (const login of runAuthors(comments)) standing.set(lower(login), await isMaintainerLogin(login));
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
log(`who wrote the comments on #${t.number} could not be asked: ${words(err)}`);
|
|
1036
|
+
held = true;
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
1039
|
+
const rowOf = (runId) => /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(runId));
|
|
1040
|
+
let waiting = false;
|
|
1041
|
+
/** @type {{ login: string | null, request: object, answer: object, number: number }[]} */
|
|
1042
|
+
const audits = [];
|
|
1043
|
+
const counts = new Map();
|
|
1044
|
+
const keyOf = (commentId, runId, kind) => {
|
|
1045
|
+
const base = `h:${commentId}:${runId ?? '-'}:${kind}`;
|
|
1046
|
+
const n = counts.get(base) ?? 0;
|
|
1047
|
+
counts.set(base, n + 1);
|
|
1048
|
+
return `${base}:${n}`;
|
|
1049
|
+
};
|
|
1050
|
+
/** Writes one block's outcome down once: its key is kept first, then the audit row follows; true when it is new */
|
|
1051
|
+
const judge = (comment, key, runId, by, answer) => {
|
|
1052
|
+
if (seen(key)) return false;
|
|
1053
|
+
mark(key);
|
|
1054
|
+
judged += 1;
|
|
1055
|
+
audits.push({ login: by ?? 'unknown', request: { runId, type: 'request', comment: comment.id }, answer: { ...answer, ...(comment.url ? { url: comment.url } : {}) }, number: t.number });
|
|
1056
|
+
return true;
|
|
1057
|
+
};
|
|
1058
|
+
const EDITED = 'the comment was edited after it was posted, so its request is not believed';
|
|
1059
|
+
const NOT_MAINTAINER = (by) => `${by ?? 'the author'} is not a maintainer now, and only a maintainer's request starts a run`;
|
|
1060
|
+
|
|
1061
|
+
const found = runBlocksOf(comments, { trust: (login, block) => block.type === 'request' && standing.get(lower(login)) === true, profiles });
|
|
1062
|
+
// Which comments hold a request block for each run id, in the order they were written (comments come oldest first)
|
|
1063
|
+
/** @type {Map<string, string[]>} */
|
|
1064
|
+
const holders = new Map();
|
|
1065
|
+
for (const b of [...found.blocks, ...found.ignored]) if (b.type === 'request') holders.set(b.runId, [...(holders.get(b.runId) ?? []), b.comment.id]);
|
|
1066
|
+
/**
|
|
1067
|
+
* Whether a block is cornfield's reply naming the id it assigned to a bare fence: the run is a hand-written one, its own comment holds no
|
|
1068
|
+
* block with that id, and this is the first other comment that does. A later one is a copy
|
|
1069
|
+
*/
|
|
1070
|
+
const isReply = (runId, commentId) => {
|
|
1071
|
+
const row = rowOf(runId);
|
|
1072
|
+
if (!row || row.via !== 'hand' || row.comment_id === commentId) return false;
|
|
1073
|
+
const list = (holders.get(runId) ?? []).filter((id) => id !== row.comment_id);
|
|
1074
|
+
return !(holders.get(runId) ?? []).includes(row.comment_id) && list[0] === commentId;
|
|
1075
|
+
};
|
|
1076
|
+
/** Posts the reply that names the id cornfield assigned, as the poll's signed-in maintainer; false when the forge said no */
|
|
1077
|
+
const reply = async (request) => {
|
|
1078
|
+
const by = await posterLogin();
|
|
1079
|
+
// Refresh looks as whoever pressed it: only a maintainer's sign-in posts a request block, so anyone else's leaves it to the poll's next look
|
|
1080
|
+
if (!by || !(await isMaintainerLogin(by).catch(() => false))) { waiting = true; return null; }
|
|
1081
|
+
try {
|
|
1082
|
+
const posted = await forge.comment(t.number, formatRunComment(request.runId, request, {
|
|
1083
|
+
profiles,
|
|
1084
|
+
line: `Run \`${request.runId}\` is the id cornfield assigned to ${request.requestedBy}'s request above, written by hand: a ${request.kind} run, followed like any other. The request is ${request.requestedBy}'s; this reply was posted by cornfield${by ? ` with ${by}'s sign-in` : ''}.`,
|
|
1085
|
+
}));
|
|
1086
|
+
return { comment: posted.id, url: posted.url ?? null, postedBy: by };
|
|
1087
|
+
} catch (err) {
|
|
1088
|
+
log(`the id of a request written by hand on #${t.number} could not be posted, so it is posted on a later look: ${words(err)}`);
|
|
1089
|
+
waiting = true;
|
|
1090
|
+
return null;
|
|
1091
|
+
}
|
|
1092
|
+
};
|
|
1093
|
+
|
|
1094
|
+
/** Takes a place for one request from a maintainer; null when there is nothing to say (cornfield's own, or left for the next look), else the outcome */
|
|
1095
|
+
const take = async (comment, request, assigned) => {
|
|
1096
|
+
const row = rowOf(request.runId);
|
|
1097
|
+
if (row) {
|
|
1098
|
+
// cornfield's own request, or one taken before: the run is that comment's
|
|
1099
|
+
if (row.comment_id === comment.id) return null;
|
|
1100
|
+
// cornfield has reserved the id and is about to post it: not yet anyone's copy, so looked at again next time
|
|
1101
|
+
if (row.transport === 'forge' && row.comment_id === '') { waiting = true; return null; }
|
|
1102
|
+
return { accepted: false, why: 'duplicate', reason: `run ${row.run_id} already has this id, so this block is not imported again (cornfield never starts a second run for one block). Write a block without an id and cornfield assigns one` };
|
|
1103
|
+
}
|
|
1104
|
+
if (at - Date.parse(request.requestedAt) >= quietMs) return { accepted: false, why: 'old', reason: 'posted more than agents.quietAfter ago, so the run would be quiet at once and count for nothing; write it again to ask now' };
|
|
1105
|
+
try {
|
|
1106
|
+
reserve(db, request, { target: t.number, who: { userId: '' }, via: null, force: false, hand: { comment } });
|
|
1107
|
+
} catch (err) {
|
|
1108
|
+
if (err instanceof Refused) return { accepted: false, why: err.code ?? 'refused', reason: err.message };
|
|
1109
|
+
throw err;
|
|
1110
|
+
}
|
|
1111
|
+
// On push and pull the run goes out as any request does: the hook is the delivery, the queue holds it for a runner to claim
|
|
1112
|
+
if (transport !== 'forge') hooks?.emit('agent.requested', { request, actor: request.requestedBy });
|
|
1113
|
+
// The thread stays the record: the id cornfield assigned is written beside the request, as a block a runner can read. The run is kept
|
|
1114
|
+
// if that fails (on pull it may be claimed already): the next look posts it
|
|
1115
|
+
const posted = assigned ? await reply(request) : null;
|
|
1116
|
+
return { accepted: true, kind: request.kind, transport, ...(posted ? { reply: posted } : {}) };
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
/** @type {{ comment: { id: string, url: string | null }, by: string, request: any, assigned: boolean }[]} */
|
|
1120
|
+
const accepted = [];
|
|
1121
|
+
for (const b of found.blocks) accepted.push({ comment: b.comment, by: b.by, request: { ...b.value, requestedBy: b.by, requestedAt: b.at }, assigned: false });
|
|
1122
|
+
for (const c of comments) {
|
|
1123
|
+
const by = c.author?.login ?? null;
|
|
1124
|
+
if (!by || typeof c.body !== 'string') continue;
|
|
1125
|
+
const maintainer = standing.get(lower(by)) === true;
|
|
1126
|
+
const edited = c.updatedAt !== undefined && !(Date.parse(c.updatedAt) - Date.parse(c.createdAt) <= EDIT_GRACE_MS);
|
|
1127
|
+
const comment = { id: String(c.id), url: c.url ?? null };
|
|
1128
|
+
for (const r of bareBlocks(c.body, by, c.createdAt, comment.id)) {
|
|
1129
|
+
// Not a maintainer's: a block that is not even a request is nobody's business; a good one is shown as ignored, with the reason
|
|
1130
|
+
if (!r.ok) { if (maintainer && judge(comment, keyOf(comment.id, null, 'refused'), null, by, { accepted: false, why: 'malformed', reason: r.error })) out.refused += 1; continue; }
|
|
1131
|
+
if (!maintainer || edited) { if (judge(comment, keyOf(comment.id, r.request.runId, edited && maintainer ? 'edited' : 'author'), r.request.runId, by, { accepted: false, why: !maintainer ? 'author' : 'edited', reason: !maintainer ? NOT_MAINTAINER(by) : EDITED })) out.refused += 1; continue; }
|
|
1132
|
+
accepted.push({ comment, by, request: r.request, assigned: r.assigned });
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
accepted.sort((x, y) => Date.parse(x.request.requestedAt) - Date.parse(y.request.requestedAt) || Number(x.comment.id) - Number(y.comment.id));
|
|
1136
|
+
for (const a of accepted) {
|
|
1137
|
+
const key = keyOf(a.comment.id, a.request.runId, 'request');
|
|
1138
|
+
if (isReply(a.request.runId, a.comment.id)) continue;
|
|
1139
|
+
// An id cornfield assigned whose reply is not in the thread (the forge said no, or cornfield stopped before it was posted): posted now
|
|
1140
|
+
const row = rowOf(a.request.runId);
|
|
1141
|
+
if (a.assigned && row && row.comment_id === a.comment.id && !(holders.get(a.request.runId) ?? []).length) {
|
|
1142
|
+
const posted = await reply(a.request);
|
|
1143
|
+
if (posted) await audit({ login: a.by, action: 'agent-hand', target: `${repo}#${t.number}`, request: { runId: a.request.runId, type: 'request', comment: a.comment.id }, answer: { accepted: true, kind: a.request.kind, transport: row.transport, reply: posted } });
|
|
1144
|
+
if (!seen(key)) mark(key);
|
|
1145
|
+
continue;
|
|
1146
|
+
}
|
|
1147
|
+
if (seen(key)) continue;
|
|
1148
|
+
const outcome = await take(a.comment, a.request, a.assigned);
|
|
1149
|
+
if (outcome === null) continue;
|
|
1150
|
+
judge(a.comment, key, a.request.runId, a.by, outcome);
|
|
1151
|
+
if (outcome.accepted) out.imported += 1; else out.refused += 1;
|
|
1152
|
+
}
|
|
1153
|
+
for (const b of found.ignored) {
|
|
1154
|
+
if (b.type !== 'request') continue;
|
|
1155
|
+
// cornfield's own request (or its reply), by a maintainer who has since stopped being one, is not a stranger's
|
|
1156
|
+
const own = rowOf(b.runId);
|
|
1157
|
+
if (own && own.comment_id === b.comment.id) continue;
|
|
1158
|
+
if (isReply(b.runId, b.comment.id)) continue;
|
|
1159
|
+
if (judge(b.comment, keyOf(b.comment.id, b.runId, b.why), b.runId, b.by, { accepted: false, why: b.why, reason: b.why === 'edited' ? EDITED : NOT_MAINTAINER(b.by) })) out.refused += 1;
|
|
1160
|
+
}
|
|
1161
|
+
// What is not strictly a request, from a maintainer: shown with the reason. A block of a run cornfield has (a report with a stray key) is the follow's to judge
|
|
1162
|
+
for (const r of found.refused) {
|
|
1163
|
+
if (r.error.startsWith('The fence names ""')) continue; // a fence with no id: read above
|
|
1164
|
+
if (!r.by || standing.get(lower(r.by)) !== true) continue;
|
|
1165
|
+
if (r.runId && rowOf(r.runId)) continue;
|
|
1166
|
+
if (judge(r.comment, keyOf(r.comment.id, r.runId, 'refused'), r.runId, r.by, { accepted: false, why: 'malformed', reason: r.error })) out.refused += 1;
|
|
1167
|
+
}
|
|
1168
|
+
for (const a of audits) await audit({ login: a.login ?? 'unknown', action: 'agent-hand', target: `${repo}#${a.number}`, request: a.request, status: null, answer: a.answer });
|
|
1169
|
+
// Read at this update: not read again until the conversation moves, unless something was left for the next look (which then starts here)
|
|
1170
|
+
if (waiting) held = true;
|
|
1171
|
+
else {
|
|
1172
|
+
db.prepare("DELETE FROM run_seen WHERE run_id = '' AND key LIKE ?").run(`scan:${t.number}@%`);
|
|
1173
|
+
mark(scanKey);
|
|
1174
|
+
advance(t);
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
// A page of only what was read before, all of one second, would be listed again and again: the look steps past that second once it is a
|
|
1178
|
+
// minute old (nothing more can be written in it then)
|
|
1179
|
+
if (!held && fresh === 0 && cursor !== null && Date.parse(cursor) <= since && Date.parse(cursor) < at - 60_000) cursor = iso(Date.parse(cursor) + 1000);
|
|
1180
|
+
if (cursor !== null) {
|
|
1181
|
+
db.prepare("DELETE FROM run_seen WHERE run_id = '' AND key LIKE 'hand-since:%'").run();
|
|
1182
|
+
mark(`hand-since:${cursor}`);
|
|
1183
|
+
}
|
|
1184
|
+
return out;
|
|
1185
|
+
}
|
|
1186
|
+
|
|
847
1187
|
/**
|
|
848
1188
|
* Looks at the forge for what the runs I follow have left (the steps in this module's header). One at a time: a follow that is running
|
|
849
1189
|
* is the answer to another asked meanwhile. Never throws; resolves with a count.
|
|
@@ -1406,7 +1746,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1406
1746
|
return hit ? hit.run_id : null;
|
|
1407
1747
|
}
|
|
1408
1748
|
|
|
1409
|
-
return { request, stop, answer, list, get, follow, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
|
|
1749
|
+
return { request, stop, answer, list, get, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
|
|
1410
1750
|
}
|
|
1411
1751
|
|
|
1412
1752
|
/** @typedef {ReturnType<typeof createRuns>} Runs */
|
package/server/forge-forgejo.js
CHANGED
|
@@ -191,6 +191,14 @@ export function createForgejoForge(forge, { token = null, fetch, apiUrl, timeout
|
|
|
191
191
|
return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
|
|
192
192
|
},
|
|
193
193
|
|
|
194
|
+
async changed({ since, limit }) {
|
|
195
|
+
// Without `type` the issues listing holds both kinds; it has no sort, so every page is read and sorted here, oldest update first
|
|
196
|
+
const q = new URLSearchParams({ state: 'open', since, limit: String(PER_PAGE) });
|
|
197
|
+
const all = (await client.list(`repos/${repo}/issues?${q}`, { what: `the open issues and pull requests of ${forge.repo} updated since ${since}` }))
|
|
198
|
+
.map((i) => ({ number: i.number, pull: Boolean(i.pull_request), labels: labelNames(i.labels), updatedAt: i.updated_at }));
|
|
199
|
+
return all.sort((x, y) => Date.parse(x.updatedAt) - Date.parse(y.updatedAt) || x.number - y.number).slice(0, limit);
|
|
200
|
+
},
|
|
201
|
+
|
|
194
202
|
async pull(n) {
|
|
195
203
|
return toPull((await client.request('GET', `repos/${repo}/pulls/${n}`, { what: pullWhat(n) })).body);
|
|
196
204
|
},
|
package/server/forge-github.js
CHANGED
|
@@ -190,6 +190,13 @@ export function createGitHubForge(forge, { token = null, fetch, apiUrl, timeoutM
|
|
|
190
190
|
return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
|
|
191
191
|
},
|
|
192
192
|
|
|
193
|
+
async changed({ since, limit }) {
|
|
194
|
+
// The issues listing holds the pull requests too: one call for both, oldest update first so a busy repo's earliest change is never cut off
|
|
195
|
+
const q = new URLSearchParams({ state: 'open', sort: 'updated', direction: 'asc', since, per_page: String(PER_PAGE) });
|
|
196
|
+
return (await client.list(`repos/${repo}/issues?${q}`, { what: `the open issues and pull requests of ${forge.repo} updated since ${since}`, limit }))
|
|
197
|
+
.map((i) => ({ number: i.number, pull: Boolean(i.pull_request), labels: labelNames(i.labels), updatedAt: i.updated_at }));
|
|
198
|
+
},
|
|
199
|
+
|
|
193
200
|
async pull(n) {
|
|
194
201
|
return toPull((await client.request('GET', `repos/${repo}/pulls/${n}`, { what: pullWhat(n) })).body);
|
|
195
202
|
},
|
package/server/forge.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* permission(repo, login) their permission on a repo: admin | maintain | write | triage | read | none
|
|
11
11
|
* issues({ state, labels, limit }) issues, not pull requests, newest first
|
|
12
12
|
* pulls({ state, limit }) pull requests, newest first
|
|
13
|
+
* changed({ since, limit }) the open issues and pull requests updated at or after `since`, the least recently updated first:
|
|
14
|
+
* `{ number, pull, labels, updatedAt }` each, one listing for both (what a look for hand-written requests reads)
|
|
13
15
|
* pull(n) one pull request (its head, its state)
|
|
14
16
|
* issue(n) one issue (not a pull request: that is `not-found`)
|
|
15
17
|
* searchIssues(words) the issues whose text holds the words (one page; the forge's search, which can lag a moment)
|
|
@@ -70,6 +72,8 @@
|
|
|
70
72
|
* @typedef {{ state?: 'open' | 'closed' | 'all', labels?: string[], limit?: number }} IssueQuery
|
|
71
73
|
* @typedef {{ state?: 'open' | 'closed' | 'all', limit?: number }} PullQuery
|
|
72
74
|
* @typedef {{ limit?: number }} RunQuery
|
|
75
|
+
* @typedef {{ since: string, limit?: number }} ChangedQuery
|
|
76
|
+
* @typedef {{ number: number, pull: boolean, labels: string[], updatedAt: string }} Changed
|
|
73
77
|
* @typedef {'merge' | 'squash' | 'rebase'} MergeMethod
|
|
74
78
|
* @typedef {{
|
|
75
79
|
* forge: 'github' | 'forgejo', repo: string,
|
|
@@ -77,6 +81,7 @@
|
|
|
77
81
|
* permission(repo: string, login: string): Promise<Permission>,
|
|
78
82
|
* issues(query?: IssueQuery): Promise<Issue[]>,
|
|
79
83
|
* pulls(query?: PullQuery): Promise<Pull[]>,
|
|
84
|
+
* changed(query: ChangedQuery): Promise<Changed[]>,
|
|
80
85
|
* pull(n: number): Promise<Pull>,
|
|
81
86
|
* issue(n: number): Promise<Issue>,
|
|
82
87
|
* searchIssues(words: string): Promise<Issue[]>,
|
|
@@ -102,7 +107,8 @@
|
|
|
102
107
|
* createReleaseDraft(input: ReleaseDraftInput): Promise<ReleaseDraft>,
|
|
103
108
|
* rateLimit(): import('./forge-http.js').RateLimit | null,
|
|
104
109
|
* }} Forge
|
|
105
|
-
* @typedef {Omit<Forge, 'forge' | 'repo' | 'merge' | 'issues' | 'pulls' | 'runs'> & {
|
|
110
|
+
* @typedef {Omit<Forge, 'forge' | 'repo' | 'merge' | 'issues' | 'pulls' | 'runs' | 'changed'> & {
|
|
111
|
+
* changed(query: Required<ChangedQuery>): Promise<Changed[]>,
|
|
106
112
|
* issues(query: Required<IssueQuery>): Promise<Issue[]>,
|
|
107
113
|
* pulls(query: Required<PullQuery>): Promise<Pull[]>,
|
|
108
114
|
* runs(query: Required<RunQuery>): Promise<Run[]>,
|
|
@@ -118,7 +124,7 @@ import { ForgeError, FILE_MAX_BYTES } from './forge-http.js';
|
|
|
118
124
|
export { ForgeError, rateLimitWords } from './forge-http.js';
|
|
119
125
|
|
|
120
126
|
/** The calls of the interface (spec 0001 section 3, with `pull(n)`), and `rateLimit()`: what the last answer said is left */
|
|
121
|
-
export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
|
|
127
|
+
export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'changed', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
|
|
122
128
|
export const PERMISSIONS = Object.freeze(['admin', 'maintain', 'write', 'triage', 'read', 'none']);
|
|
123
129
|
/** A check that has finished and does not stand in the way: success, or one the forge says does not count */
|
|
124
130
|
export const GREEN_STATES = Object.freeze(['success', 'neutral', 'skipped']);
|
|
@@ -273,6 +279,13 @@ export function wrap(a, forge) {
|
|
|
273
279
|
},
|
|
274
280
|
issues: async (q) => a.issues(/** @type {Required<IssueQuery>} */ (query(q, true))),
|
|
275
281
|
pulls: async (q) => a.pulls(/** @type {Required<PullQuery>} */ (query(q, false))),
|
|
282
|
+
changed: async (q) => {
|
|
283
|
+
if (!q || typeof q !== 'object' || Array.isArray(q)) throw invalid('A query is an object.');
|
|
284
|
+
const { since, limit = DEFAULT_LIMIT } = q;
|
|
285
|
+
if (typeof since !== 'string' || !ISO_TIME.test(since) || Number.isNaN(Date.parse(since))) throw invalid('since is a time like 2026-11-05T09:00:00Z.');
|
|
286
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw invalid('The limit is a whole number above 0.');
|
|
287
|
+
return a.changed({ since: new Date(since).toISOString(), limit });
|
|
288
|
+
},
|
|
276
289
|
pull: async (n) => a.pull(number(n)),
|
|
277
290
|
issue: async (n) => a.issue(number(n)),
|
|
278
291
|
searchIssues: async (words) => {
|
package/server/server.js
CHANGED
|
@@ -239,7 +239,9 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
239
239
|
if (specMs !== null) specPoll?.start();
|
|
240
240
|
else if (specPoll && runs) {
|
|
241
241
|
// Runs asked for before a restart are followed again from the start
|
|
242
|
-
|
|
242
|
+
// (or, with agents.handWritten on, even with none: a request written by hand is found by the same look)
|
|
243
|
+
if (runs.discovers) specPoll.start();
|
|
244
|
+
else runs.hasWork().then((work) => { if (work && !serverClosed) specPoll.start(); }).catch(() => {});
|
|
243
245
|
}
|
|
244
246
|
});
|
|
245
247
|
server.on('close', () => { serverClosed = true; specPoll?.close(); runnerWatch?.close(); lander?.close(); hooks?.close(); auth.close(); });
|
package/server/spec-poll.js
CHANGED
|
@@ -28,6 +28,10 @@
|
|
|
28
28
|
* database alone, so an idle repo costs the forge nothing), the same tick hands the same maintainer's forge to `runs.follow`, which reads the
|
|
29
29
|
* runs' comments and pull requests. A server with no `spec.ready` hook still polls for runs (`specs: false`) and then does nothing else.
|
|
30
30
|
*
|
|
31
|
+
* **Requests written by hand** (issue #98, `agents.handWritten`, on by default) ride the same tick: before the follow, `runs.discover` lists the open issues and pull requests changed
|
|
32
|
+
* since its last look (one call, empty on an idle repo) and reads the comments of those that changed, so a maintainer's own `cornfield-run` block becomes a run and is followed in this very look.
|
|
33
|
+
* That makes the tick worth running with no run at all, so the server starts it for them too; `handWritten: false` returns to "only runs cornfield asked for".
|
|
34
|
+
*
|
|
31
35
|
* **Never in the way.** One tick runs at a time (the next is scheduled when one ends, so a slow forge cannot pile them up).
|
|
32
36
|
* A forge error is logged and never thrown; the next tick waits twice the interval until one succeeds. The timer is
|
|
33
37
|
* unref'd and `close()` clears it.
|
|
@@ -73,7 +77,7 @@ export async function findMaintainerForge({ auth, repo, now = Date.now }) {
|
|
|
73
77
|
* where: { proposals: string },
|
|
74
78
|
* auth: { store: () => Promise<import('node:sqlite').DatabaseSync>, forgeForUser: (userId: string) => Promise<import('./forge.js').Forge> },
|
|
75
79
|
* hooks: import('./hooks.js').Hooks | null,
|
|
76
|
-
* runs?: { hasWork: () => Promise<boolean>, follow: (forge: import('./forge.js').Forge) => Promise<unknown> } | null,
|
|
80
|
+
* runs?: { hasWork: () => Promise<boolean>, follow: (forge: import('./forge.js').Forge) => Promise<unknown>, discovers?: boolean, discover?: (forge: import('./forge.js').Forge) => Promise<{ imported: number }> } | null,
|
|
77
81
|
* specs?: boolean,
|
|
78
82
|
* intervalMs: number,
|
|
79
83
|
* now?: () => number,
|
|
@@ -125,7 +129,9 @@ export function createSpecPoll({ config, where, auth, hooks, runs = null, specs
|
|
|
125
129
|
} catch (err) {
|
|
126
130
|
log(`the runs could not be counted: ${words(err)}`);
|
|
127
131
|
}
|
|
128
|
-
|
|
132
|
+
// Requests written by hand (agents.handWritten) are looked for even when there is no run yet: that is how the first one is found
|
|
133
|
+
const discovers = Boolean(runs && runs.discovers && runs.discover);
|
|
134
|
+
if (!specs && !followRuns && !discovers) return 'ok';
|
|
129
135
|
let found;
|
|
130
136
|
try {
|
|
131
137
|
found = await maintainerForge();
|
|
@@ -161,6 +167,16 @@ export function createSpecPoll({ config, where, auth, hooks, runs = null, specs
|
|
|
161
167
|
out = 'error';
|
|
162
168
|
}
|
|
163
169
|
}
|
|
170
|
+
if (discovers && !closed) {
|
|
171
|
+
try {
|
|
172
|
+
const found2 = await /** @type {any} */ (runs).discover(found.forge);
|
|
173
|
+
// A run just found is followed in this same look
|
|
174
|
+
if (found2 && found2.imported > 0) followRuns = true;
|
|
175
|
+
} catch (err) {
|
|
176
|
+
log(`the requests written by hand could not be looked for: ${words(err)}`);
|
|
177
|
+
out = 'error';
|
|
178
|
+
}
|
|
179
|
+
}
|
|
164
180
|
if (followRuns && !closed) {
|
|
165
181
|
try {
|
|
166
182
|
await /** @type {NonNullable<typeof runs>} */ (runs).follow(found.forge);
|