@popcorn245/cornfield 0.15.0 → 0.17.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.
@@ -41,11 +41,42 @@
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
+ *
65
+ * ## Waiting, and the answer (issue #101)
66
+ *
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
68
+ * from the run (`answer`): **Continue**, **Stop** or a **reply** with text. Over push and pull the answer is kept on the run (one answer: a second
69
+ * replaces the first, until the runner reports again) and comes back through `GET /api/runs/<runId>` as `answer: { action, text?, at, by }`, the
70
+ * way `stopRequested` does. On the forge it is posted as a `cornfield-run` `answered` block, as the maintainer, like a stop request. A **Stop** is
71
+ * a stop request (`stop`), so it behaves in every way as a Stop does; the answer is recorded beside it. A report of `waiting` after another state
72
+ * clears the answer of the wait before. Hooks: `run.waiting` (the runner asked), `run.answered` (a maintainer answered; the action, never the text).
73
+ *
44
74
  * ## What counts as open
45
75
  *
46
76
  * A run is **open** unless it is finished or quiet (`statusOf`): finished is the runner's report `done`, `failed` or `stopped`, or its pull
47
77
  * request merged or closed; **quiet** is no report, push or pull request activity within `agents.quietAfter` (24h unless set). A quiet run
48
- * is shown as quiet and counts toward neither the cap nor the one-per-subject rule; a later report or push makes it open again.
78
+ * is shown as quiet and counts toward neither the cap nor the one-per-subject rule; a later report or push makes it open again. A run **waiting**
79
+ * on a maintainer (its runner reported `waiting`, nobody asked it to stop) is never quiet: a human owes it an answer, so it keeps counting.
49
80
  *
50
81
  * ## Following (`follow`)
51
82
  *
@@ -63,23 +94,24 @@
63
94
  * - **the branches**, for a run that has no pull request yet: a branch whose name holds the run id, and when its head moves
64
95
  *
65
96
  * Everything seen is kept in `runs` and `run_seen` (server/db.js) before any hook is sent, and each comment is judged once and each hook event
66
- * sent once (a `run_seen` key), so a restart re-reads the forge and fires nothing twice. Hooks: `run.claimed`, `run.state`, `run.stopRequested`,
67
- * `run.finished` (server/hooks.js).
97
+ * sent once (a `run_seen` key), so a restart re-reads the forge and fires nothing twice. Hooks: `run.claimed`, `run.state`, `run.waiting`, `run.answered`,
98
+ * `run.stopRequested`, `run.finished` (server/hooks.js).
68
99
  *
69
100
  * @typedef {import('../core/agent-contract.js').RunRequest} RunRequest
70
101
  * @typedef {{ run_id: string, repo: string, kind: string, profile: string | null, issue: number | null, proposal: string | null, thread: number | null,
71
102
  * target: number, comment_id: string, comment_url: string | null, request: string, requested_by: string, requested_by_id: string, requested_at: string,
72
103
  * via: string, state: string, reported_at: string | null, reported_by: string | null, note: string | null, url: string | null, tokens: number | null,
73
- * cost: number | null, transport: 'forge' | 'push' | 'pull', claimed_by: number | null, claimed_at: string | null, stop_requested_at: string | null, stop_requested_by: string | null, pull: number | null, pull_state: string | null,
104
+ * cost: number | null, transport: 'forge' | 'push' | 'pull', claimed_by: number | null, claimed_at: string | null, stop_requested_at: string | null, stop_requested_by: string | null, answer_action: string | null, answer_text: string | null, answer_at: string | null, answer_by: string | null, pull: number | null, pull_state: string | null,
74
105
  * pull_url: string | null, pull_by: string | null, pull_trusted: number, linked_via: string | null, branch: string | null, head_sha: string | null,
75
106
  * checks: string | null, last_activity: string }} RunRow
76
107
  */
77
108
 
78
109
  import fs from 'node:fs';
110
+ import { createHash } from 'node:crypto';
79
111
  import path from 'node:path';
80
112
  import { ForgeError, isMaintainer } from './forge.js';
81
- import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
82
- 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, quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
83
115
  import { runnerPresence } from './runner-presence.js';
84
116
  import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
85
117
  import { readTopology } from '../core/validate.js';
@@ -111,6 +143,15 @@ export const MAX_FILE_READS = 10;
111
143
  export const MENTIONS_KEEP_MS = 3_600_000;
112
144
  /** The queued requests a runner's listing answers at most, oldest first */
113
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;
114
155
  /** The runs that are over once the runner has said so */
115
156
  /** The keys of a request as the API and the button send it: the contract's fields, less what cornfield writes, plus `force` */
116
157
  export const REQUEST_BODY_KEYS = Object.freeze(['kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'force']);
@@ -127,13 +168,18 @@ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
127
168
  const words = (err) => (err instanceof Error ? err.message : String(err));
128
169
  const maxIso = (a, b) => (Date.parse(b) > Date.parse(a) ? b : a);
129
170
 
171
+ /** Whether a run is waiting on a maintainer: its runner reported `waiting` and nobody has asked it to stop. Such a run is exempt from quiet */
172
+ const waitsOnMaintainer = (row) => row.state === 'waiting' && !row.stop_requested_at;
173
+
130
174
  /**
131
175
  * What a run is, as of `nowMs`, from the runner's reports and what the forge shows. Pure.
132
176
  *
133
177
  * done / failed / stopped the runner's latest report
134
178
  * merged / closed its (trusted) pull request ended
135
- * quiet nothing happened within `quietMs`
179
+ * quiet nothing happened within `quietMs`, unless it is waiting (below)
136
180
  * stop-requested a maintainer asked it to stop and the runner has not said so
181
+ * waiting the runner's latest report: it asks a maintainer (open: the run is not over). A run waiting on a maintainer
182
+ * never goes quiet, so it keeps counting toward the cap; once a maintainer asks it to stop, or it reports again, quiet applies again
137
183
  * claimed / working the runner's latest report
138
184
  * working no report, but a (trusted) pull request or a branch carries its id: a silent runner is seen through what it pushes
139
185
  * requested asked for, nothing seen yet
@@ -149,7 +195,7 @@ export function statusOf(row, nowMs, quietMs) {
149
195
  let status;
150
196
  if (REPORT_FINISHED.includes(row.state)) status = row.state;
151
197
  else if (ended) status = /** @type {string} */ (row.pull_state);
152
- else if (nowMs - Date.parse(row.last_activity) >= quietMs) status = 'quiet';
198
+ else if (!waitsOnMaintainer(row) && nowMs - Date.parse(row.last_activity) >= quietMs) status = 'quiet';
153
199
  else if (row.stop_requested_at) status = 'stop-requested';
154
200
  else if (row.state !== 'requested') status = row.state;
155
201
  else status = (row.pull_trusted === 1 && row.pull) || row.branch ? 'working' : 'requested';
@@ -174,6 +220,11 @@ function subjectKeys(refs) {
174
220
 
175
221
  const subjectWords = (refs) => [refs.issue != null && `issue #${refs.issue}`, refs.thread != null && refs.thread !== refs.issue && `thread #${refs.thread}`, refs.proposal != null && `proposal ${refs.proposal}`].filter(Boolean).join(' and ');
176
222
 
223
+ /** A maintainer's answer to the latest wait as the API shows it (the runner reads the same), or null */
224
+ function answerOf(row) {
225
+ return row.answer_at ? { action: row.answer_action, ...(row.answer_text ? { text: row.answer_text } : {}), at: row.answer_at, by: row.answer_by } : null;
226
+ }
227
+
177
228
  /**
178
229
  * A run for the dashboard and the API: derived status, the request's limits beside the runner's report, no credential, nothing that is the
179
230
  * database's own. Text the runner wrote (a note, a link) is data for the page to escape.
@@ -188,12 +239,13 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
188
239
  return {
189
240
  runId: row.run_id, kind: row.kind, profile: row.profile,
190
241
  refs: { ...(row.issue != null ? { issue: row.issue } : {}), ...(row.proposal != null ? { proposal: row.proposal } : {}), ...(row.thread != null ? { thread: row.thread } : {}) },
191
- 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,
192
243
  claimedAt: row.claimed_at,
193
244
  comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
194
245
  limits,
195
246
  report: row.reported_at ? { state: row.state, at: row.reported_at, by: byFromText(row.reported_by), note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
196
247
  stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
248
+ answer: answerOf(row),
197
249
  pull: row.pull != null ? { number: row.pull, state: row.pull_state, url: row.pull_url, by: row.pull_by, trusted: row.pull_trusted === 1, via: row.linked_via } : null,
198
250
  branch: row.branch, headSha: row.head_sha, checks: row.checks, lastActivity: row.last_activity,
199
251
  ...extra,
@@ -276,6 +328,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
276
328
  const transport = /** @type {'forge' | 'push' | 'pull'} */ (agents.transport ?? 'forge');
277
329
  const log = (what) => console.error(`[cornfield] agent runs: ${what}`);
278
330
  let following = null;
331
+ let discovering = null;
279
332
 
280
333
  const audit = async (entry) => {
281
334
  try {
@@ -376,7 +429,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
376
429
  }
377
430
 
378
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`. */
379
- 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 }) {
380
433
  const at = now();
381
434
  const mine = subjectKeys(request.refs);
382
435
  db.exec('BEGIN IMMEDIATE');
@@ -406,10 +459,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
406
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');
407
460
  }
408
461
  }
409
- db.prepare(`INSERT INTO runs (run_id, repo, kind, profile, issue, proposal, thread, target, request, requested_by, requested_by_id, requested_at, via, last_activity, transport)
410
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
411
465
  .run(request.runId, repo, request.kind, request.profile ?? null, request.refs.issue ?? null, request.refs.proposal ?? null, request.refs.thread ?? null,
412
- 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);
413
467
  db.exec('COMMIT');
414
468
  } catch (err) {
415
469
  try { db.exec('ROLLBACK'); } catch { /* nothing was begun */ }
@@ -671,6 +725,109 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
671
725
  }
672
726
  }
673
727
 
728
+ /**
729
+ * A maintainer's answer to a run that reported `waiting`: `continue`, `stop` or a `reply` (text). Throws like `stop`.
730
+ * - **Stop** is `stop` itself (the same checks, block, audit row and hook), with the answer recorded beside it.
731
+ * - **Continue and reply** are kept on the run, replacing an earlier answer to the same wait; on the forge the `answered` block is posted
732
+ * first, in the same place as the request, as the maintainer who clicked. A run that is not waiting, is over, or was asked to stop is a 409.
733
+ * @param {RequestContext} ctx
734
+ * @param {{ runId: unknown, action?: unknown, text?: unknown, problem?: { status: number, message: string } }} input
735
+ */
736
+ async function answer(ctx, { runId, action, text, problem }) {
737
+ const { who, via = null } = ctx;
738
+ // A Stop to a run that is waiting is a stop request; anything else (not strictly an answer, no such run, not waiting) is refused below as an answer
739
+ const stopping = action === 'stop' && !problem && validateAnswer({ state: 'answered', action, ...(text !== undefined ? { text } : {}) }).ok
740
+ && typeof runId === 'string' && /** @type {RunRow | undefined} */ ((await auth.store()).prepare('SELECT state FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo))?.state === 'waiting';
741
+ if (stopping) {
742
+ const stopped = await stop(ctx, { runId, note: text, problem });
743
+ const db = await auth.store();
744
+ const stamp = iso(now());
745
+ const kept = db.prepare("UPDATE runs SET answer_action = 'stop', answer_text = ?, answer_at = ?, answer_by = ? WHERE run_id = ? AND state = 'waiting'")
746
+ .run(typeof text === 'string' && text.trim() !== '' ? text : null, stamp, who.login, stopped.run.runId).changes;
747
+ const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(stopped.run.runId));
748
+ if (kept) hooks?.emit('run.answered', { ...runPayload(after, who.login), action: 'stop' });
749
+ return { ...stopped, run: publicRun(after, now(), quietMs, extrasFor(db, [after], now()).get(after.run_id)) };
750
+ }
751
+ const at = ctx.limits.now ?? now;
752
+ const flood = countAttempt(ctx.limits, who.userId, at());
753
+ if (flood) throw flood;
754
+ let target = repo;
755
+ let done = false;
756
+ let release = () => {};
757
+ const asked = { ...(typeof runId === 'string' && runId.length <= 40 ? { runId } : {}), ...(typeof action === 'string' && action.length <= 10 ? { action } : {}), ...(typeof text === 'string' ? { textChars: text.length } : {}), ...(via ? { via: 'api', token: via.token } : {}) };
758
+ try {
759
+ if (problem) throw new Refused(problem.status, problem.message, 'invalid');
760
+ const checked = validateAnswer({ state: 'answered', action, ...(text !== undefined ? { text } : {}) });
761
+ if (!checked.ok) throw new Refused(400, checked.error, 'invalid');
762
+ const a = checked.value;
763
+ const db = await auth.store();
764
+ const row = typeof runId === 'string' ? /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo)) : undefined;
765
+ if (!row) throw new Refused(404, 'cornfield has no such run.', 'not-found');
766
+ target = `${repo}#${row.target}`;
767
+ release = throttle(ctx.limits, who.userId, `agent-answer|${row.run_id}`, at());
768
+ const forge = await ctx.forge();
769
+ const me = await forge.me();
770
+ if (String(me.id) !== who.userId) throw new Refused(403, 'The forge says this sign-in is someone else now; sign in again.', 'forbidden');
771
+ if (!isMaintainer(await forge.permission(repo, me.login))) throw new Refused(403, `Only the repo's maintainers answer agent runs; ${me.login} is not one now.`, 'forbidden');
772
+ const was = statusOf(row, now(), quietMs);
773
+ if (was.finished) throw new Refused(409, `Run ${row.run_id} is ${was.status}; there is nothing to answer.`, 'conflict');
774
+ if (row.stop_requested_at) throw new Refused(409, `${row.stop_requested_by ?? 'A maintainer'} already asked run ${row.run_id} to stop (${row.stop_requested_at}); the runner decides what that means.`, 'conflict');
775
+ if (row.state !== 'waiting') throw new Refused(409, `Run ${row.run_id} is not waiting for an answer (its runner last reported ${row.state}).`, 'conflict');
776
+ if (a.action === 'stop') throw new Refused(409, `Run ${row.run_id} changed while the answer was being taken; read it again.`, 'conflict');
777
+ if (ctx.stillAllowed) {
778
+ const why = await ctx.stillAllowed();
779
+ if (why) throw new Refused(403, why, 'forbidden');
780
+ }
781
+ const stamp = iso(now());
782
+ let posted = null;
783
+ if (row.transport === 'forge') {
784
+ let comment;
785
+ try {
786
+ comment = formatRunComment(row.run_id, a, { line: `Answered run \`${row.run_id}\`: ${a.action} (${me.login}, in cornfield${via ? `, through the agent API with the token \`${via.token.label}\`` : ''}).` });
787
+ } catch (err) {
788
+ throw new Refused(400, words(err), 'invalid');
789
+ }
790
+ posted = await forge.comment(row.target, comment);
791
+ }
792
+ db.exec('BEGIN IMMEDIATE');
793
+ try {
794
+ // The runner may have reported again while the forge was asked: it answered the wait it was in, so only a run still waiting takes it
795
+ // The block just posted is judged already, whatever comes of it: a follow must never read cornfield's own answer back as a maintainer's,
796
+ // not even one that came too late for the wait it answered (kept even when the answer is refused below)
797
+ if (posted) {
798
+ db.prepare('INSERT OR IGNORE INTO run_seen (run_id, key, at) VALUES (?, ?, ?)').run(row.run_id, `c:${posted.id}:${row.run_id}:answer:0`, stamp);
799
+ db.prepare('INSERT OR IGNORE INTO run_seen (run_id, key, at) VALUES (?, ?, ?)').run(row.run_id, `ev:answered:${posted.id}:c:${posted.id}:${row.run_id}:answer:0`, stamp);
800
+ }
801
+ const kept = db.prepare("UPDATE runs SET answer_action = ?, answer_text = ?, answer_at = ?, answer_by = ?, last_activity = MAX(last_activity, ?) WHERE run_id = ? AND state = 'waiting' AND stop_requested_at IS NULL")
802
+ .run(a.action, a.text ?? null, stamp, me.login, stamp, row.run_id).changes;
803
+ if (kept !== 1) {
804
+ db.exec('COMMIT');
805
+ throw new Refused(409, `Run ${row.run_id} changed while the answer was being taken; read it again.`, 'conflict');
806
+ }
807
+ // Two maintainers answering at once: the last write wins on the run, and the timeline keeps both
808
+ keepEvent(db, row.run_id, { key: posted ? `answer:${posted.id}` : `answer:cornfield:${stamp}:${me.login}`, at: stamp, kind: 'answered', actor: me.login, ref: a.action, note: a.text ?? null, url: posted ? posted.url ?? null : null });
809
+ db.exec('COMMIT');
810
+ } catch (err) {
811
+ try { db.exec('ROLLBACK'); } catch { /* nothing was begun */ }
812
+ throw err;
813
+ }
814
+ done = true;
815
+ await audit({ login: me.login, action: 'agent-answer', target, request: { ...asked, action: a.action, ...(a.text ? { textChars: a.text.length } : {}) }, status: 201, answer: posted ? { comment: posted.id, url: posted.url ?? null } : { transport: row.transport } });
816
+ const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
817
+ hooks?.emit('run.answered', { ...runPayload(after, me.login), action: a.action });
818
+ return { run: publicRun(after, now(), quietMs, extrasFor(db, [after], now()).get(after.run_id)), comment: posted ? { id: posted.id, url: posted.url ?? null } : null };
819
+ } catch (err) {
820
+ if (!done) {
821
+ const out = describe(err);
822
+ await audit({ login: who.login, action: 'agent-answer', target, request: asked, status: err instanceof ForgeError ? err.status ?? (err.code === 'unavailable' ? null : out.status) : out.status, answer: { error: out.error, code: out.code } });
823
+ if (!(err instanceof Refused) && !(err instanceof ForgeError)) log(`answering ${asked.runId ?? ''} failed: ${err instanceof Error ? err.stack || err.message : err}`);
824
+ }
825
+ throw err;
826
+ } finally {
827
+ release();
828
+ }
829
+ }
830
+
674
831
  /** The body of a run hook event: which run, in what state, about what, caused by whom */
675
832
  function runPayload(row, actor) {
676
833
  return { runId: row.run_id, state: statusOf(row, now(), quietMs).status, pull: row.pull ?? undefined, issue: row.issue ?? row.thread ?? undefined, actor };
@@ -698,6 +855,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
698
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,
699
856
  triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
700
857
  refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
858
+ handWritten: { mode: handMode, refused: discovers ? handRefused(db, at) : [] },
701
859
  };
702
860
  }
703
861
 
@@ -708,10 +866,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
708
866
  return row ? publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)) : null;
709
867
  }
710
868
 
711
- /** The runs a follow looks at: posted, not over for good (a trusted pull request merged or closed), and active within the follow window */
869
+ /** The runs a follow looks at: posted, not over for good (a trusted pull request merged or closed), and active within the follow window or waiting on a maintainer */
712
870
  function followable(db, at) {
713
871
  const window = Math.max(2 * quietMs, FOLLOW_FLOOR_MS);
714
- return /** @type {RunRow[]} */ (db.prepare(`SELECT * FROM runs WHERE repo = ? AND ${POSTED} AND last_activity > ? AND NOT (pull_trusted = 1 AND pull_state IN ('merged', 'closed')) ORDER BY last_activity DESC LIMIT ?`)
872
+ return /** @type {RunRow[]} */ (db.prepare(`SELECT * FROM runs WHERE repo = ? AND ${POSTED} AND (last_activity > ? OR (state = 'waiting' AND stop_requested_at IS NULL)) AND NOT (pull_trusted = 1 AND pull_state IN ('merged', 'closed')) ORDER BY last_activity DESC LIMIT ?`)
715
873
  .all(repo, iso(at - window), MAX_FOLLOWED));
716
874
  }
717
875
 
@@ -720,6 +878,289 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
720
878
  return followable(await auth.store(), now()).length > 0;
721
879
  }
722
880
 
881
+ // -------------------------------------------------------------------------
882
+ // Requests written by hand (issue #98)
883
+ // -------------------------------------------------------------------------
884
+
885
+ const handMode = handWrittenMode(config);
886
+
887
+ /** 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 */
888
+ function handRefused(db, at) {
889
+ 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")
890
+ .all(repo, `${repo}#%`, iso(at - HAND_SHOWN_MS)));
891
+ const out = [];
892
+ for (const r of rows) {
893
+ const a = safeJson(r.answer) ?? {};
894
+ if (a.accepted !== false) continue;
895
+ const q = safeJson(r.request) ?? {};
896
+ 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 : '' });
897
+ if (out.length >= HAND_SHOWN) break;
898
+ }
899
+ return out;
900
+ }
901
+
902
+ /**
903
+ * 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
904
+ * cornfield is to assign the id: `{ ok, request | error }` for each, in order. The JSON may leave out `version`, `runId`, `requestedBy` and
905
+ * `requestedAt` (cornfield writes them: the author is the comment's, the time is when it was posted); everything else is checked as any request.
906
+ */
907
+ function bareBlocks(text, login, postedAt, commentId) {
908
+ const out = [];
909
+ let index = 0;
910
+ if (typeof text !== 'string' || !text.includes(RUN_TAG)) return out;
911
+ for (const b of fencedBlocks(text.slice(0, MAX_TEXT_CHARS).replace(/\r\n?/g, '\n'))) {
912
+ if (b.fence !== '```' || !b.end || b.info.trim() !== RUN_TAG) continue;
913
+ if (out.length >= MAX_BLOCKS) break;
914
+ const id = handRunId(commentId, index++, postedAt);
915
+ if (b.body.length > MAX_BLOCK_CHARS) { out.push({ ok: false, error: `The block is longer than ${MAX_BLOCK_CHARS} characters.` }); continue; }
916
+ let json;
917
+ try { json = JSON.parse(b.body); } catch { out.push({ ok: false, error: 'The block is not JSON (it holds exactly one object).' }); continue; }
918
+ if (!isObject(json)) { out.push({ ok: false, error: 'A request is a JSON object.' }); continue; }
919
+ 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; }
920
+ const checked = validateRequest({ version: CONTRACT_VERSION, ...json, runId: json.runId ?? id, requestedBy: login, requestedAt: postedAt }, { profiles });
921
+ out.push(checked.ok ? { ok: true, request: checked.value, assigned: json.runId === undefined } : { ok: false, error: checked.error });
922
+ }
923
+ return out;
924
+ }
925
+
926
+ /**
927
+ * 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,
928
+ * 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
929
+ */
930
+ function handRunId(commentId, index, postedAt) {
931
+ const ms = Date.parse(postedAt);
932
+ const digest = createHash('sha256').update(`${repo}\0${commentId}\0${index}`).digest();
933
+ return newRunId({ now: () => (Number.isSafeInteger(ms) && ms >= 0 ? ms : 0), random: () => digest.subarray(0, 10) });
934
+ }
935
+
936
+ /** Whether the engine looks for requests written by hand (`agents.handWritten`): the spec poll asks, so it runs even with no run to follow */
937
+ const discovers = handMode !== false;
938
+
939
+ /**
940
+ * 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
941
+ * each valid one (the steps in this module's header, "Requests written by hand"). One look reads at most `MAX_HAND_READS` conversations, the
942
+ * ones that moved earliest since they were last read; every block is judged once (`run_seen`, an audit row). Never throws.
943
+ * @param {import('./forge.js').Forge} forge a signed-in maintainer's
944
+ * @returns {Promise<{ read: number, imported: number, refused: number }>}
945
+ */
946
+ function discover(forge) {
947
+ if (!discovers) return Promise.resolve({ read: 0, imported: 0, refused: 0 });
948
+ if (discovering) return discovering;
949
+ discovering = discoverRuns(forge)
950
+ .catch((err) => {
951
+ log(`a look for requests written by hand failed: ${words(err)}`);
952
+ return { read: 0, imported: 0, refused: 0 };
953
+ })
954
+ .finally(() => { discovering = null; });
955
+ return discovering;
956
+ }
957
+
958
+ async function discoverRuns(forge) {
959
+ const out = { read: 0, imported: 0, refused: 0 };
960
+ const db = await auth.store();
961
+ const at = now();
962
+ const label = ideaLabel(config);
963
+ const wanted = (x) => handMode === 'all' || (label !== null && Array.isArray(x.labels) && x.labels.includes(label));
964
+ const seen = (key) => db.prepare("SELECT 1 FROM run_seen WHERE run_id = '' AND key = ?").get(key) !== undefined;
965
+ const mark = (key) => db.prepare("INSERT OR IGNORE INTO run_seen (run_id, key, at) VALUES ('', ?, ?)").run(key, iso(at));
966
+ // 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
967
+ // 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
968
+ const cursorRow = /** @type {{ key: string } | undefined} */ (db.prepare("SELECT key FROM run_seen WHERE run_id = '' AND key LIKE 'hand-since:%'").get());
969
+ const since = Math.max(at - quietMs, cursorRow ? Date.parse(cursorRow.key.slice('hand-since:'.length)) || 0 : 0);
970
+ /** @type {{ number: number, updatedAt: string, labels: string[] }[]} */
971
+ let targets;
972
+ try {
973
+ // `since` is "at or after": what shares the second the cursor stopped at is listed again, and skipped by its key
974
+ targets = await forge.changed({ since: iso(since), limit: HAND_TARGETS });
975
+ } catch (err) {
976
+ log(`the open issues and pull requests could not be listed for requests written by hand: ${words(err)}`);
977
+ return out;
978
+ }
979
+ let cursor = null;
980
+ let held = false;
981
+ const advance = (t) => { if (!held && Number.isFinite(Date.parse(t.updatedAt))) cursor = t.updatedAt; };
982
+ const maintainerOf = new Map();
983
+ const isMaintainerLogin = (login) => {
984
+ const k = lower(login);
985
+ if (!maintainerOf.has(k)) maintainerOf.set(k, forge.permission(repo, login).then(isMaintainer));
986
+ return maintainerOf.get(k);
987
+ };
988
+ let poster = null;
989
+ const posterLogin = async () => (poster ??= await forge.me().then((m) => m.login, () => null));
990
+ let judged = 0;
991
+ let fresh = 0;
992
+ for (const t of targets) {
993
+ if (!wanted(t)) { advance(t); continue; }
994
+ const scanKey = `scan:${t.number}@${t.updatedAt}`;
995
+ if (seen(scanKey)) { advance(t); continue; }
996
+ fresh += 1;
997
+ // The rest wait for the next look, which starts here
998
+ if (out.read >= MAX_HAND_READS || judged >= MAX_HAND_JUDGED) break;
999
+ let comments;
1000
+ try {
1001
+ comments = await forge.comments(t.number);
1002
+ } catch (err) {
1003
+ log(`the comments on #${t.number} could not be read for requests written by hand: ${words(err)}`);
1004
+ held = true;
1005
+ continue;
1006
+ }
1007
+ out.read += 1;
1008
+ const standing = new Map();
1009
+ try {
1010
+ for (const login of runAuthors(comments)) standing.set(lower(login), await isMaintainerLogin(login));
1011
+ } catch (err) {
1012
+ log(`who wrote the comments on #${t.number} could not be asked: ${words(err)}`);
1013
+ held = true;
1014
+ continue;
1015
+ }
1016
+ const rowOf = (runId) => /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(runId));
1017
+ let waiting = false;
1018
+ /** @type {{ login: string | null, request: object, answer: object, number: number }[]} */
1019
+ const audits = [];
1020
+ const counts = new Map();
1021
+ const keyOf = (commentId, runId, kind) => {
1022
+ const base = `h:${commentId}:${runId ?? '-'}:${kind}`;
1023
+ const n = counts.get(base) ?? 0;
1024
+ counts.set(base, n + 1);
1025
+ return `${base}:${n}`;
1026
+ };
1027
+ /** Writes one block's outcome down once: its key is kept first, then the audit row follows; true when it is new */
1028
+ const judge = (comment, key, runId, by, answer) => {
1029
+ if (seen(key)) return false;
1030
+ mark(key);
1031
+ judged += 1;
1032
+ audits.push({ login: by ?? 'unknown', request: { runId, type: 'request', comment: comment.id }, answer: { ...answer, ...(comment.url ? { url: comment.url } : {}) }, number: t.number });
1033
+ return true;
1034
+ };
1035
+ const EDITED = 'the comment was edited after it was posted, so its request is not believed';
1036
+ const NOT_MAINTAINER = (by) => `${by ?? 'the author'} is not a maintainer now, and only a maintainer's request starts a run`;
1037
+
1038
+ const found = runBlocksOf(comments, { trust: (login, block) => block.type === 'request' && standing.get(lower(login)) === true, profiles });
1039
+ // Which comments hold a request block for each run id, in the order they were written (comments come oldest first)
1040
+ /** @type {Map<string, string[]>} */
1041
+ const holders = new Map();
1042
+ for (const b of [...found.blocks, ...found.ignored]) if (b.type === 'request') holders.set(b.runId, [...(holders.get(b.runId) ?? []), b.comment.id]);
1043
+ /**
1044
+ * 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
1045
+ * block with that id, and this is the first other comment that does. A later one is a copy
1046
+ */
1047
+ const isReply = (runId, commentId) => {
1048
+ const row = rowOf(runId);
1049
+ if (!row || row.via !== 'hand' || row.comment_id === commentId) return false;
1050
+ const list = (holders.get(runId) ?? []).filter((id) => id !== row.comment_id);
1051
+ return !(holders.get(runId) ?? []).includes(row.comment_id) && list[0] === commentId;
1052
+ };
1053
+ /** Posts the reply that names the id cornfield assigned, as the poll's signed-in maintainer; false when the forge said no */
1054
+ const reply = async (request) => {
1055
+ const by = await posterLogin();
1056
+ // 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
1057
+ if (!by || !(await isMaintainerLogin(by).catch(() => false))) { waiting = true; return null; }
1058
+ try {
1059
+ const posted = await forge.comment(t.number, formatRunComment(request.runId, request, {
1060
+ profiles,
1061
+ 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` : ''}.`,
1062
+ }));
1063
+ return { comment: posted.id, url: posted.url ?? null, postedBy: by };
1064
+ } catch (err) {
1065
+ 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)}`);
1066
+ waiting = true;
1067
+ return null;
1068
+ }
1069
+ };
1070
+
1071
+ /** 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 */
1072
+ const take = async (comment, request, assigned) => {
1073
+ const row = rowOf(request.runId);
1074
+ if (row) {
1075
+ // cornfield's own request, or one taken before: the run is that comment's
1076
+ if (row.comment_id === comment.id) return null;
1077
+ // cornfield has reserved the id and is about to post it: not yet anyone's copy, so looked at again next time
1078
+ if (row.transport === 'forge' && row.comment_id === '') { waiting = true; return null; }
1079
+ 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` };
1080
+ }
1081
+ 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' };
1082
+ try {
1083
+ reserve(db, request, { target: t.number, who: { userId: '' }, via: null, force: false, hand: { comment } });
1084
+ } catch (err) {
1085
+ if (err instanceof Refused) return { accepted: false, why: err.code ?? 'refused', reason: err.message };
1086
+ throw err;
1087
+ }
1088
+ // 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
1089
+ if (transport !== 'forge') hooks?.emit('agent.requested', { request, actor: request.requestedBy });
1090
+ // 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
1091
+ // if that fails (on pull it may be claimed already): the next look posts it
1092
+ const posted = assigned ? await reply(request) : null;
1093
+ return { accepted: true, kind: request.kind, transport, ...(posted ? { reply: posted } : {}) };
1094
+ };
1095
+
1096
+ /** @type {{ comment: { id: string, url: string | null }, by: string, request: any, assigned: boolean }[]} */
1097
+ const accepted = [];
1098
+ 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 });
1099
+ for (const c of comments) {
1100
+ const by = c.author?.login ?? null;
1101
+ if (!by || typeof c.body !== 'string') continue;
1102
+ const maintainer = standing.get(lower(by)) === true;
1103
+ const edited = c.updatedAt !== undefined && !(Date.parse(c.updatedAt) - Date.parse(c.createdAt) <= EDIT_GRACE_MS);
1104
+ const comment = { id: String(c.id), url: c.url ?? null };
1105
+ for (const r of bareBlocks(c.body, by, c.createdAt, comment.id)) {
1106
+ // 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
1107
+ 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; }
1108
+ 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; }
1109
+ accepted.push({ comment, by, request: r.request, assigned: r.assigned });
1110
+ }
1111
+ }
1112
+ accepted.sort((x, y) => Date.parse(x.request.requestedAt) - Date.parse(y.request.requestedAt) || Number(x.comment.id) - Number(y.comment.id));
1113
+ for (const a of accepted) {
1114
+ const key = keyOf(a.comment.id, a.request.runId, 'request');
1115
+ if (isReply(a.request.runId, a.comment.id)) continue;
1116
+ // An id cornfield assigned whose reply is not in the thread (the forge said no, or cornfield stopped before it was posted): posted now
1117
+ const row = rowOf(a.request.runId);
1118
+ if (a.assigned && row && row.comment_id === a.comment.id && !(holders.get(a.request.runId) ?? []).length) {
1119
+ const posted = await reply(a.request);
1120
+ 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 } });
1121
+ if (!seen(key)) mark(key);
1122
+ continue;
1123
+ }
1124
+ if (seen(key)) continue;
1125
+ const outcome = await take(a.comment, a.request, a.assigned);
1126
+ if (outcome === null) continue;
1127
+ judge(a.comment, key, a.request.runId, a.by, outcome);
1128
+ if (outcome.accepted) out.imported += 1; else out.refused += 1;
1129
+ }
1130
+ for (const b of found.ignored) {
1131
+ if (b.type !== 'request') continue;
1132
+ // cornfield's own request (or its reply), by a maintainer who has since stopped being one, is not a stranger's
1133
+ const own = rowOf(b.runId);
1134
+ if (own && own.comment_id === b.comment.id) continue;
1135
+ if (isReply(b.runId, b.comment.id)) continue;
1136
+ 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;
1137
+ }
1138
+ // 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
1139
+ for (const r of found.refused) {
1140
+ if (r.error.startsWith('The fence names ""')) continue; // a fence with no id: read above
1141
+ if (!r.by || standing.get(lower(r.by)) !== true) continue;
1142
+ if (r.runId && rowOf(r.runId)) continue;
1143
+ 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;
1144
+ }
1145
+ 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 });
1146
+ // Read at this update: not read again until the conversation moves, unless something was left for the next look (which then starts here)
1147
+ if (waiting) held = true;
1148
+ else {
1149
+ db.prepare("DELETE FROM run_seen WHERE run_id = '' AND key LIKE ?").run(`scan:${t.number}@%`);
1150
+ mark(scanKey);
1151
+ advance(t);
1152
+ }
1153
+ }
1154
+ // 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
1155
+ // minute old (nothing more can be written in it then)
1156
+ if (!held && fresh === 0 && cursor !== null && Date.parse(cursor) <= since && Date.parse(cursor) < at - 60_000) cursor = iso(Date.parse(cursor) + 1000);
1157
+ if (cursor !== null) {
1158
+ db.prepare("DELETE FROM run_seen WHERE run_id = '' AND key LIKE 'hand-since:%'").run();
1159
+ mark(`hand-since:${cursor}`);
1160
+ }
1161
+ return out;
1162
+ }
1163
+
723
1164
  /**
724
1165
  * 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
725
1166
  * is the answer to another asked meanwhile. Never throws; resolves with a count.
@@ -867,7 +1308,9 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
867
1308
 
868
1309
  const seen = (runId, key) => db.prepare('SELECT 1 FROM run_seen WHERE run_id = ? AND key = ?').get(runId, key) !== undefined;
869
1310
  const touch = (row, when) => { row.last_activity = maxIso(row.last_activity, iso(Number.isFinite(Date.parse(when)) ? Date.parse(when) : at)); dirty.add(row.run_id); };
870
- const queue = (row, event, key, actor, state) => { events.push({ runId: row.run_id, event, key, actor, state }); };
1311
+ const queue = (row, event, key, actor, state, action) => { events.push({ runId: row.run_id, event, key, actor, state, ...(action ? { action } : {}) }); };
1312
+ /** The runs whose answer columns this look changed (written on their own, so a look that began before an answer was kept cannot undo it) */
1313
+ const answered = new Set();
871
1314
 
872
1315
  // Who counts: runners by the config, maintainers by what the forge says now (asked once per login per look)
873
1316
  const maintainerOf = new Map();
@@ -986,8 +1429,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
986
1429
  const trust = (login, block) => {
987
1430
  const who = standing.get(lower(login));
988
1431
  if (!who) return false;
989
- // A report: a runner (agents.runners) or a maintainer. A stop request: a maintainer. A request is not ours to follow
990
- return block.type === 'report' ? who.runner || who.maintainer : block.type === 'stop-request' ? who.maintainer : false;
1432
+ // A report: a runner (agents.runners) or a maintainer. A stop request and an answer: a maintainer. A request is not ours to follow
1433
+ return block.type === 'report' ? who.runner || who.maintainer : block.type === 'stop-request' || block.type === 'answer' ? who.maintainer : false;
991
1434
  };
992
1435
  const found = runBlocksOf(comments, { trust });
993
1436
  const counts = new Map();
@@ -1015,7 +1458,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1015
1458
  if (!row || !ids.has(b.runId) || b.type === 'request') continue;
1016
1459
  const key = keyOf(b.comment.id, b.runId, b.type);
1017
1460
  const reason = b.why === 'edited' ? 'edited after it was posted, so it is not believed'
1018
- : b.type === 'report' ? 'not from a runner (agents.runners) or a maintainer' : 'a stop request is believed only from a maintainer';
1461
+ : b.type === 'report' ? 'not from a runner (agents.runners) or a maintainer' : `${b.type === 'answer' ? 'an answer' : 'a stop request'} is believed only from a maintainer`;
1019
1462
  if (judge(row, b.comment.id, key, b.by, b.type, { ...(b.value.state ? { state: b.value.state } : {}) }, { accepted: false, reason })) out.ignored += 1;
1020
1463
  }
1021
1464
  // A block that is not strictly the contract's (a credential in a report, a stray key) is turned away, and written down once
@@ -1034,12 +1477,29 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1034
1477
  state: r.state, reported_at: when, reported_by: login, note: r.note ?? null, url: r.url ?? null,
1035
1478
  tokens: r.tokens ?? row.tokens, cost: r.cost ?? row.cost,
1036
1479
  });
1480
+ // A new wait is a new question: the answer to the last one is not its answer
1481
+ if (r.state === 'waiting' && previous !== 'waiting') {
1482
+ Object.assign(row, { answer_action: null, answer_text: null, answer_at: null, answer_by: null });
1483
+ answered.add(row.run_id);
1484
+ }
1037
1485
  touch(row, when);
1038
1486
  out.reports += 1;
1039
1487
  cause.set(row.run_id, key);
1040
1488
  happen(row, { key: `report:${key}`, at: when, kind: r.state === 'claimed' ? 'claimed' : 'report', actor: login, ref: r.state, note: r.note ?? null, url: r.url ?? null });
1041
1489
  if (r.state === 'claimed') queue(row, 'run.claimed', 'ev:claimed', login, 'claimed');
1042
1490
  if (r.state !== previous) queue(row, 'run.state', `ev:state:${id}:${key}`, login, r.state);
1491
+ if (r.state === 'waiting' && previous !== 'waiting') queue(row, 'run.waiting', `ev:waiting:${id}:${key}`, login, 'waiting');
1492
+ } else if (block.type === 'answer') {
1493
+ // An answer to a run that is not waiting answers nothing (the runner went on, or it asked nothing), nor does one after a stop request: it is kept in the audit only
1494
+ if (row.state !== 'waiting' || (row.stop_requested_at && block.value.action !== 'stop')) continue;
1495
+ const a = block.value;
1496
+ Object.assign(row, { answer_action: a.action, answer_text: a.text ?? null, answer_at: when, answer_by: login });
1497
+ answered.add(row.run_id);
1498
+ if (a.action === 'stop' && !row.stop_requested_at) Object.assign(row, { stop_requested_at: when, stop_requested_by: login });
1499
+ touch(row, when);
1500
+ happen(row, { key: `answer:${id}`, at: when, kind: 'answered', actor: login, ref: a.action, note: a.text ?? null });
1501
+ queue(row, 'run.answered', `ev:answered:${id}:${key}`, login, 'waiting', a.action);
1502
+ if (a.action === 'stop') queue(row, 'run.stopRequested', `ev:stop:${id}:${key}`, login, 'stop-requested');
1043
1503
  } else {
1044
1504
  if (!row.stop_requested_at) Object.assign(row, { stop_requested_at: when, stop_requested_by: login });
1045
1505
  touch(row, when);
@@ -1106,6 +1566,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1106
1566
  last_activity = MAX(last_activity, ?) WHERE run_id = ?`)
1107
1567
  .run(r.state, r.reported_at, r.reported_by, r.note, r.url, r.tokens, r.cost, r.stop_requested_at, r.stop_requested_by,
1108
1568
  r.pull, r.pull_state, r.pull_url, r.pull_by, r.pull_trusted, r.linked_via, r.branch, r.head_sha, r.checks, r.last_activity, id);
1569
+ if (answered.has(id)) db.prepare('UPDATE runs SET answer_action = ?, answer_text = ?, answer_at = ?, answer_by = ? WHERE run_id = ?').run(r.answer_action, r.answer_text, r.answer_at, r.answer_by, id);
1109
1570
  }
1110
1571
  for (const e of events) if (mark.run(e.runId, e.key, iso(at)).changes === 1) fresh.push(e);
1111
1572
  for (const ev of happened) keepEvent(db, ev.runId, ev);
@@ -1119,7 +1580,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1119
1580
  }
1120
1581
  for (const e of fresh) {
1121
1582
  const row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(e.runId));
1122
- hooks?.emit(e.event, { ...runPayload(row, e.actor), state: e.state });
1583
+ hooks?.emit(e.event, { ...runPayload(row, e.actor), state: e.state, ...(e.action ? { action: e.action } : {}) });
1123
1584
  }
1124
1585
  return out;
1125
1586
  }
@@ -1134,10 +1595,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1134
1595
  /** What a runner's act writes into the timeline: the runner, with the maintainer who minted the token kept in `mintedBy` */
1135
1596
  const runnerText = (token) => byToText(runnerBy(token));
1136
1597
 
1137
- /** A run for a runner: the state it is in as cornfield derives it, and whether a maintainer asked it to stop. Nothing else about the run, no credential */
1598
+ /** A run for a runner: the state it is in as cornfield derives it, whether a maintainer asked it to stop, and the answer to its wait if there is one. Nothing else about the run, no credential */
1138
1599
  function runnerView(row) {
1139
1600
  const st = statusOf(row, now(), quietMs);
1140
- return { runId: row.run_id, state: st.status, reported: row.state === 'requested' ? null : row.state, stopRequested: row.stop_requested_at != null, ...(row.stop_requested_at ? { stopRequestedAt: row.stop_requested_at } : {}), open: st.open, finished: st.finished };
1601
+ return { runId: row.run_id, state: st.status, reported: row.state === 'requested' ? null : row.state, stopRequested: row.stop_requested_at != null, ...(row.stop_requested_at ? { stopRequestedAt: row.stop_requested_at } : {}), ...(row.answer_at ? { answer: answerOf(row) } : {}), open: st.open, finished: st.finished };
1141
1602
  }
1142
1603
 
1143
1604
  /** The run a runner token names, or a `Refused`: 404 when there is none, 403 when the token may not touch it */
@@ -1197,7 +1658,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1197
1658
  return { request: checked.ok ? checked.value : null, run: runnerView(row), row };
1198
1659
  }
1199
1660
 
1200
- /** One run as the runner that holds it sees it: `GET /api/runs/<runId>`, how a runner learns it was asked to stop */
1661
+ /** One run as the runner that holds it sees it: `GET /api/runs/<runId>`, how a runner learns it was asked to stop, or answered */
1201
1662
  async function runnerGet(token, runId) {
1202
1663
  const db = await auth.store();
1203
1664
  return runnerView(runnerRun(db, token, runId));
@@ -1220,10 +1681,14 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1220
1681
  const was = statusOf(row, at, quietMs);
1221
1682
  if (was.finished) throw new Refused(409, `Run ${row.run_id} is ${was.status}; it takes no more reports.`, 'conflict');
1222
1683
  const stamp = iso(at);
1684
+ // A new wait is a new question: the answer to the last one goes (a repeat of `waiting` while waiting keeps it)
1685
+ const newWait = r.state === 'waiting' && row.state !== 'waiting';
1223
1686
  const changed = db.prepare(`UPDATE runs SET state = ?, reported_at = ?, reported_by = ?, note = ?, url = ?, tokens = COALESCE(?, tokens), cost = COALESCE(?, cost),
1224
- claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?)
1687
+ claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?),
1688
+ answer_action = CASE WHEN ? THEN NULL ELSE answer_action END, answer_text = CASE WHEN ? THEN NULL ELSE answer_text END,
1689
+ answer_at = CASE WHEN ? THEN NULL ELSE answer_at END, answer_by = CASE WHEN ? THEN NULL ELSE answer_by END
1225
1690
  WHERE run_id = ? AND (claimed_by IS NULL OR claimed_by = ?) AND state NOT IN ('done', 'failed', 'stopped')`)
1226
- .run(r.state, stamp, runnerText(token), r.note ?? null, r.url ?? null, r.tokens ?? null, r.cost ?? null, token.id, stamp, stamp, row.run_id, token.id).changes;
1691
+ .run(r.state, stamp, runnerText(token), r.note ?? null, r.url ?? null, r.tokens ?? null, r.cost ?? null, token.id, stamp, stamp, +newWait, +newWait, +newWait, +newWait, row.run_id, token.id).changes;
1227
1692
  if (changed !== 1) throw new Refused(409, `Run ${row.run_id} changed while the report was being taken; read it again (GET /api/runs/${row.run_id}).`, 'conflict');
1228
1693
  const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
1229
1694
  // A report of `claimed` on a run the claim route already claimed is a report, not a second "Claimed" line
@@ -1231,6 +1696,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1231
1696
  const actor = runnerActor(token);
1232
1697
  if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
1233
1698
  if (r.state !== row.state) hooks?.emit('run.state', { ...runPayload(after, actor), state: r.state });
1699
+ if (newWait) hooks?.emit('run.waiting', { ...runPayload(after, actor), state: r.state });
1234
1700
  if (REPORT_FINISHED.includes(r.state)) hooks?.emit('run.finished', { ...runPayload(after, actor), state: r.state });
1235
1701
  return { run: runnerView(after), row: after, was: row };
1236
1702
  }
@@ -1257,7 +1723,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1257
1723
  return hit ? hit.run_id : null;
1258
1724
  }
1259
1725
 
1260
- return { request, stop, list, get, follow, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1726
+ return { request, stop, answer, list, get, follow, discover, discovers, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1261
1727
  }
1262
1728
 
1263
1729
  /** @typedef {ReturnType<typeof createRuns>} Runs */