@popcorn245/cornfield 0.15.0 → 0.16.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.
@@ -8,8 +8,9 @@
8
8
  * - **A run id,** `run-` and a 26 character ULID (Crockford base32): `newRunId`, `isRunId`.
9
9
  * - **The request,** JSON v1, checked strictly (`validateRequest`, `createRequest`). It carries no credential, ever: a field
10
10
  * named like a token, a secret or a password is refused, and so is a value shaped like one.
11
- * - **The report** a runner may send (`validateReport`: claimed, working, done, failed, stopped) and **the stop request**
12
- * cornfield sends (`validateStopRequest`: `stop-requested`).
11
+ * - **The report** a runner may send (`validateReport`: claimed, working, waiting, done, failed, stopped), **the stop request**
12
+ * cornfield sends (`validateStopRequest`: `stop-requested`) and **the answer** a maintainer gives a run that reported `waiting`
13
+ * (`validateAnswer`: `answered`, with an `action` of continue, stop or reply).
13
14
  * - **The fenced block,** one form for all three, modelled on the review block of ADR 0005 (server/reviews.js):
14
15
  *
15
16
  * Asked for a code run `run-01JC…` on #12 (maintainer-one, in cornfield).
@@ -20,7 +21,7 @@
20
21
  *
21
22
  * `formatRunComment` writes it (the human line is defused, so it pings and links nobody), `readRunBlocks` and
22
23
  * `parseRunBlocks` read it back: tolerant of the text around a block, strict about what is inside. A block that is not
23
- * strictly a request, a report or a stop request is skipped, and `readRunBlocks` says which and why.
24
+ * strictly a request, a report, a stop request or an answer is skipped, and `readRunBlocks` says which and why.
24
25
  * - **The trailer,** `Cornfield-Run: run-…` on its own line of a pull request body or a commit message, with the run id in a
25
26
  * branch name as the fallback (`parseTrailer`, `runIdFromBranch`, `findRunId`).
26
27
  *
@@ -40,11 +41,13 @@
40
41
  * @typedef {{ minutes?: number, turns?: number, cost?: number }} RunLimits
41
42
  * @typedef {{ version: 1, runId: string, kind: RunKind, profile?: string, refs: RunRefs, branch?: string, brief: string,
42
43
  * limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
43
- * @typedef {'claimed' | 'working' | 'done' | 'failed' | 'stopped'} ReportState
44
+ * @typedef {'claimed' | 'working' | 'waiting' | 'done' | 'failed' | 'stopped'} ReportState
44
45
  * @typedef {{ state: ReportState, note?: string, url?: string, tokens?: number, cost?: number }} RunReport
45
46
  * @typedef {{ state: 'stop-requested', note?: string }} StopRequest
47
+ * @typedef {'continue' | 'stop' | 'reply'} AnswerAction
48
+ * @typedef {{ state: 'answered', action: AnswerAction, text?: string }} RunAnswer
46
49
  * @typedef {{ ok: true, value: any } | { ok: false, error: string }} Checked
47
- * @typedef {{ runId: string, type: 'request', value: RunRequest } | { runId: string, type: 'report', value: RunReport } | { runId: string, type: 'stop-request', value: StopRequest }} RunBlock
50
+ * @typedef {{ runId: string, type: 'request', value: RunRequest } | { runId: string, type: 'report', value: RunReport } | { runId: string, type: 'stop-request', value: StopRequest } | { runId: string, type: 'answer', value: RunAnswer }} RunBlock
48
51
  */
49
52
 
50
53
  import { defuse } from './defuse.js';
@@ -58,11 +61,14 @@ const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
58
61
 
59
62
  export const CONTRACT_VERSION = 1;
60
63
  export const RUN_KINDS = ['code', 'summary', 'brief', 'proposal'];
61
- export const REPORT_STATES = ['claimed', 'working', 'done', 'failed', 'stopped'];
64
+ export const REPORT_STATES = ['claimed', 'working', 'waiting', 'done', 'failed', 'stopped'];
62
65
  export const STOP_STATE = 'stop-requested';
66
+ /** The state of an answer block, and what a maintainer may answer a `waiting` run */
67
+ export const ANSWER_STATE = 'answered';
68
+ export const ANSWER_ACTIONS = ['continue', 'stop', 'reply'];
63
69
  /** The brief, in characters */
64
70
  export const MAX_BRIEF_CHARS = 20000;
65
- /** A report's or a stop request's note, in characters */
71
+ /** A report's or a stop request's note, and an answer's text, in characters */
66
72
  export const MAX_NOTE_CHARS = 4000;
67
73
  export const MAX_URL_CHARS = 2000;
68
74
  export const MAX_NODES = 100;
@@ -91,6 +97,7 @@ const REF_KEYS = ['issue', 'proposal', 'pull', 'thread'];
91
97
  const LIMIT_KEYS = ['minutes', 'turns', 'cost'];
92
98
  const REPORT_KEYS = ['state', 'note', 'url', 'tokens', 'cost'];
93
99
  const STOP_KEYS = ['state', 'note'];
100
+ const ANSWER_KEYS = ['state', 'action', 'text'];
94
101
 
95
102
  // ---------------------------------------------------------------------------
96
103
  // Patterns. Each is plain ECMAScript with no flags, so the JSON Schema can carry the same source.
@@ -391,7 +398,7 @@ export function createRequest(fields, { profiles, now = Date.now, random } = {})
391
398
  }
392
399
 
393
400
  // ---------------------------------------------------------------------------
394
- // The report, and the stop request
401
+ // The report, the stop request and the answer
395
402
  // ---------------------------------------------------------------------------
396
403
 
397
404
  function noteAndUrl(body, no) {
@@ -448,18 +455,43 @@ export function validateStopRequest(body) {
448
455
  return { ok: true, value: { state: STOP_STATE, ...(body.note !== undefined ? { note: body.note } : {}) } };
449
456
  }
450
457
 
458
+ /**
459
+ * Checks an answer: `{ state: 'answered', action, text? }`. A maintainer sends it to a run that reported `waiting`: `continue` (go on),
460
+ * `stop` (the same as a stop request) or `reply` (go on with `text`, which a reply must have). cornfield or a maintainer sends it; the
461
+ * runner decides what it means.
462
+ * @param {unknown} body
463
+ * @returns {Checked}
464
+ */
465
+ export function validateAnswer(body) {
466
+ const no = (error) => ({ ok: false, error });
467
+ if (!isObject(body)) return no('An answer is a JSON object with a state.');
468
+ const keys = keyProblem(body, ANSWER_KEYS, 'An answer');
469
+ if (keys) return no(keys);
470
+ const secret = valueProblem(body, 'The answer');
471
+ if (secret) return no(secret);
472
+ if (body.state !== ANSWER_STATE) return no(`"state" is "${ANSWER_STATE}".`);
473
+ if (!ANSWER_ACTIONS.includes(body.action)) return no(`"action" is one of ${ANSWER_ACTIONS.join(', ')}.`);
474
+ if (body.text !== undefined) {
475
+ const problem = text(body.text, 'text', MAX_NOTE_CHARS);
476
+ if (problem) return no(problem);
477
+ }
478
+ if (body.action === 'reply' && (body.text === undefined || body.text.trim() === '')) return no('A reply has "text": what the maintainer says.');
479
+ return { ok: true, value: { state: ANSWER_STATE, action: body.action, ...(body.text !== undefined && body.text.trim() !== '' ? { text: body.text } : {}) } };
480
+ }
481
+
451
482
  /**
452
483
  * Checks whatever a `cornfield-run` block holds, by its shape: a `version` makes it a request, the state `stop-requested` a
453
- * stop request, any other state a report.
484
+ * stop request, the state `answered` an answer, any other state a report.
454
485
  * @param {unknown} body
455
486
  * @param {{ profiles?: string[] }} [opts]
456
- * @returns {{ ok: true, type: 'request' | 'report' | 'stop-request', value: any } | { ok: false, error: string }}
487
+ * @returns {{ ok: true, type: 'request' | 'report' | 'stop-request' | 'answer', value: any } | { ok: false, error: string }}
457
488
  */
458
489
  export function validateRunBody(body, opts) {
459
490
  if (Array.isArray(body)) return { ok: false, error: 'A cornfield-run block holds one JSON object, not a list.' };
460
491
  if (!isObject(body)) return { ok: false, error: 'A cornfield-run block holds one JSON object.' };
461
492
  const [type, checked] = 'version' in body || 'runId' in body ? ['request', validateRequest(body, opts)]
462
493
  : body.state === STOP_STATE ? ['stop-request', validateStopRequest(body)]
494
+ : body.state === ANSWER_STATE ? ['answer', validateAnswer(body)]
463
495
  : 'state' in body ? ['report', validateReport(body)]
464
496
  : ['request', validateRequest(body, opts)]; // neither shape: the request check names the first key or field that is wrong
465
497
  return checked.ok ? { ok: true, type, value: checked.value } : checked;
@@ -471,7 +503,7 @@ export function validateRunBody(body, opts) {
471
503
 
472
504
  const FENCE = '```';
473
505
 
474
- /** The block for a checked request, report or stop request, as text: the fence named for the run, the JSON, the closing fence. Throws on anything that is not strictly one. */
506
+ /** The block for a checked request, report, stop request or answer, as text: the fence named for the run, the JSON, the closing fence. Throws on anything that is not strictly one. */
475
507
  export function formatRunBlock(runId, body, opts) {
476
508
  if (!isRunId(runId)) throw new TypeError(`${shown(runId)} is not a run id.`);
477
509
  const checked = validateRunBody(body, opts);
@@ -492,14 +524,15 @@ function defaultLine(runId, type, value) {
492
524
  return `Asked for a ${value.kind} run \`${runId}\` on ${about}${value.profile ? ` with the profile ${value.profile}` : ''} (${value.requestedBy}, in cornfield).`;
493
525
  }
494
526
  if (type === 'stop-request') return `Asked run \`${runId}\` to stop.`;
527
+ if (type === 'answer') return `Answered run \`${runId}\`: ${value.action}.`;
495
528
  return `Run \`${runId}\`: ${value.state}.`;
496
529
  }
497
530
 
498
531
  /**
499
- * The text of a comment for a request, a report or a stop request: a human line (defused: it pings and links nobody), the note of a
500
- * report or stop request quoted and defused, then the block. The block keeps every value as sent, for the runner.
532
+ * The text of a comment for a request, a report, a stop request or an answer: a human line (defused: it pings and links nobody), the note of a
533
+ * report or stop request quoted and defused (an answer's text is in the block only), then the block. The block keeps every value as sent, for the runner.
501
534
  * @param {string} runId
502
- * @param {RunRequest | RunReport | StopRequest} body
535
+ * @param {RunRequest | RunReport | StopRequest | RunAnswer} body
503
536
  * @param {{ line?: string, profiles?: string[] }} [opts] `line`: your own human line, in place of the default
504
537
  * @returns {string}
505
538
  */
@@ -507,7 +540,8 @@ export function formatRunComment(runId, body, { line, profiles } = {}) {
507
540
  const block = formatRunBlock(runId, body, { profiles });
508
541
  const checked = validateRunBody(body, { profiles });
509
542
  const head = oneLine(line ?? defaultLine(runId, checked.type, checked.value));
510
- const note = checked.type === 'request' ? '' : (checked.value.note ?? '').trim();
543
+ // An answer's text is the maintainer's words to the runner: it travels in the block only, never quoted beside it
544
+ const note = checked.type === 'request' || checked.type === 'answer' ? '' : (checked.value.note ?? '').trim();
511
545
  const quoted = note ? `\n\n${defuse(note).split(/\r?\n/).map((l) => (l ? `> ${l}` : '>')).join('\n')}` : '';
512
546
  const out = `${head}${quoted}\n\n${block}`;
513
547
  if (out.length > MAX_COMMENT_CHARS) throw new RangeError(`That is too long for a comment (${out.length} characters, at most ${MAX_COMMENT_CHARS}); shorten the brief or the note.`);
@@ -545,7 +579,7 @@ export function* fencedBlocks(text) {
545
579
 
546
580
  /**
547
581
  * Every block a comment's text holds, in order, and every block that was refused with the reason. A block that is not strictly a
548
- * request, a report or a stop request is refused: not JSON, a list, two objects, a key it does not have, a credential, a fence
582
+ * request, a report, a stop request or an answer is refused: not JSON, a list, two objects, a key it does not have, a credential, a fence
549
583
  * that names no run id, a request for another run than its fence names. Text around a block, a quoted block (`> ```…`), an
550
584
  * indented one, one nobody closed, and one inside another fence (a ```` example) are ignored (`fencedBlocks`). Nothing is thrown,
551
585
  * and the time it takes is linear in the text.
@@ -626,8 +660,8 @@ export function runAuthors(comments) {
626
660
  * - `blocks`: from an author `trust(login)` accepts, in a comment not edited after it was posted;
627
661
  * - `ignored`: well formed, but from someone else (or a deleted account), or in an edited comment: the spec wants one audit row
628
662
  * for each, so they are kept with the reason;
629
- * - `refused`: not strictly a request, report or stop request (`readRunBlocks`), with the author.
630
- * Whom to trust is the caller's to decide, because it takes the forge: a maintainer now for a request or a stop, a login in
663
+ * - `refused`: not strictly a request, report, stop request or answer (`readRunBlocks`), with the author.
664
+ * Whom to trust is the caller's to decide, because it takes the forge: a maintainer now for a request, a stop or an answer, a login in
631
665
  * `agents.runners` or a maintainer for a report (spec 0005). `trust` is asked once per block, with the block, so it can tell them
632
666
  * apart.
633
667
  * @param {RunComment[]} comments
@@ -665,7 +699,7 @@ export function parseRunBlocks(body, opts) {
665
699
  * drops the ones whose author is not a maintainer, or whose comment was edited), or null. Later wins.
666
700
  * @param {RunBlock[]} blocks
667
701
  * @param {string} runId
668
- * @param {'request' | 'report' | 'stop-request'} type
702
+ * @param {'request' | 'report' | 'stop-request' | 'answer'} type
669
703
  * @returns {RunBlock | null}
670
704
  */
671
705
  export function latestBlock(blocks, runId, type) {
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://github.com/popcorn245/CornField/blob/main/core/agent-contract.schema.json",
4
4
  "title": "cornfield agent contract, version 1",
5
- "description": "The JSON a cornfield-run fenced block holds: a request, a report or a stop request. docs/agent-contract.md says what each means. Checks the shape; a few rules are the validator's alone (the configured profile list, that a date is a real one), and are listed in the docs.",
5
+ "description": "The JSON a cornfield-run fenced block holds: a request, a report, a stop request or an answer. docs/agent-contract.md says what each means. Checks the shape; a few rules are the validator's alone (the configured profile list, that a date is a real one, that a reply has text), and are listed in the docs.",
6
6
  "oneOf": [
7
7
  {
8
8
  "$ref": "#/$defs/request"
@@ -12,6 +12,9 @@
12
12
  },
13
13
  {
14
14
  "$ref": "#/$defs/stopRequest"
15
+ },
16
+ {
17
+ "$ref": "#/$defs/answer"
15
18
  }
16
19
  ],
17
20
  "$defs": {
@@ -227,6 +230,7 @@
227
230
  "enum": [
228
231
  "claimed",
229
232
  "working",
233
+ "waiting",
230
234
  "done",
231
235
  "failed",
232
236
  "stopped"
@@ -285,6 +289,34 @@
285
289
  }
286
290
  }
287
291
  }
292
+ },
293
+ "answer": {
294
+ "description": "A maintainer answering a run that reported waiting: continue, stop (the same as a stop request) or reply with text. The runner decides what it means.",
295
+ "type": "object",
296
+ "additionalProperties": false,
297
+ "required": [
298
+ "state",
299
+ "action"
300
+ ],
301
+ "properties": {
302
+ "state": {
303
+ "const": "answered"
304
+ },
305
+ "action": {
306
+ "enum": [
307
+ "continue",
308
+ "stop",
309
+ "reply"
310
+ ]
311
+ },
312
+ "text": {
313
+ "type": "string",
314
+ "maxLength": 4000,
315
+ "not": {
316
+ "pattern": "(?<![A-Za-z0-9])gh[pousr]_[A-Za-z0-9]{30,}|(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{20,}|(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{15,}|(?<![A-Za-z0-9])gto-[A-Za-z0-9]{20,}|(?<![A-Za-z0-9])cf_(?:rt|at|nt)_[A-Za-z0-9_-]{20,}|(?<![A-Za-z0-9])sk-(?=[A-Za-z0-9_-]{20})[A-Za-z_-]{0,40}[0-9]|(?<![A-Za-z0-9])AKIA[0-9A-Z]{16}|(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}|(?<![A-Za-z0-9])xox[abprs]-[A-Za-z0-9-]{10,}|(?<![A-Za-z0-9])eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{5,}|-----BEGIN [A-Z ]{0,40}PRIVATE KEY-----|(?<![A-Za-z0-9])[bB][eE][aA][rR][eE][rR][ \\t]+(?=[A-Za-z0-9._~+/=-]{20})[A-Za-z._~+/=-]{0,40}[0-9]|(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]{0,31}://[^\\s/@:]+:[^\\s/@]+@"
317
+ }
318
+ }
319
+ }
288
320
  }
289
321
  }
290
322
  }
package/core/config.js CHANGED
@@ -70,7 +70,7 @@ export const FORGE_TYPES = ['github', 'forgejo'];
70
70
  /** How a pull request cornfield lands is merged (`forge.mergeMethod`): the way the repo lands its pull requests */
71
71
  export const MERGE_METHODS = ['merge', 'squash', 'rebase'];
72
72
  /** The events a hook may ask for (`hooks[].events`), and what each one means: docs/config.md#hooks */
73
- export const HOOK_EVENTS = Object.freeze(['spec.ready', 'spec.approved', 'spec.sentBack', 'build.opened', 'pr.landed', 'session.expiring', 'thread.opened', 'thread.message', 'thread.linked', 'agent.requested', 'run.claimed', 'run.state', 'run.stopRequested', 'run.finished', 'trigger.skipped', 'runner.offline']);
73
+ export const HOOK_EVENTS = Object.freeze(['spec.ready', 'spec.approved', 'spec.sentBack', 'build.opened', 'pr.landed', 'session.expiring', 'thread.opened', 'thread.message', 'thread.linked', 'agent.requested', 'run.claimed', 'run.state', 'run.waiting', 'run.answered', 'run.stopRequested', 'run.finished', 'trigger.skipped', 'runner.offline']);
74
74
  /** The events that come from looking at threads (server/threads.js): a poll that wants any of them looks at threads too */
75
75
  export const THREAD_EVENTS = Object.freeze(['thread.opened', 'thread.message', 'thread.linked']);
76
76
  /** The keys of `threads` when it is an object, and the label's longest length */
@@ -69,7 +69,7 @@ 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, 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, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
73
73
  } from './runs-model.js';
74
74
  import { runsHtml } from './runs-view.js';
75
75
  import { setRunsOnMap, clearRunsOnMap } from './runs-map.js';
@@ -121,6 +121,7 @@ const ui = {
121
121
  runSel: null, // the run lit on the map (Light on the map), by id
122
122
  runnerSaid: null, // the runner state last shown ('online', 'offline', 'none'; null off the pull transport), so a change is said once
123
123
  runTimelines: new Set(), // the runs whose timeline is open
124
+ runReplies: new Map(), // the reply typed so far for each waiting run, so a repaint (the runs are looked at again) keeps it
124
125
  agent: null, // { opener, refs, posting } while the Start an agent dialog is open
125
126
  };
126
127
 
@@ -1043,6 +1044,8 @@ function findAgain(el) {
1043
1044
  if (el.dataset.forgeRerun) return `[data-forge-rerun="${el.dataset.forgeRerun}"]`;
1044
1045
  if (el.dataset.forgeAgent) return `[data-forge-agent="${el.dataset.forgeAgent}"]`;
1045
1046
  if (el.dataset.forgeStop) return `[data-forge-stop="${el.dataset.forgeStop}"]`;
1047
+ if (el.dataset.runReply) return `[data-run-reply="${el.dataset.runReply}"]`;
1048
+ if (el.dataset.runAnswer) return `[data-run-answer="${el.dataset.runAnswer}"][data-run-id="${el.dataset.runId}"]`;
1046
1049
  if (el.dataset.runSelect) return `[data-run-select="${el.dataset.runSelect}"]`;
1047
1050
  if (el.dataset.runTimeline) return `[data-run-timeline="${el.dataset.runTimeline}"]`;
1048
1051
  return null;
@@ -1150,7 +1153,7 @@ function viewContext() {
1150
1153
  const base = f && safeUrl(f.url) ? f.url.replace(/\/+$/, '') : null;
1151
1154
  return {
1152
1155
  esc: escHtml, safeUrl, forgeName: forgeName(), forgeType: f ? f.type : 'github', repoUrl: base && f.repo ? `${base}/${f.repo}` : null,
1153
- now: now(), nodes: state.nodes, selected: ui.runSel, timelines: ui.runTimelines, busy: !!ui.busy,
1156
+ now: now(), nodes: state.nodes, selected: ui.runSel, timelines: ui.runTimelines, replies: ui.runReplies, busy: !!ui.busy,
1154
1157
  };
1155
1158
  }
1156
1159
 
@@ -1547,6 +1550,35 @@ async function stopRun(runId) {
1547
1550
  paint();
1548
1551
  }
1549
1552
 
1553
+ /** Answers a waiting run: Continue, Stop, or a reply with the text typed. One POST, then the runs are read again */
1554
+ async function answerRun(runId, action) {
1555
+ if (ui.busy) return;
1556
+ const text = ui.runReplies.get(runId) || '';
1557
+ if (action === 'reply' && text.trim() === '') {
1558
+ ui.runNote = { text: 'Write a reply first.', ok: false };
1559
+ announce(ui.runNote.text);
1560
+ paint();
1561
+ return;
1562
+ }
1563
+ // Where the focus goes back to once it is sent: the reply field after a reply (empty, for the next one), the button after Continue; while the
1564
+ // buttons are disabled the focus has nowhere to stay, so it is put back by hand. A run that no longer asks (a Stop) gets its Timeline button
1565
+ const back = action === 'reply' ? `[data-run-reply="${runId}"]` : `[data-run-answer="${action}"][data-run-id="${runId}"]`;
1566
+ ui.busy = 'answer';
1567
+ ui.runNote = null;
1568
+ announce(`Answering ${runId}`);
1569
+ paint();
1570
+ const res = await post(answerUrl(runId), answerBody(action, text));
1571
+ ui.busy = '';
1572
+ if (res.ok && action === 'reply') ui.runReplies.delete(runId);
1573
+ ui.runNote = { text: answerWordsFor(res.status, res.body, runId, action), ok: res.ok };
1574
+ announce(ui.runNote.text);
1575
+ await loadRuns(false, { say: false });
1576
+ paint();
1577
+ const panel = $('forge-panel');
1578
+ const to = panel && [back, `[data-run-timeline="${runId}"]`].map((sel) => panel.querySelector(sel)).find((el) => el && !el.disabled);
1579
+ if (to && to !== document.activeElement) to.focus();
1580
+ }
1581
+
1550
1582
  // ---------------------------------------------------------------------------
1551
1583
  // Opening and closing
1552
1584
  // ---------------------------------------------------------------------------
@@ -1678,6 +1710,8 @@ function onClick(e) {
1678
1710
  if (agent) { openAgent(agent.dataset.forgeAgent, `[data-forge-agent="${agent.dataset.forgeAgent}"]`); return; }
1679
1711
  const stop = t.closest('[data-forge-stop]');
1680
1712
  if (stop) { stopRun(stop.dataset.forgeStop); return; }
1713
+ const answer = t.closest('[data-run-answer]');
1714
+ if (answer) { answerRun(answer.dataset.runId, answer.dataset.runAnswer); return; }
1681
1715
  const pick = t.closest('[data-run-select]');
1682
1716
  if (pick) { selectRun(pick.dataset.runSelect); return; }
1683
1717
  const timeline = t.closest('[data-run-timeline]');
@@ -1742,6 +1776,7 @@ function onChange(e) {
1742
1776
  }
1743
1777
 
1744
1778
  function onInput(e) {
1779
+ if (e.target.dataset && e.target.dataset.runReply) { ui.runReplies.set(e.target.dataset.runReply, e.target.value); return; }
1745
1780
  if (e.target.id !== 'forge-text') return;
1746
1781
  ui.filters.text = e.target.value;
1747
1782
  filtersChanged(false);
@@ -1751,6 +1786,7 @@ function onInput(e) {
1751
1786
 
1752
1787
  /** Escape anywhere in the panel closes it, and the button has the focus again (a field's own Escape comes first) */
1753
1788
  function onKey(e) {
1789
+ if (e.key === 'Enter' && e.target.dataset && e.target.dataset.runReply && !e.defaultPrevented) { e.preventDefault(); answerRun(e.target.dataset.runReply, 'reply'); return; }
1754
1790
  if (e.key === 'Enter' && e.target.id === 'notes-tag' && !e.defaultPrevented) { e.preventDefault(); postDraft(); return; }
1755
1791
  if (e.key === 'Escape' && !e.defaultPrevented && ui.notes.confirm && e.target.closest && e.target.closest('#notes-confirm')) {
1756
1792
  e.preventDefault();
@@ -1848,5 +1884,5 @@ export function resetForgePanelForTests(clock = () => Date.now()) {
1848
1884
  runsTimer = 0;
1849
1885
  pageAway = false;
1850
1886
  clearRunsOnMap();
1851
- Object.assign(ui, { runSel: null, runTimelines: new Set(), thread: null, threadDetail: null, threadError: '', litThread: null, idea: freshIdea(), config: null, open: false, kind: 'pulls', filters: defaultFilters(), lists: {}, work: null, workFilters: { agentsOnly: false, finished: false }, loading: false, error: '', selected: null, detail: null, landing: null, detailError: '', lit: null, deploy: null, deployItem: null, litDeploy: null, nodesSeen: null, busy: '', note: null, confirm: null, actNote: null, notes: freshNotes(), runs: null, runnerSaid: null, runNote: null, agent: null });
1887
+ Object.assign(ui, { runSel: null, runTimelines: new Set(), runReplies: new Map(), thread: null, threadDetail: null, threadError: '', litThread: null, idea: freshIdea(), config: null, open: false, kind: 'pulls', filters: defaultFilters(), lists: {}, work: null, workFilters: { agentsOnly: false, finished: false }, loading: false, error: '', selected: null, detail: null, landing: null, detailError: '', lit: null, deploy: null, deployItem: null, litDeploy: null, nodesSeen: null, busy: '', note: null, confirm: null, actNote: null, notes: freshNotes(), runs: null, runnerSaid: null, runNote: null, agent: null });
1852
1888
  }
@@ -11,6 +11,7 @@ import { relativeTime } from './review-model.js';
11
11
  export const RUNS_URL = '/api/agent-runs';
12
12
  export const runsUrl = (follow) => (follow ? `${RUNS_URL}?follow=1` : RUNS_URL);
13
13
  export const stopUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/stop`;
14
+ export const answerUrl = (runId) => `${RUNS_URL}/${encodeURIComponent(runId)}/answer`;
14
15
 
15
16
  /** The kinds of run (the contract's), and what each asks the runner for */
16
17
  export const KINDS = Object.freeze([
@@ -32,7 +33,7 @@ export function aboutWords(refs) {
32
33
  /** The state of a run, said short */
33
34
  export function statusWords(run) {
34
35
  const words = {
35
- requested: 'Requested', claimed: 'Claimed', working: 'Working', done: 'Done', failed: 'Failed', stopped: 'Stopped',
36
+ requested: 'Requested', claimed: 'Claimed', working: 'Working', waiting: 'Waiting', done: 'Done', failed: 'Failed', stopped: 'Stopped',
36
37
  'stop-requested': 'Stop requested', quiet: 'Quiet', merged: 'Merged', closed: 'Closed',
37
38
  };
38
39
  return words[run.status] || run.status;
@@ -44,6 +45,9 @@ export function statusWhy(run) {
44
45
  case 'quiet': return 'Nothing reported or pushed for a while, so it no longer counts toward the limit. A report or a push brings it back.';
45
46
  case 'stop-requested': return `${run.stopRequested && run.stopRequested.by ? run.stopRequested.by : 'A maintainer'} asked it to stop. The runner decides what that means; this stays until it says stopped, or the run goes quiet.`;
46
47
  case 'requested': return 'Waiting for a runner to pick it up. cornfield only asks; it starts nothing.';
48
+ case 'waiting': return run.answer
49
+ ? `${run.answer.by || 'A maintainer'} answered: ${answerWords(run.answer)}. The runner picks the answer up and goes on; answer again to change it until it does.`
50
+ : 'The runner stopped to ask and goes on once a maintainer answers: Continue, Stop, or a reply.';
47
51
  default: return '';
48
52
  }
49
53
  }
@@ -85,6 +89,28 @@ export function triggerNotice(data) {
85
89
  /** Whether a Stop is offered: the run is open and nobody has asked it to stop yet */
86
90
  export const canStop = (run) => run.open === true && !run.stopRequested;
87
91
 
92
+ /** Whether the run asks for an answer (Continue, Stop, Reply): the runner reported `waiting` and nobody has asked it to stop */
93
+ export const canAnswer = (run) => run.open === true && run.status === 'waiting' && !run.stopRequested;
94
+
95
+ /** An answer, said short: "continue", "stop", "reply: use the second plan" */
96
+ export function answerWords(answer) {
97
+ if (!answer) return '';
98
+ return answer.action === 'reply' ? `reply: ${answer.text || ''}`.trim() : answer.action;
99
+ }
100
+
101
+ /** The body of an answer: the action, and a reply's text (trimmed); Continue and Stop carry none */
102
+ export function answerBody(action, text) {
103
+ return action === 'reply' ? { action, text: (text || '').trim() } : { action };
104
+ }
105
+
106
+ /** What an answer came to */
107
+ export function answerWordsFor(status, body, runId, action) {
108
+ if (status === null) return 'cornfield did not answer; nothing was sent.';
109
+ if (status === 401) return 'Your sign-in has ended. Sign in again to answer a run.';
110
+ if (body && body.ok) return action === 'stop' ? `Asked ${runId} to stop. The runner decides what that means.` : `Answered ${runId}: ${action}. The runner picks it up and goes on.`;
111
+ return (body && body.error) || `The answer was refused (${status}).`;
112
+ }
113
+
88
114
  /** The summary line over the list: "2 open of 3 allowed, 5 runs" */
89
115
  export function runsStatus(data) {
90
116
  const n = data.runs.length;
@@ -234,6 +260,7 @@ export function timelineWords(entry) {
234
260
  case 'pull-opened': return { what: `Opened pull request ${entry.ref || ''}${by}`.trim(), note: '' };
235
261
  case 'checks': return { what: { success: 'Checks passed', failure: 'Checks failed', running: 'Checks running', none: 'No checks' }[entry.ref] || 'Checks changed', note: '' };
236
262
  case 'stop-requested': return { what: `Asked to stop${by}`, note: entry.note || '' };
263
+ case 'answered': return { what: `Answered ${entry.ref || ''}${by}`.replace(/\s+/g, ' ').trim(), note: entry.note || '' };
237
264
  case 'merged': return { what: `Landed: pull request ${entry.ref || ''} merged`, note: '' };
238
265
  case 'closed': return { what: `Pull request ${entry.ref || ''} closed without landing`, note: '' };
239
266
  case 'quiet': return { what: 'Went quiet: nothing reported or pushed for a while', note: '' };
@@ -9,9 +9,9 @@
9
9
  */
10
10
 
11
11
  import { relativeTime } from './review-model.js';
12
- import { aboutWords, statusWords, statusWhy, runMeta, canStop, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords } from './runs-model.js';
12
+ import { aboutWords, statusWords, statusWhy, runMeta, canStop, canAnswer, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
13
13
 
14
- const TONE = { done: 'success', merged: 'success', failed: 'failure', quiet: 'queued', 'stop-requested': 'queued' };
14
+ const TONE = { done: 'success', merged: 'success', failed: 'failure', quiet: 'queued', 'stop-requested': 'queued', waiting: 'queued' };
15
15
 
16
16
  /**
17
17
  * @typedef {object} ViewContext
@@ -25,6 +25,7 @@ const TONE = { done: 'success', merged: 'success', failed: 'failure', quiet: 'qu
25
25
  * @property {string | null} selected the run lit on the map
26
26
  * @property {Set<string>} timelines the runs whose timeline is open
27
27
  * @property {boolean} busy an action is in flight
28
+ * @property {Map<string, string>} [replies] the reply typed so far for each waiting run, so a repaint keeps it
28
29
  */
29
30
 
30
31
  /** A link that opens a new tab, said so for a screen reader */
@@ -45,7 +46,7 @@ function linksHtml(ctx, run) {
45
46
  thread != null && ctx.repoUrl ? link(ctx, `${ctx.repoUrl}/issues/${thread}`, `Thread #${thread}`) : '',
46
47
  run.branch ? link(ctx, branchUrl(ctx, run.branch), `Branch ${run.branch}`) : '',
47
48
  run.pull ? link(ctx, run.pull.url, `Pull request #${run.pull.number}`, run.pull.trusted ? '' : ' <span class="hx-faint">(not from a runner, so it moves nothing)</span>') : '',
48
- link(ctx, run.report && run.report.url, 'Runner\'s log'),
49
+ link(ctx, run.report && run.report.url, run.status === 'waiting' ? 'Runner\'s link' : 'Runner\'s log'),
49
50
  ].filter(Boolean).join(' · ');
50
51
  }
51
52
 
@@ -57,6 +58,24 @@ function timelineHtml(ctx, run) {
57
58
  return `<ol class="hx-run-timeline" id="run-tl-${ctx.esc(run.runId)}" aria-label="Timeline of ${ctx.esc(run.runId)}, oldest first">${items.join('')}</ol>`;
58
59
  }
59
60
 
61
+ /** What was answered, escaped: the action, a reply's words, who and when */
62
+ function answeredHtml(ctx, run) {
63
+ const a = run.answer;
64
+ return `<p class="hx-forge-meta">Answered: ${ctx.esc(answerWords(a))} · ${ctx.esc(a.by || 'a maintainer')}, ${ctx.esc(relativeTime(a.at, ctx.now) || a.at)}</p>`;
65
+ }
66
+
67
+ /** A waiting run: what was asked (the note and link are shown above) and the three answers, plain buttons and a reply field */
68
+ function answerHtml(ctx, run) {
69
+ const id = ctx.esc(run.runId);
70
+ const off = ctx.busy ? ' disabled' : '';
71
+ const reply = ctx.replies && ctx.replies.get(run.runId) || '';
72
+ return `${run.answer ? answeredHtml(ctx, run) : ''}<div class="hx-run-actions" role="group" aria-label="Answer run ${id}">
73
+ <button type="button" class="hx-btn hx-forge-act" data-run-answer="continue" data-run-id="${id}" aria-label="Continue run ${id}"${off}>Continue</button>
74
+ <button type="button" class="hx-btn hx-forge-act" data-run-answer="stop" data-run-id="${id}" aria-label="Stop run ${id}"${off}>Stop</button></div>
75
+ <label class="hx-forge-field">Reply to run ${id}<input type="text" class="hx-forge-input" data-run-reply="${id}" value="${ctx.esc(reply)}" maxlength="4000" autocomplete="off" /></label>
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
+ }
78
+
60
79
  /** One run */
61
80
  export function runHtml(ctx, run, all) {
62
81
  const lit = ctx.selected === run.runId;
@@ -64,7 +83,8 @@ export function runHtml(ctx, run, all) {
64
83
  const tone = TONE[run.status] || 'running';
65
84
  const why = statusWhy(run);
66
85
  const note = run.report && run.report.note ? `<p class="hx-forge-meta">Runner: ${ctx.esc(run.report.note)}</p>` : '';
67
- const stop = canStop(run) ? `<button type="button" class="hx-btn hx-forge-act" data-forge-stop="${ctx.esc(run.runId)}" aria-label="Stop run ${ctx.esc(run.runId)}"${ctx.busy ? ' disabled' : ''}>Stop</button>` : '';
86
+ const answering = canAnswer(run);
87
+ const stop = canStop(run) && !answering ? `<button type="button" class="hx-btn hx-forge-act" data-forge-stop="${ctx.esc(run.runId)}" aria-label="Stop run ${ctx.esc(run.runId)}"${ctx.busy ? ' disabled' : ''}>Stop</button>` : '';
68
88
  const names = nodeLabels(run.nodes, ctx.nodes);
69
89
  const collision = collisionWords(run, all, ctx.nodes);
70
90
  const limits = limitRows(run);
@@ -78,6 +98,7 @@ export function runHtml(ctx, run, all) {
78
98
  <p class="hx-forge-meta">${ctx.esc(checksWords(run))}</p>
79
99
  <p class="hx-forge-meta">${names.length ? `Changing ${run.nodesFrom === 'files' ? '' : 'or expected to change '}${ctx.esc(names.join(', '))}` : 'No node on the map yet.'}</p>
80
100
  ${links ? `<p class="hx-forge-meta">${links}</p>` : ''}
101
+ ${answering ? answerHtml(ctx, run) : ''}${run.answer && !answering ? answeredHtml(ctx, run) : ''}
81
102
  <div class="hx-run-actions">${stop}
82
103
  <button type="button" class="hx-btn hx-forge-act" data-run-select="${ctx.esc(run.runId)}" aria-pressed="${lit}" aria-label="Light the nodes of ${ctx.esc(run.runId)} on the map"${(run.nodes || []).length ? '' : ' disabled'}>${lit ? 'Lit on the map' : 'Light on the map'}</button>
83
104
  <button type="button" class="hx-btn hx-forge-act" data-run-timeline="${ctx.esc(run.runId)}" aria-expanded="${open}" aria-controls="run-tl-${ctx.esc(run.runId)}">Timeline (${count})</button></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.15.0",
3
+ "version": "0.16.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)",
@@ -10,6 +10,7 @@
10
10
  * GET /api/agent-runs/<runId> one run
11
11
  * POST /api/agent-runs the dashboard's Start an agent: the same body as the API
12
12
  * POST /api/agent-runs/<runId>/stop { note? } asks the runner to stop
13
+ * POST /api/agent-runs/<runId>/answer { action: 'continue' | 'stop' | 'reply', text? } answers a run that reported `waiting`
13
14
  *
14
15
  * **The call takes an agent token and nothing else,** exactly as the review API takes a review token (server/review-api.js): it runs
15
16
  * before the sign-in guard (a script has no cookie), reads no cookie, needs no same-origin check (a browser never adds an `Authorization`
@@ -156,7 +157,7 @@ export async function serveAgentCall(req, res, ctx) {
156
157
  * @returns {Promise<boolean>} whether the path was one of these
157
158
  */
158
159
  export async function serveRunRoutes(req, res, reqPath, ctx) {
159
- const m = /^\/api\/agent-runs(?:\/(run-[0-9A-Za-z]{26}))?(\/stop)?$/.exec(reqPath);
160
+ const m = /^\/api\/agent-runs(?:\/(run-[0-9A-Za-z]{26}))?(\/stop|\/answer)?$/.exec(reqPath);
160
161
  if (!m || (m[2] && !m[1])) return false;
161
162
  const { auth, runs, session } = ctx;
162
163
  const runId = m[1] ?? null;
@@ -211,9 +212,15 @@ export async function serveRunRoutes(req, res, reqPath, ctx) {
211
212
  problem = { status: 400, message: 'The request could not be read.' };
212
213
  }
213
214
  }
214
- if (runId && !problem && (body === null || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some((k) => k !== 'note'))) problem = { status: 400, message: 'A stop request is { note? }.' };
215
+ const answering = m[2] === '/answer';
216
+ if (runId && !problem && (body === null || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some((k) => !(answering ? ['action', 'text'] : ['note']).includes(k)))) {
217
+ problem = { status: 400, message: answering ? 'An answer is { action: "continue" | "stop" | "reply", text? }.' : 'A stop request is { note? }.' };
218
+ }
215
219
  try {
216
- if (runId) {
220
+ if (runId && answering) {
221
+ const answered = await runs.answer(ask, { runId, action: /** @type {any} */ (body)?.action, text: /** @type {any} */ (body)?.text, problem });
222
+ send(res, 200, { ok: true, ...answered });
223
+ } else if (runId) {
217
224
  const stopped = await runs.stop(ask, { runId, note: /** @type {any} */ (body)?.note, problem });
218
225
  send(res, 200, { ok: true, ...stopped });
219
226
  } else {
@@ -41,11 +41,21 @@
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
+ * ## Waiting, and the answer (issue #101)
45
+ *
46
+ * 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
47
+ * 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
48
+ * replaces the first, until the runner reports again) and comes back through `GET /api/runs/<runId>` as `answer: { action, text?, at, by }`, the
49
+ * 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
50
+ * 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
51
+ * clears the answer of the wait before. Hooks: `run.waiting` (the runner asked), `run.answered` (a maintainer answered; the action, never the text).
52
+ *
44
53
  * ## What counts as open
45
54
  *
46
55
  * 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
56
  * 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.
57
+ * 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**
58
+ * 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
59
  *
50
60
  * ## Following (`follow`)
51
61
  *
@@ -63,14 +73,14 @@
63
73
  * - **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
74
  *
65
75
  * 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).
76
+ * 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`,
77
+ * `run.stopRequested`, `run.finished` (server/hooks.js).
68
78
  *
69
79
  * @typedef {import('../core/agent-contract.js').RunRequest} RunRequest
70
80
  * @typedef {{ run_id: string, repo: string, kind: string, profile: string | null, issue: number | null, proposal: string | null, thread: number | null,
71
81
  * target: number, comment_id: string, comment_url: string | null, request: string, requested_by: string, requested_by_id: string, requested_at: string,
72
82
  * 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,
83
+ * 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
84
  * pull_url: string | null, pull_by: string | null, pull_trusted: number, linked_via: string | null, branch: string | null, head_sha: string | null,
75
85
  * checks: string | null, last_activity: string }} RunRow
76
86
  */
@@ -78,7 +88,7 @@
78
88
  import fs from 'node:fs';
79
89
  import path from 'node:path';
80
90
  import { ForgeError, isMaintainer } from './forge.js';
81
- import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
91
+ import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateAnswer, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
82
92
  import { quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
83
93
  import { runnerPresence } from './runner-presence.js';
84
94
  import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
@@ -127,13 +137,18 @@ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
127
137
  const words = (err) => (err instanceof Error ? err.message : String(err));
128
138
  const maxIso = (a, b) => (Date.parse(b) > Date.parse(a) ? b : a);
129
139
 
140
+ /** 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 */
141
+ const waitsOnMaintainer = (row) => row.state === 'waiting' && !row.stop_requested_at;
142
+
130
143
  /**
131
144
  * What a run is, as of `nowMs`, from the runner's reports and what the forge shows. Pure.
132
145
  *
133
146
  * done / failed / stopped the runner's latest report
134
147
  * merged / closed its (trusted) pull request ended
135
- * quiet nothing happened within `quietMs`
148
+ * quiet nothing happened within `quietMs`, unless it is waiting (below)
136
149
  * stop-requested a maintainer asked it to stop and the runner has not said so
150
+ * waiting the runner's latest report: it asks a maintainer (open: the run is not over). A run waiting on a maintainer
151
+ * 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
152
  * claimed / working the runner's latest report
138
153
  * working no report, but a (trusted) pull request or a branch carries its id: a silent runner is seen through what it pushes
139
154
  * requested asked for, nothing seen yet
@@ -149,7 +164,7 @@ export function statusOf(row, nowMs, quietMs) {
149
164
  let status;
150
165
  if (REPORT_FINISHED.includes(row.state)) status = row.state;
151
166
  else if (ended) status = /** @type {string} */ (row.pull_state);
152
- else if (nowMs - Date.parse(row.last_activity) >= quietMs) status = 'quiet';
167
+ else if (!waitsOnMaintainer(row) && nowMs - Date.parse(row.last_activity) >= quietMs) status = 'quiet';
153
168
  else if (row.stop_requested_at) status = 'stop-requested';
154
169
  else if (row.state !== 'requested') status = row.state;
155
170
  else status = (row.pull_trusted === 1 && row.pull) || row.branch ? 'working' : 'requested';
@@ -174,6 +189,11 @@ function subjectKeys(refs) {
174
189
 
175
190
  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
191
 
192
+ /** A maintainer's answer to the latest wait as the API shows it (the runner reads the same), or null */
193
+ function answerOf(row) {
194
+ return row.answer_at ? { action: row.answer_action, ...(row.answer_text ? { text: row.answer_text } : {}), at: row.answer_at, by: row.answer_by } : null;
195
+ }
196
+
177
197
  /**
178
198
  * 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
199
  * database's own. Text the runner wrote (a note, a link) is data for the page to escape.
@@ -194,6 +214,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
194
214
  limits,
195
215
  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
216
  stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
217
+ answer: answerOf(row),
197
218
  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
219
  branch: row.branch, headSha: row.head_sha, checks: row.checks, lastActivity: row.last_activity,
199
220
  ...extra,
@@ -671,6 +692,109 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
671
692
  }
672
693
  }
673
694
 
695
+ /**
696
+ * A maintainer's answer to a run that reported `waiting`: `continue`, `stop` or a `reply` (text). Throws like `stop`.
697
+ * - **Stop** is `stop` itself (the same checks, block, audit row and hook), with the answer recorded beside it.
698
+ * - **Continue and reply** are kept on the run, replacing an earlier answer to the same wait; on the forge the `answered` block is posted
699
+ * 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.
700
+ * @param {RequestContext} ctx
701
+ * @param {{ runId: unknown, action?: unknown, text?: unknown, problem?: { status: number, message: string } }} input
702
+ */
703
+ async function answer(ctx, { runId, action, text, problem }) {
704
+ const { who, via = null } = ctx;
705
+ // 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
706
+ const stopping = action === 'stop' && !problem && validateAnswer({ state: 'answered', action, ...(text !== undefined ? { text } : {}) }).ok
707
+ && typeof runId === 'string' && /** @type {RunRow | undefined} */ ((await auth.store()).prepare('SELECT state FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo))?.state === 'waiting';
708
+ if (stopping) {
709
+ const stopped = await stop(ctx, { runId, note: text, problem });
710
+ const db = await auth.store();
711
+ const stamp = iso(now());
712
+ const kept = db.prepare("UPDATE runs SET answer_action = 'stop', answer_text = ?, answer_at = ?, answer_by = ? WHERE run_id = ? AND state = 'waiting'")
713
+ .run(typeof text === 'string' && text.trim() !== '' ? text : null, stamp, who.login, stopped.run.runId).changes;
714
+ const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(stopped.run.runId));
715
+ if (kept) hooks?.emit('run.answered', { ...runPayload(after, who.login), action: 'stop' });
716
+ return { ...stopped, run: publicRun(after, now(), quietMs, extrasFor(db, [after], now()).get(after.run_id)) };
717
+ }
718
+ const at = ctx.limits.now ?? now;
719
+ const flood = countAttempt(ctx.limits, who.userId, at());
720
+ if (flood) throw flood;
721
+ let target = repo;
722
+ let done = false;
723
+ let release = () => {};
724
+ 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 } : {}) };
725
+ try {
726
+ if (problem) throw new Refused(problem.status, problem.message, 'invalid');
727
+ const checked = validateAnswer({ state: 'answered', action, ...(text !== undefined ? { text } : {}) });
728
+ if (!checked.ok) throw new Refused(400, checked.error, 'invalid');
729
+ const a = checked.value;
730
+ const db = await auth.store();
731
+ const row = typeof runId === 'string' ? /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo)) : undefined;
732
+ if (!row) throw new Refused(404, 'cornfield has no such run.', 'not-found');
733
+ target = `${repo}#${row.target}`;
734
+ release = throttle(ctx.limits, who.userId, `agent-answer|${row.run_id}`, at());
735
+ const forge = await ctx.forge();
736
+ const me = await forge.me();
737
+ if (String(me.id) !== who.userId) throw new Refused(403, 'The forge says this sign-in is someone else now; sign in again.', 'forbidden');
738
+ 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');
739
+ const was = statusOf(row, now(), quietMs);
740
+ if (was.finished) throw new Refused(409, `Run ${row.run_id} is ${was.status}; there is nothing to answer.`, 'conflict');
741
+ 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');
742
+ 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');
743
+ if (a.action === 'stop') throw new Refused(409, `Run ${row.run_id} changed while the answer was being taken; read it again.`, 'conflict');
744
+ if (ctx.stillAllowed) {
745
+ const why = await ctx.stillAllowed();
746
+ if (why) throw new Refused(403, why, 'forbidden');
747
+ }
748
+ const stamp = iso(now());
749
+ let posted = null;
750
+ if (row.transport === 'forge') {
751
+ let comment;
752
+ try {
753
+ 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}\`` : ''}).` });
754
+ } catch (err) {
755
+ throw new Refused(400, words(err), 'invalid');
756
+ }
757
+ posted = await forge.comment(row.target, comment);
758
+ }
759
+ db.exec('BEGIN IMMEDIATE');
760
+ try {
761
+ // 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
762
+ // 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,
763
+ // not even one that came too late for the wait it answered (kept even when the answer is refused below)
764
+ if (posted) {
765
+ 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);
766
+ 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);
767
+ }
768
+ 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")
769
+ .run(a.action, a.text ?? null, stamp, me.login, stamp, row.run_id).changes;
770
+ if (kept !== 1) {
771
+ db.exec('COMMIT');
772
+ throw new Refused(409, `Run ${row.run_id} changed while the answer was being taken; read it again.`, 'conflict');
773
+ }
774
+ // Two maintainers answering at once: the last write wins on the run, and the timeline keeps both
775
+ 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 });
776
+ db.exec('COMMIT');
777
+ } catch (err) {
778
+ try { db.exec('ROLLBACK'); } catch { /* nothing was begun */ }
779
+ throw err;
780
+ }
781
+ done = true;
782
+ 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 } });
783
+ const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
784
+ hooks?.emit('run.answered', { ...runPayload(after, me.login), action: a.action });
785
+ return { run: publicRun(after, now(), quietMs, extrasFor(db, [after], now()).get(after.run_id)), comment: posted ? { id: posted.id, url: posted.url ?? null } : null };
786
+ } catch (err) {
787
+ if (!done) {
788
+ const out = describe(err);
789
+ 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 } });
790
+ if (!(err instanceof Refused) && !(err instanceof ForgeError)) log(`answering ${asked.runId ?? ''} failed: ${err instanceof Error ? err.stack || err.message : err}`);
791
+ }
792
+ throw err;
793
+ } finally {
794
+ release();
795
+ }
796
+ }
797
+
674
798
  /** The body of a run hook event: which run, in what state, about what, caused by whom */
675
799
  function runPayload(row, actor) {
676
800
  return { runId: row.run_id, state: statusOf(row, now(), quietMs).status, pull: row.pull ?? undefined, issue: row.issue ?? row.thread ?? undefined, actor };
@@ -708,10 +832,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
708
832
  return row ? publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)) : null;
709
833
  }
710
834
 
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 */
835
+ /** 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
836
  function followable(db, at) {
713
837
  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 ?`)
838
+ 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
839
  .all(repo, iso(at - window), MAX_FOLLOWED));
716
840
  }
717
841
 
@@ -867,7 +991,9 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
867
991
 
868
992
  const seen = (runId, key) => db.prepare('SELECT 1 FROM run_seen WHERE run_id = ? AND key = ?').get(runId, key) !== undefined;
869
993
  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 }); };
994
+ const queue = (row, event, key, actor, state, action) => { events.push({ runId: row.run_id, event, key, actor, state, ...(action ? { action } : {}) }); };
995
+ /** 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) */
996
+ const answered = new Set();
871
997
 
872
998
  // Who counts: runners by the config, maintainers by what the forge says now (asked once per login per look)
873
999
  const maintainerOf = new Map();
@@ -986,8 +1112,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
986
1112
  const trust = (login, block) => {
987
1113
  const who = standing.get(lower(login));
988
1114
  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;
1115
+ // A report: a runner (agents.runners) or a maintainer. A stop request and an answer: a maintainer. A request is not ours to follow
1116
+ return block.type === 'report' ? who.runner || who.maintainer : block.type === 'stop-request' || block.type === 'answer' ? who.maintainer : false;
991
1117
  };
992
1118
  const found = runBlocksOf(comments, { trust });
993
1119
  const counts = new Map();
@@ -1015,7 +1141,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1015
1141
  if (!row || !ids.has(b.runId) || b.type === 'request') continue;
1016
1142
  const key = keyOf(b.comment.id, b.runId, b.type);
1017
1143
  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';
1144
+ : 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
1145
  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
1146
  }
1021
1147
  // 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 +1160,29 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1034
1160
  state: r.state, reported_at: when, reported_by: login, note: r.note ?? null, url: r.url ?? null,
1035
1161
  tokens: r.tokens ?? row.tokens, cost: r.cost ?? row.cost,
1036
1162
  });
1163
+ // A new wait is a new question: the answer to the last one is not its answer
1164
+ if (r.state === 'waiting' && previous !== 'waiting') {
1165
+ Object.assign(row, { answer_action: null, answer_text: null, answer_at: null, answer_by: null });
1166
+ answered.add(row.run_id);
1167
+ }
1037
1168
  touch(row, when);
1038
1169
  out.reports += 1;
1039
1170
  cause.set(row.run_id, key);
1040
1171
  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
1172
  if (r.state === 'claimed') queue(row, 'run.claimed', 'ev:claimed', login, 'claimed');
1042
1173
  if (r.state !== previous) queue(row, 'run.state', `ev:state:${id}:${key}`, login, r.state);
1174
+ if (r.state === 'waiting' && previous !== 'waiting') queue(row, 'run.waiting', `ev:waiting:${id}:${key}`, login, 'waiting');
1175
+ } else if (block.type === 'answer') {
1176
+ // 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
1177
+ if (row.state !== 'waiting' || (row.stop_requested_at && block.value.action !== 'stop')) continue;
1178
+ const a = block.value;
1179
+ Object.assign(row, { answer_action: a.action, answer_text: a.text ?? null, answer_at: when, answer_by: login });
1180
+ answered.add(row.run_id);
1181
+ if (a.action === 'stop' && !row.stop_requested_at) Object.assign(row, { stop_requested_at: when, stop_requested_by: login });
1182
+ touch(row, when);
1183
+ happen(row, { key: `answer:${id}`, at: when, kind: 'answered', actor: login, ref: a.action, note: a.text ?? null });
1184
+ queue(row, 'run.answered', `ev:answered:${id}:${key}`, login, 'waiting', a.action);
1185
+ if (a.action === 'stop') queue(row, 'run.stopRequested', `ev:stop:${id}:${key}`, login, 'stop-requested');
1043
1186
  } else {
1044
1187
  if (!row.stop_requested_at) Object.assign(row, { stop_requested_at: when, stop_requested_by: login });
1045
1188
  touch(row, when);
@@ -1106,6 +1249,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1106
1249
  last_activity = MAX(last_activity, ?) WHERE run_id = ?`)
1107
1250
  .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
1251
  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);
1252
+ 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
1253
  }
1110
1254
  for (const e of events) if (mark.run(e.runId, e.key, iso(at)).changes === 1) fresh.push(e);
1111
1255
  for (const ev of happened) keepEvent(db, ev.runId, ev);
@@ -1119,7 +1263,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1119
1263
  }
1120
1264
  for (const e of fresh) {
1121
1265
  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 });
1266
+ hooks?.emit(e.event, { ...runPayload(row, e.actor), state: e.state, ...(e.action ? { action: e.action } : {}) });
1123
1267
  }
1124
1268
  return out;
1125
1269
  }
@@ -1134,10 +1278,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1134
1278
  /** What a runner's act writes into the timeline: the runner, with the maintainer who minted the token kept in `mintedBy` */
1135
1279
  const runnerText = (token) => byToText(runnerBy(token));
1136
1280
 
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 */
1281
+ /** 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
1282
  function runnerView(row) {
1139
1283
  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 };
1284
+ 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
1285
  }
1142
1286
 
1143
1287
  /** The run a runner token names, or a `Refused`: 404 when there is none, 403 when the token may not touch it */
@@ -1197,7 +1341,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1197
1341
  return { request: checked.ok ? checked.value : null, run: runnerView(row), row };
1198
1342
  }
1199
1343
 
1200
- /** One run as the runner that holds it sees it: `GET /api/runs/<runId>`, how a runner learns it was asked to stop */
1344
+ /** 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
1345
  async function runnerGet(token, runId) {
1202
1346
  const db = await auth.store();
1203
1347
  return runnerView(runnerRun(db, token, runId));
@@ -1220,10 +1364,14 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1220
1364
  const was = statusOf(row, at, quietMs);
1221
1365
  if (was.finished) throw new Refused(409, `Run ${row.run_id} is ${was.status}; it takes no more reports.`, 'conflict');
1222
1366
  const stamp = iso(at);
1367
+ // A new wait is a new question: the answer to the last one goes (a repeat of `waiting` while waiting keeps it)
1368
+ const newWait = r.state === 'waiting' && row.state !== 'waiting';
1223
1369
  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, ?)
1370
+ claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?),
1371
+ answer_action = CASE WHEN ? THEN NULL ELSE answer_action END, answer_text = CASE WHEN ? THEN NULL ELSE answer_text END,
1372
+ answer_at = CASE WHEN ? THEN NULL ELSE answer_at END, answer_by = CASE WHEN ? THEN NULL ELSE answer_by END
1225
1373
  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;
1374
+ .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
1375
  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
1376
  const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
1229
1377
  // A report of `claimed` on a run the claim route already claimed is a report, not a second "Claimed" line
@@ -1231,6 +1379,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1231
1379
  const actor = runnerActor(token);
1232
1380
  if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
1233
1381
  if (r.state !== row.state) hooks?.emit('run.state', { ...runPayload(after, actor), state: r.state });
1382
+ if (newWait) hooks?.emit('run.waiting', { ...runPayload(after, actor), state: r.state });
1234
1383
  if (REPORT_FINISHED.includes(r.state)) hooks?.emit('run.finished', { ...runPayload(after, actor), state: r.state });
1235
1384
  return { run: runnerView(after), row: after, was: row };
1236
1385
  }
@@ -1257,7 +1406,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1257
1406
  return hit ? hit.run_id : null;
1258
1407
  }
1259
1408
 
1260
- return { request, stop, list, get, follow, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1409
+ return { request, stop, answer, list, get, follow, hasWork, resume, queued, claim, runnerGet, report, openOn, maxOpen: cap, profiles, transport };
1261
1410
  }
1262
1411
 
1263
1412
  /** @typedef {ReturnType<typeof createRuns>} Runs */
package/server/db.js CHANGED
@@ -19,7 +19,8 @@
19
19
  * it and when anything last happened (server/agent-runs.js, migration 7); review_tokens also keep a scope
20
20
  * (review, agent, or runner: migration 8, which also gives a run its transport and the runner token that claimed it)
21
21
  * run_seen what has been seen of each run (a comment judged, a hook event sent), so a restart sends and judges nothing twice
22
- * run_events what happened to each run, in order, for its timeline; run_reads what was read to work out its nodes (migration 9, issue #82)
22
+ * run_events what happened to each run, in order, for its timeline; run_reads what was read to work out its nodes (migration 9, issue #82);
23
+ * migration 10 lets a run wait (state 'waiting') and keeps a maintainer's answer to it (answer_* on runs, 'answered' events)
23
24
  * sessions also keep a forge refresh token, the access token's expiry and when `session.expiring` was sent (migration 5)
24
25
  *
25
26
  * The schema is a list of numbered migrations (`MIGRATIONS`); the file's `PRAGMA user_version` is the number of
@@ -258,6 +259,82 @@ export const MIGRATIONS = Object.freeze([
258
259
  PRIMARY KEY (run_id, source)
259
260
  ) STRICT;
260
261
  `,
262
+ // 10: a run may wait for a maintainer (server/agent-runs.js, issue #101): the runner's report `waiting` and the maintainer's answer. SQLite cannot
263
+ // change a CHECK, so runs (whose `state` gains 'waiting') and run_events (whose `kind` gains 'answered') are rebuilt the documented way: a new
264
+ // table, the rows copied, the old one dropped, the new one renamed, the indexes made again. The answer is kept on the run: the latest one only.
265
+ // No foreign key refers to either table and neither has a trigger, so `PRAGMA foreign_keys` (on, and not changeable inside the migration's
266
+ // transaction) leaves the rebuild alone; a later migration that adds one must rebuild with that in mind (test/server/db.test.js checks it)
267
+ `
268
+ CREATE TABLE runs_new (
269
+ run_id TEXT PRIMARY KEY,
270
+ repo TEXT NOT NULL,
271
+ kind TEXT NOT NULL,
272
+ profile TEXT,
273
+ issue INTEGER,
274
+ proposal TEXT,
275
+ thread INTEGER,
276
+ target INTEGER NOT NULL,
277
+ comment_id TEXT NOT NULL DEFAULT '',
278
+ comment_url TEXT,
279
+ request TEXT NOT NULL CHECK (json_valid(request)),
280
+ requested_by TEXT NOT NULL,
281
+ requested_by_id TEXT NOT NULL,
282
+ requested_at TEXT NOT NULL,
283
+ via TEXT NOT NULL DEFAULT 'dashboard',
284
+ state TEXT NOT NULL DEFAULT 'requested' CHECK (state IN ('requested', 'claimed', 'working', 'waiting', 'done', 'failed', 'stopped')), -- the runner's latest report
285
+ reported_at TEXT,
286
+ reported_by TEXT,
287
+ note TEXT,
288
+ url TEXT,
289
+ tokens INTEGER,
290
+ cost REAL,
291
+ stop_requested_at TEXT,
292
+ stop_requested_by TEXT,
293
+ pull INTEGER,
294
+ pull_state TEXT CHECK (pull_state IS NULL OR pull_state IN ('open', 'merged', 'closed')),
295
+ pull_url TEXT,
296
+ pull_by TEXT,
297
+ pull_trusted INTEGER NOT NULL DEFAULT 0,
298
+ linked_via TEXT CHECK (linked_via IS NULL OR linked_via IN ('body', 'commit', 'branch')),
299
+ branch TEXT,
300
+ head_sha TEXT,
301
+ checks TEXT CHECK (checks IS NULL OR checks IN ('success', 'failure', 'running', 'none')),
302
+ last_activity TEXT NOT NULL,
303
+ transport TEXT NOT NULL DEFAULT 'forge' CHECK (transport IN ('forge', 'push', 'pull')),
304
+ claimed_by INTEGER,
305
+ claimed_at TEXT,
306
+ answer_action TEXT CHECK (answer_action IS NULL OR answer_action IN ('continue', 'stop', 'reply')), -- a maintainer's answer to the latest wait; a new 'waiting' report clears it
307
+ answer_text TEXT,
308
+ answer_at TEXT,
309
+ answer_by TEXT
310
+ ) STRICT;
311
+ INSERT INTO runs_new (run_id, repo, kind, profile, issue, proposal, thread, target, comment_id, comment_url, request, requested_by, requested_by_id, requested_at, via,
312
+ state, reported_at, reported_by, note, url, tokens, cost, stop_requested_at, stop_requested_by, pull, pull_state, pull_url, pull_by, pull_trusted, linked_via,
313
+ branch, head_sha, checks, last_activity, transport, claimed_by, claimed_at)
314
+ SELECT run_id, repo, kind, profile, issue, proposal, thread, target, comment_id, comment_url, request, requested_by, requested_by_id, requested_at, via,
315
+ state, reported_at, reported_by, note, url, tokens, cost, stop_requested_at, stop_requested_by, pull, pull_state, pull_url, pull_by, pull_trusted, linked_via,
316
+ branch, head_sha, checks, last_activity, transport, claimed_by, claimed_at FROM runs;
317
+ DROP TABLE runs;
318
+ ALTER TABLE runs_new RENAME TO runs;
319
+ CREATE INDEX runs_repo ON runs (repo, requested_at);
320
+ CREATE INDEX runs_queue ON runs (repo, transport, state, requested_at);
321
+
322
+ CREATE TABLE run_events_new (
323
+ run_id TEXT NOT NULL,
324
+ key TEXT NOT NULL,
325
+ at TEXT NOT NULL,
326
+ kind TEXT NOT NULL CHECK (kind IN ('claimed', 'report', 'stop-requested', 'answered', 'push', 'pull-opened', 'checks', 'merged', 'closed')),
327
+ actor TEXT,
328
+ ref TEXT, -- for 'answered': the action (continue, stop, reply); note is a reply's text
329
+ note TEXT,
330
+ url TEXT,
331
+ PRIMARY KEY (run_id, key)
332
+ ) STRICT;
333
+ INSERT INTO run_events_new (run_id, key, at, kind, actor, ref, note, url) SELECT run_id, key, at, kind, actor, ref, note, url FROM run_events;
334
+ DROP TABLE run_events;
335
+ ALTER TABLE run_events_new RENAME TO run_events;
336
+ CREATE INDEX run_events_at ON run_events (run_id, at);
337
+ `,
261
338
  ]);
262
339
 
263
340
  /** The version a file is at: its `user_version` */
package/server/hooks.js CHANGED
@@ -30,9 +30,11 @@
30
30
  * Its body is its own: `{ event, at, trigger: { event, by, ref }, by, reason, mapUrl }`
31
31
  * runner.offline on the pull transport, the last live runner token has not polled for `agents.runnerQuietAfter` (3 minutes unless set; server/runner-presence.js).
32
32
  * Once, and again only after a runner has been seen online again. Its body is its own: `{ event, at, label, lastSeen, mapUrl }`, never a token
33
- * run.claimed run.state run.stopRequested run.finished a run was claimed by its runner, changed state, was asked to stop, ended. They are
33
+ * run.claimed run.state run.waiting run.answered run.stopRequested run.finished a run was claimed by its runner, changed state, reported
34
+ * `waiting` (it asks a maintainer), was answered, was asked to stop, ended. They are
34
35
  * seen when cornfield looks (the spec poll, server/spec-poll.js), each once. Their body is their own:
35
- * `{ event, at, runId, state, pull?, issue?, actor, mapUrl }`
36
+ * `{ event, at, runId, state, pull?, issue?, action?, actor, mapUrl }`; `action` (continue, stop or reply) is only on `run.answered`,
37
+ * and a reply's words are never in it
36
38
  *
37
39
  * **Triggers listen in-process.** `subscribe(fn)` hands a function the same moments the hooks fire at, with the payload resolved, whether or not
38
40
  * any hook asks for them (server/triggers.js: `spec.approved`, `build.opened`, `thread.message`). A thread's payload then also holds the
@@ -226,11 +228,12 @@ export function createHooks({ hooks, secret, fetch: doFetch = globalThis.fetch,
226
228
  if (!checked.ok) throw new Error(checked.error);
227
229
  return JSON.stringify({ event, at: new Date(now()).toISOString(), request: checked.value, actor: p.actor ?? null, mapUrl: publicUrl || null });
228
230
  }
229
- // The events of a run (claimed, state, stopRequested, finished) say which run, in what state, and about what
231
+ // The events of a run (claimed, state, waiting, answered, stopRequested, finished) say which run, in what state, and about what
230
232
  if (event.startsWith('run.')) {
231
233
  return JSON.stringify({
232
234
  event, at: new Date(now()).toISOString(), runId: p.runId ?? null, state: p.state ?? null,
233
- ...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}), actor: p.actor ?? null, mapUrl: publicUrl || null,
235
+ ...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}),
236
+ ...(event === 'run.answered' && ['continue', 'stop', 'reply'].includes(p.action) ? { action: p.action } : {}), actor: p.actor ?? null, mapUrl: publicUrl || null,
234
237
  });
235
238
  }
236
239
  // A thread's event is only which thread, which comment, who and what it links to: never the words said