@popcorn245/cornfield 0.18.0 → 0.19.1

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.
@@ -50,7 +50,7 @@
50
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
51
51
  */
52
52
 
53
- import { defuse } from './defuse.js';
53
+ import { defuse, quoteInert } from './defuse.js';
54
54
 
55
55
  /** Ten (or `n`) random bytes, from the Web Crypto API that Node and the browser both have */
56
56
  const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
@@ -543,7 +543,7 @@ export function formatRunComment(runId, body, { line, profiles } = {}) {
543
543
  const head = oneLine(line ?? defaultLine(runId, checked.type, checked.value));
544
544
  // An answer's text is the maintainer's words to the runner: it travels in the block only, never quoted beside it
545
545
  const note = checked.type === 'request' || checked.type === 'answer' ? '' : (checked.value.note ?? '').trim();
546
- const quoted = note ? `\n\n${defuse(note).split(/\r?\n/).map((l) => (l ? `> ${l}` : '>')).join('\n')}` : '';
546
+ const quoted = note ? `\n\n${quoteInert(note)}` : '';
547
547
  const out = `${head}${quoted}\n\n${block}`;
548
548
  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.`);
549
549
  return out;
package/core/config.js CHANGED
@@ -175,7 +175,7 @@ export const PROPOSALS_KEYS = Object.freeze(['dir', 'approveLands']);
175
175
  /** The keys of `worktrees` when it is an object: the folder, and how many days without a change leave a worktree out of the list (default: none is left out) */
176
176
  export const WORKTREES_KEYS = Object.freeze(['dir', 'maxAgeDays']);
177
177
  const MAX_WORKTREE_AGE_DAYS = 36500;
178
- const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'runnerQuietAfter', 'limits', 'on', 'refuseCollisions', 'handWritten'];
178
+ const AGENT_KEYS = ['authors', 'labels', 'branchPrefixes', 'bots', 'transport', 'maxOpen', 'profiles', 'runners', 'quietAfter', 'runnerQuietAfter', 'limits', 'on', 'refuseCollisions', 'handWritten', 'mirror'];
179
179
  const PROFILE_NAME = new RegExp(PROFILE_SOURCE);
180
180
  const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
181
181
  const isText = (v) => typeof v === 'string' && v.trim() !== '';
@@ -393,6 +393,7 @@ function agentRunProblems(a) {
393
393
  const out = [];
394
394
  if (a.transport !== undefined && !AGENT_TRANSPORTS.includes(a.transport)) out.push(`agents.transport is ${AGENT_TRANSPORTS.map((t) => JSON.stringify(t)).join(', ')}: where a request goes: "forge" posts it as a comment (the default), "push" sends it as an agent.requested hook event, "pull" keeps it for a runner to claim (docs/agents.md#transports).`);
395
395
  if (a.refuseCollisions !== undefined && typeof a.refuseCollisions !== 'boolean') out.push('agents.refuseCollisions is true or false: whether a new request that names a node an open run is already changing is refused (false unless set).');
396
+ if (a.mirror !== undefined && typeof a.mirror !== 'boolean') out.push('agents.mirror is true (the default) or false: whether cornfield keeps one status comment per run in the thread the run is about, edited as the run moves (docs/agents.md#a-thread-for-every-run).');
396
397
  if (a.handWritten !== undefined && a.handWritten !== true && a.handWritten !== false && a.handWritten !== 'labeled') out.push('agents.handWritten is true (the default: a maintainer\'s hand-written request block on any open issue or pull request becomes a run), "labeled" (only on those with the threads label) or false (cornfield follows only the runs it asked for): docs/agents.md#requests-written-by-hand.');
397
398
  if (a.maxOpen !== undefined && !(Number.isInteger(a.maxOpen) && a.maxOpen >= 1 && a.maxOpen <= MAX_OPEN_CEILING)) out.push(`agents.maxOpen is a whole number from 1 to ${MAX_OPEN_CEILING}: the most open runs cornfield asks for at once (${DEFAULT_MAX_OPEN} unless set).`);
398
399
  if (a.profiles !== undefined) {
package/core/defuse.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * `#1`, `owner/repo#1`, `GH-1`, and the links the forge would make of `https://…` or `www.…`. A zero-width space after
6
6
  * the character keeps the text as it reads and stops it notifying anyone or linking anything. The pipeline's issues
7
7
  * (server/pipeline.js), a review that came through the review API (server/reviews.js) and the agent contract
8
- * (core/agent-contract.js) use it. It imports nothing, so Node and the browser can both load it.
8
+ * (core/agent-contract.js) use it; `inert` and `quoteInert` also make someone else's words plain Markdown, the way the agent contract
9
+ * and a run's thread (server/run-thread.js) show a runner's note. It imports nothing, so Node and the browser can both load it.
9
10
  */
10
11
 
11
12
  /** A zero-width space: it ends a mention or a reference without showing */
@@ -15,3 +16,20 @@ export const ZW = '​';
15
16
  export function defuse(text) {
16
17
  return String(text).replace(/[@#]/g, (c) => `${c}${ZW}`).replace(/\b(GH)-(?=\d)/gi, `$1${ZW}-`).replace(/:\/\//g, `:${ZW}//`).replace(/\b(www)\./gi, `$1${ZW}.`);
17
18
  }
19
+
20
+ /**
21
+ * Text that makes no Markdown of its own: `\\` escaped first (so no escape of ours is undone), `&` and `<` as entities (no HTML, no
22
+ * character reference), `[` escaped (no link, image or `[[node]]`), backticks made `'` and runs of tildes broken (no code span, no fence).
23
+ * Mentions, references and links are not touched here: `defuse` them first.
24
+ */
25
+ export function inert(text) {
26
+ return String(text).replace(/\\/g, '\\\\').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\[/g, '\\[').replace(/`/g, "'").replace(/~(?=~)/g, `~${ZW}`);
27
+ }
28
+
29
+ /**
30
+ * Text quoted line by line, defused and inert: every line end Markdown and the agent contract's reader know (`\r\n`, `\r` alone, `\n`)
31
+ * ends a line here, and every line is behind `> ` (an empty one is `>`), so no line escapes the quote and nothing in it opens a fence.
32
+ */
33
+ export function quoteInert(text) {
34
+ return inert(defuse(text)).split(/\r\n?|\n/).map((l) => (l.trim() ? `> ${l}` : '>')).join('\n');
35
+ }
@@ -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, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines, limitsWords, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
72
+ RUNS_URL, runsUrl, stopUrl, runOnThread, threadRunWords, runTone, answerUrl, answerBody, answerWordsFor, KINDS, aboutWords, statusWords, statusWhy, runMeta, canStop, runsStatus, runnerState, runnerWords, triggerNotice, totalsLines, handLines, limitsWords, startBody, startWords, stopWords, confirmStartWords, litOfRun, changeWords,
73
73
  } from './runs-model.js';
74
74
  import { runsHtml, totalsHtml } from './runs-view.js';
75
75
  import { setRunsOnMap, clearRunsOnMap } from './runs-map.js';
@@ -257,7 +257,11 @@ async function loadList(refresh = false, quiet = false) {
257
257
  ui.loading = false;
258
258
  if (res.ok) {
259
259
  ui.lists[key] = { items: res.body.items || [], at: res.body.at, rate: res.body.rate || '', stale: res.body.stale || '', problem: res.body.problem || '' };
260
- if (ui.kind === 'threads') repaintThreads();
260
+ if (ui.kind === 'threads') {
261
+ repaintThreads();
262
+ // A thread's row names the state of the run that is about it (issue #104): the runs are read, once, when the tab is the first thing opened
263
+ if (!ui.runs) loadRuns(false, { say: false }).then(() => { if (ui.open && ui.kind === 'threads') paint(); }, () => {});
264
+ }
261
265
  if (!quiet) announce(`${plural(filterItems(ui.lists[key].items, ui.kind, ui.filters).length, kindWords())} shown${ui.lists[key].stale ? '. This is an older answer' : ''}`);
262
266
  } else {
263
267
  ui.error = errorWords(res.status, res.body);
@@ -850,9 +854,13 @@ function threadHtml(t) {
850
854
  const link = safeUrl(t.url);
851
855
  const out = link ? `<a class="hx-forge-out" href="${escHtml(link)}" target="_blank" rel="noreferrer" aria-label="Open thread ${t.number} on ${escHtml(forgeName())} (new tab)">↗</a>` : '';
852
856
  const note = [t.proposals && t.proposals.length ? `Proposal ${t.proposals.map((p) => p.slug).join(', ')}` : '', t.idea ? `Idea #${t.idea}` : ''].filter(Boolean).join(' · ');
857
+ // The run that is about this thread, as a word (issue #104): the Agents tab's list, read for every tab, says it; the row only names its state
858
+ const runs = ui.runs && ui.runs.data ? ui.runs.data.runs : null;
859
+ const run = runOnThread(runs, t.number);
860
+ const runWord = run ? `<span class="hx-forge-state hx-forge-state--${runTone(run)}" data-thread-run="${escHtml(run.runId)}">${escHtml(threadRunWords(runs, t.number))}</span> ` : '';
853
861
  return `<li class="hx-forge-item"><button type="button" class="hx-forge-row" data-forge-thread="${t.number}" aria-pressed="${ui.thread === t.number}">
854
862
  <span class="hx-forge-title">${escHtml(t.title)}</span>
855
- <span class="hx-forge-meta"><span class="hx-forge-state hx-forge-state--${escHtml(t.state)}">${escHtml(t.state === 'open' ? 'Open' : 'Closed')}</span> <span class="hx-forge-label">${escHtml(threadKindWords(t))}</span> ${escHtml(threadMeta(t, now()))}</span>${note ? `<span class="hx-forge-meta">${escHtml(note)}</span>` : ''}</button>${out}</li>`;
863
+ <span class="hx-forge-meta"><span class="hx-forge-state hx-forge-state--${escHtml(t.state)}">${escHtml(t.state === 'open' ? 'Open' : 'Closed')}</span> ${runWord}<span class="hx-forge-label">${escHtml(threadKindWords(t))}</span> ${escHtml(threadMeta(t, now()))}</span>${note ? `<span class="hx-forge-meta">${escHtml(note)}</span>` : ''}</button>${out}</li>`;
856
864
  }
857
865
 
858
866
  function itemHtml(item, before = '', after = '') {
@@ -39,6 +39,32 @@ export function statusWords(run) {
39
39
  return words[run.status] || run.status;
40
40
  }
41
41
 
42
+ /** The colour class (`hx-forge-state--<tone>`) of a run's state: done and merged are green, failed red, a run that is waiting on someone or has gone quiet amber, the rest in motion */
43
+ export const RUN_TONE = Object.freeze({ done: 'success', merged: 'success', failed: 'failure', quiet: 'queued', 'stop-requested': 'queued', waiting: 'queued' });
44
+ export const runTone = (run) => RUN_TONE[run.status] || 'running';
45
+
46
+ /**
47
+ * The run to show on the row of a thread (issue #104): the run whose conversation the thread is (`thread.number`, which the server fills in;
48
+ * `target` for an older answer), an open one before a finished one, then the newest. `null` when no run is about it.
49
+ * @param {{ status: string, open?: boolean, requestedAt?: string, target?: number, thread?: { number: number } }[] | null | undefined} runs
50
+ * @param {number} number the thread's number (its issue, or its spec pull request)
51
+ */
52
+ export function runOnThread(runs, number) {
53
+ if (!Array.isArray(runs)) return null;
54
+ const mine = runs.filter((r) => (r.thread && Number.isInteger(r.thread.number) ? r.thread.number : r.target) === number);
55
+ if (!mine.length) return null;
56
+ const newest = (a, b) => Date.parse(b.requestedAt || 0) - Date.parse(a.requestedAt || 0);
57
+ return [...mine.filter((r) => r.open === true).sort(newest), ...mine.filter((r) => r.open !== true).sort(newest)][0];
58
+ }
59
+
60
+ /** What a thread's row says of its run, in a few words: "Run: Working" (more than one run on it: "Run: Working (+1)") */
61
+ export function threadRunWords(runs, number) {
62
+ const run = runOnThread(runs, number);
63
+ if (!run) return '';
64
+ const more = runs.filter((r) => (r.thread && Number.isInteger(r.thread.number) ? r.thread.number : r.target) === number).length - 1;
65
+ return `Run: ${statusWords(run)}${more > 0 ? ` (+${more})` : ''}`;
66
+ }
67
+
42
68
  /** Why a state is what it is, for people who ask: one line under the state */
43
69
  export function statusWhy(run) {
44
70
  switch (run.status) {
@@ -9,9 +9,8 @@
9
9
  */
10
10
 
11
11
  import { relativeTime } from './review-model.js';
12
- import { aboutWords, statusWords, statusWhy, runMeta, canStop, canAnswer, groupRuns, compareTitle, limitRows, checksWords, timelineWords, nodeLabels, collisionWords, answerWords } from './runs-model.js';
12
+ import { runTone, 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', waiting: 'queued' };
15
14
 
16
15
  /**
17
16
  * @typedef {object} ViewContext
@@ -85,7 +84,7 @@ export function totalsHtml(ctx, lines) {
85
84
  export function runHtml(ctx, run, all) {
86
85
  const lit = ctx.selected === run.runId;
87
86
  const open = ctx.timelines.has(run.runId);
88
- const tone = TONE[run.status] || 'running';
87
+ const tone = runTone(run);
89
88
  const why = statusWhy(run);
90
89
  const note = run.report && run.report.note ? `<p class="hx-forge-meta">Runner: ${ctx.esc(run.report.note)}</p>` : '';
91
90
  const answering = canAnswer(run);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.18.0",
3
+ "version": "0.19.1",
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)",
@@ -71,6 +71,25 @@
71
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
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
73
  *
74
+ * ## A thread for every run (`mirror`, issue #104)
75
+ *
76
+ * A run is about a conversation: its `target`, the issue, thread or spec pull request its request was (or, over push and pull, would have been)
77
+ * posted on. cornfield keeps **one status comment per run** there and **edits it in place** as the run moves (the forge's `editComment`;
78
+ * `run_mirrors` keeps its id and a hash of the text last written, so a look that finds nothing new writes nothing). The comment (server/run-thread.js)
79
+ * holds the state as a word, who asked, the runner's last report with its note quoted, the branch, and the run's pull request, linked once it opens
80
+ * (so a run from a proposal shows its pull request in the proposal's thread). It never holds a `cornfield-run` block, so it is no request, report,
81
+ * stop request or answer to anything; the text is defused; the poll's tick, `discover` and the triggers read it and find nothing to do.
82
+ *
83
+ * - **when**: at once for a run asked for over push or pull (the thread otherwise never hears of it), after a stop request or an answer, and on every
84
+ * look (`follow`) for any run whose text has changed. A runner's report over push or pull that moves the state is nudged there just after it is
85
+ * answered, with the last look's forge if that look is recent (`nudge`, `NUDGE_FRESH_MS`); else it reaches the thread at the next look. A run asked for on
86
+ * the forge gets it once there is something beyond its request to say (its request comment is already in the thread)
87
+ * - **who**: the maintainer whose forge made the call, so a run's comment is written as the maintainer who asked when they are at the dashboard, and as the
88
+ * poll's signed-in maintainer when it is a look that finds a change. A comment edited by someone else is overwritten at the next change; one deleted
89
+ * is not posted again (`gone`)
90
+ * - **less noise**: an edit notifies nobody, so a run costs its thread one notification however long it runs. `agents.mirror: false` turns it all off
91
+ * - at most `MAX_MIRRORS` comments a look (a refusal counts); a forge that refuses one is logged and tried again at the next look
92
+ *
74
93
  * ## What counts as open
75
94
  *
76
95
  * A run is **open** unless it is finished or quiet (`statusOf`): finished is the runner's report `done`, `failed` or `stopped`, or its pull
@@ -118,6 +137,7 @@ import { readTopology } from '../core/validate.js';
118
137
  import { findPullProposal, listPullProposals, pullProposals, readPullProposal } from './proposal-pulls.js';
119
138
  import { Refused, countAttempt, throttle } from './throttle.js';
120
139
  import { byFromText, byToText, runnerBy } from './review-tokens.js';
140
+ import { formatRunStatus } from './run-thread.js';
121
141
 
122
142
  /** Requests one person may make in a minute (a ceiling of its own; every other action is counted by `ATTEMPTS_PER_MINUTE` and `PER_MINUTE`) */
123
143
  export const AGENT_REQUESTS_PER_MINUTE = 6;
@@ -150,6 +170,11 @@ export const MAX_HAND_READS = 30;
150
170
  /** The most refused or ignored hand-written blocks the Runs view lists (newest first), and how far back */
151
171
  export const HAND_SHOWN = 20;
152
172
  export const HAND_SHOWN_MS = 7 * 24 * 3_600_000;
173
+ /** The most status comments one look posts or edits (the rest wait for the next look), and how long a claim on one is held before it is taken as lost */
174
+ export const MAX_MIRRORS = 10;
175
+ export const MIRROR_BUSY_MS = 2 * 60_000;
176
+ /** How recent the last look must be for a runner's report to nudge its status comment with that look's sign-in (older: the next look writes it) */
177
+ export const NUDGE_FRESH_MS = 10 * 60_000;
153
178
  /** The most hand-written blocks one look judges, so a thread full of them cannot grow the audit table in one tick */
154
179
  export const MAX_HAND_JUDGED = 50;
155
180
  /** The runs that are over once the runner has said so */
@@ -329,6 +354,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
329
354
  const log = (what) => console.error(`[cornfield] agent runs: ${what}`);
330
355
  let following = null;
331
356
  let discovering = null;
357
+ /** The forge of the last look (a maintainer's sign-in: the poll's, or the one at the dashboard who asked to look now), and when; a report nudges with it */
358
+ let lastLook = null;
359
+ /** The runs whose status comment a report has nudged and that is not written yet: one nudge at a time per run */
360
+ const nudging = new Set();
332
361
 
333
362
  const audit = async (entry) => {
334
363
  try {
@@ -398,17 +427,79 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
398
427
  const ask = db.prepare('SELECT at, kind, actor, ref, note, url FROM run_events WHERE run_id = ? ORDER BY at, rowid LIMIT ?');
399
428
  for (const r of rows) events.set(r.run_id, ask.all(r.run_id, TIMELINE_LIMIT));
400
429
  }
430
+ const mirrors = new Map(rows.length ? /** @type {{ run_id: string, comment_url: string | null, gone: number }[]} */ (db.prepare(`SELECT run_id, comment_url, gone FROM run_mirrors WHERE run_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map((r) => r.run_id))).map((m) => [m.run_id, m]) : []);
401
431
  return new Map(rows.map((r) => {
402
432
  const mine = nodesOf.get(r.run_id);
433
+ const kept = mirrors.get(r.run_id);
403
434
  const collidesWith = openIds.has(r.run_id)
404
435
  ? open.filter((o) => o.run_id !== r.run_id && nodesOf.get(o.run_id).nodes.some((id) => mine.nodes.includes(id))).map((o) => o.run_id)
405
436
  : [];
406
437
  let brief = '';
407
438
  try { brief = String(JSON.parse(r.request).brief ?? '').slice(0, BRIEF_SHOWN); } catch { brief = ''; }
408
- return [r.run_id, { brief, nodes: mine.nodes, nodesFrom: mine.from, collidesWith, timeline: timelineOf(r, events.get(r.run_id) ?? [], statusOf(r, at, quietMs), quietMs) }];
439
+ return [r.run_id, { brief, nodes: mine.nodes, nodesFrom: mine.from, collidesWith, timeline: timelineOf(r, events.get(r.run_id) ?? [], statusOf(r, at, quietMs), quietMs),
440
+ thread: { number: r.target, mirror: kept && kept.comment_url && kept.gone === 0 ? { url: kept.comment_url } : null } }];
409
441
  }));
410
442
  }
411
443
 
444
+ // -------------------------------------------------------------------------
445
+ // A thread for every run (issue #104): one status comment, edited in place
446
+ // -------------------------------------------------------------------------
447
+
448
+ const mirrorOn = agents.mirror !== false;
449
+
450
+ /** Whether a run has something to say in its thread beyond its request: always over push and pull (no request comment is there), else once it has moved */
451
+ const worthMirroring = (row) => row.transport !== 'forge' || statusOf(row, now(), quietMs).status !== 'requested';
452
+
453
+ /**
454
+ * Posts or edits the status comment of a run, if its text has changed since it was last written. Never throws: a forge that refuses is logged and
455
+ * the next look tries again. One claim (`busy`) at a time per run, so a look and a request at once cannot post two comments.
456
+ * @param {import('./forge.js').Forge} forge
457
+ * @param {any} db
458
+ * @param {RunRow} row
459
+ * @returns {Promise<'' | 'written' | 'refused'>} what the forge was asked, if anything: a refusal counts toward a look's `MAX_MIRRORS` too
460
+ */
461
+ async function mirrorRun(forge, db, row) {
462
+ if (!mirrorOn || !worthMirroring(row) || typeof forge.editComment !== 'function') return '';
463
+ let claimed = false;
464
+ let asked = false;
465
+ try {
466
+ const at = now();
467
+ const body = formatRunStatus(publicRun(row, at, quietMs));
468
+ const hash = createHash('sha256').update(body).digest('hex');
469
+ let m = /** @type {{ number: number, comment_id: string | null, hash: string, busy: string | null, gone: number } | undefined} */ (db.prepare('SELECT * FROM run_mirrors WHERE run_id = ?').get(row.run_id));
470
+ if (m && (m.gone === 1 || (m.comment_id && m.hash === hash))) return '';
471
+ db.prepare('INSERT OR IGNORE INTO run_mirrors (run_id, number, at) VALUES (?, ?, ?)').run(row.run_id, row.target, iso(at));
472
+ claimed = db.prepare('UPDATE run_mirrors SET busy = ? WHERE run_id = ? AND (busy IS NULL OR busy < ?)').run(iso(at), row.run_id, iso(at - MIRROR_BUSY_MS)).changes === 1;
473
+ if (!claimed) return '';
474
+ // What the other look wrote while this one waited for the claim is read again
475
+ m = /** @type {any} */ (db.prepare('SELECT * FROM run_mirrors WHERE run_id = ?').get(row.run_id));
476
+ if (m.gone === 1 || (m.comment_id && m.hash === hash)) return '';
477
+ asked = true;
478
+ if (!m.comment_id) {
479
+ const posted = await forge.comment(m.number, body);
480
+ db.prepare('UPDATE run_mirrors SET comment_id = ?, comment_url = ?, hash = ?, at = ? WHERE run_id = ?').run(posted.id, posted.url ?? null, hash, iso(now()), row.run_id);
481
+ } else {
482
+ try {
483
+ await forge.editComment(m.comment_id, body);
484
+ db.prepare('UPDATE run_mirrors SET hash = ?, at = ? WHERE run_id = ?').run(hash, iso(now()), row.run_id);
485
+ } catch (err) {
486
+ if (!(err instanceof ForgeError) || err.code !== 'not-found') throw err;
487
+ // Someone deleted it: they meant it, so cornfield does not post another
488
+ db.prepare('UPDATE run_mirrors SET gone = 1, at = ? WHERE run_id = ?').run(iso(now()), row.run_id);
489
+ log(`the status comment of ${row.run_id} on #${m.number} is gone, so it is no longer kept`);
490
+ }
491
+ }
492
+ return 'written';
493
+ } catch (err) {
494
+ log(`the status comment of ${row.run_id} could not be written: ${words(err)}`);
495
+ return asked ? 'refused' : '';
496
+ } finally {
497
+ if (claimed) {
498
+ try { db.prepare('UPDATE run_mirrors SET busy = NULL WHERE run_id = ?').run(row.run_id); } catch { /* the database closed with the server */ }
499
+ }
500
+ }
501
+ }
502
+
412
503
  /** Writes what happened to a run, once: the key says what, so a second look at the same thing adds nothing */
413
504
  function keepEvent(db, runId, ev) {
414
505
  // A forge's answer may lack a field (a pull request with no `createdAt`): the timeline then says when cornfield saw it, and a value
@@ -618,7 +709,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
618
709
  await audit({ login: me.login, action: 'agent-request', target, request: { ...asked, target: number }, status, answer: posted ? { comment: posted.id, url: posted.url ?? null } : { transport, queued: transport === 'pull' } });
619
710
  hooks?.emit('agent.requested', { request: made, actor: me.login });
620
711
  try { onAsk?.(); } catch { /* the poll is a convenience */ }
621
- const row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(made.runId));
712
+ let row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(made.runId));
713
+ // Over push and pull no request comment is in the thread: the run's status comment is, as the maintainer who asked
714
+ await mirrorRun(forge, db, row);
715
+ row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(made.runId));
622
716
  return { run: publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)), request: made, comment: posted ? { id: posted.id, url: posted.url ?? null, number } : null };
623
717
  } catch (err) {
624
718
  if (status === null) {
@@ -712,6 +806,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
712
806
  hooks?.emit('run.state', { ...runPayload(after, me.login), state: 'stopped' });
713
807
  hooks?.emit('run.finished', { ...runPayload(after, me.login), state: 'stopped' });
714
808
  }
809
+ await mirrorRun(forge, db, after);
715
810
  return { run: publicRun(after, now(), quietMs, extrasFor(db, [after], now()).get(after.run_id)), comment: posted ? { id: posted.id, url: posted.url ?? null } : null };
716
811
  } catch (err) {
717
812
  if (!done) {
@@ -815,6 +910,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
815
910
  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
911
  const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
817
912
  hooks?.emit('run.answered', { ...runPayload(after, me.login), action: a.action });
913
+ await mirrorRun(forge, db, after);
818
914
  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
915
  } catch (err) {
820
916
  if (!done) {
@@ -1188,9 +1284,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1188
1284
  * 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
1189
1285
  * is the answer to another asked meanwhile. Never throws; resolves with a count.
1190
1286
  * @param {import('./forge.js').Forge} forge a signed-in maintainer's
1191
- * @returns {Promise<{ followed: number, reports: number, ignored: number, linked: number }>}
1287
+ * @returns {Promise<{ followed: number, reports: number, ignored: number, linked: number, mirrored?: number }>}
1192
1288
  */
1193
1289
  function follow(forge) {
1290
+ lastLook = { forge, at: now() };
1194
1291
  if (following) return following;
1195
1292
  following = followRuns(forge)
1196
1293
  .catch((err) => {
@@ -1313,7 +1410,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1313
1410
  const db = await auth.store();
1314
1411
  const at = now();
1315
1412
  const rows = followable(db, at);
1316
- const out = { followed: rows.length, reports: 0, ignored: 0, linked: 0 };
1413
+ const out = { followed: rows.length, reports: 0, ignored: 0, linked: 0, mirrored: 0 };
1317
1414
  if (!rows.length) return out;
1318
1415
  /** @type {Map<string, RunRow>} the rows as they will be written: patched in place as the forge is read */
1319
1416
  const cur = new Map(rows.map((r) => [r.run_id, { ...r }]));
@@ -1605,6 +1702,19 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1605
1702
  const row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(e.runId));
1606
1703
  hooks?.emit(e.event, { ...runPayload(row, e.actor), state: e.state, ...(e.action ? { action: e.action } : {}) });
1607
1704
  }
1705
+ // ---- the status comment of each run, edited when its text has moved (a runner's report over push or pull is first heard of here) ----------------
1706
+ if (mirrorOn) {
1707
+ let written = 0;
1708
+ let asked = 0;
1709
+ for (const id of cur.keys()) {
1710
+ if (asked >= MAX_MIRRORS) break;
1711
+ const row = /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(id));
1712
+ const did = row ? await mirrorRun(forge, db, row) : '';
1713
+ if (did) asked += 1;
1714
+ if (did === 'written') written += 1;
1715
+ }
1716
+ out.mirrored = written;
1717
+ }
1608
1718
  return out;
1609
1719
  }
1610
1720
 
@@ -1721,9 +1831,28 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
1721
1831
  if (r.state !== row.state) hooks?.emit('run.state', { ...runPayload(after, actor), state: r.state });
1722
1832
  if (newWait) hooks?.emit('run.waiting', { ...runPayload(after, actor), state: r.state });
1723
1833
  if (REPORT_FINISHED.includes(r.state)) hooks?.emit('run.finished', { ...runPayload(after, actor), state: r.state });
1834
+ if (r.state !== row.state) nudge(db, row.run_id);
1724
1835
  return { run: runnerView(after), row: after, was: row };
1725
1836
  }
1726
1837
 
1838
+ /**
1839
+ * A runner's report over push or pull that moved its run's state is taken to its thread soon, not at the next look: the status comment is
1840
+ * written after the report has been answered, with the forge of the last look if it is recent (`NUDGE_FRESH_MS`). With none, or for a report
1841
+ * that only changes the note, the next look writes it. Never throws; the runner's answer never waits for it.
1842
+ */
1843
+ function nudge(db, runId) {
1844
+ if (!mirrorOn || !lastLook || now() - lastLook.at > NUDGE_FRESH_MS || nudging.has(runId)) return;
1845
+ const { forge } = lastLook;
1846
+ nudging.add(runId);
1847
+ const later = setImmediate(async () => {
1848
+ try {
1849
+ const row = /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(runId));
1850
+ if (row) await mirrorRun(forge, db, row);
1851
+ } catch { /* the database closed with the server: the next look writes it */ } finally { nudging.delete(runId); }
1852
+ });
1853
+ if (typeof later.unref === 'function') later.unref();
1854
+ }
1855
+
1727
1856
  /** Drops what a crash left: a request that was never posted. Run once at start. */
1728
1857
  async function resume() {
1729
1858
  const db = await auth.store();
package/server/db.js CHANGED
@@ -21,6 +21,8 @@
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
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
23
  * migration 10 lets a run wait (state 'waiting') and keeps a maintainer's answer to it (answer_* on runs, 'answered' events)
24
+ * run_mirrors the one status comment cornfield keeps for a run in its thread (migration 11, issue #104): which comment, and a hash of the
25
+ * text last written to it, so a look edits it only when the run has moved
24
26
  * sessions also keep a forge refresh token, the access token's expiry and when `session.expiring` was sent (migration 5)
25
27
  *
26
28
  * The schema is a list of numbered migrations (`MIGRATIONS`); the file's `PRAGMA user_version` is the number of
@@ -335,6 +337,21 @@ export const MIGRATIONS = Object.freeze([
335
337
  ALTER TABLE run_events_new RENAME TO run_events;
336
338
  CREATE INDEX run_events_at ON run_events (run_id, at);
337
339
  `,
340
+ // 11: a thread for every run (server/agent-runs.js, issue #104): the ONE comment cornfield keeps in a run's thread, edited in place as the run moves.
341
+ // A table of its own, so no existing table is rebuilt. `busy` is a claim (a time) held while the comment is being posted or edited, so two looks at
342
+ // once cannot post two comments; `gone` says someone deleted the comment, and cornfield does not post another
343
+ `
344
+ CREATE TABLE run_mirrors (
345
+ run_id TEXT PRIMARY KEY,
346
+ number INTEGER NOT NULL, -- the issue or pull request the comment is on
347
+ comment_id TEXT, -- the forge's id of the comment, once it is posted
348
+ comment_url TEXT,
349
+ hash TEXT NOT NULL DEFAULT '', -- a hash of the text last written to it
350
+ busy TEXT,
351
+ gone INTEGER NOT NULL DEFAULT 0 CHECK (gone IN (0, 1)),
352
+ at TEXT NOT NULL
353
+ ) STRICT;
354
+ `,
338
355
  ]);
339
356
 
340
357
  /** The version a file is at: its `user_version` */
@@ -267,6 +267,10 @@ export function createForgejoForge(forge, { token = null, fetch, apiUrl, timeout
267
267
  return toComment((await client.request('POST', `repos/${repo}/issues/${n}/comments`, { body: { body }, what: `#${n} in ${forge.repo}` })).body);
268
268
  },
269
269
 
270
+ async editComment(id, body) {
271
+ return toComment((await client.request('PATCH', `repos/${repo}/issues/comments/${id}`, { body: { body }, what: `comment ${id} in ${forge.repo}` })).body);
272
+ },
273
+
270
274
  async checks(ref) {
271
275
  const statuses = await client.list(`repos/${repo}/commits/${segments(ref)}/status?limit=${PER_PAGE}`, { what: `the checks on ${ref} in ${forge.repo}`, items: (b) => b?.statuses });
272
276
  return statuses.map(toStatus);
@@ -257,6 +257,10 @@ export function createGitHubForge(forge, { token = null, fetch, apiUrl, timeoutM
257
257
  return toComment((await client.request('POST', `repos/${repo}/issues/${n}/comments`, { body: { body }, what: `#${n} in ${forge.repo}` })).body);
258
258
  },
259
259
 
260
+ async editComment(id, body) {
261
+ return toComment((await client.request('PATCH', `repos/${repo}/issues/comments/${id}`, { body: { body }, what: `comment ${id} in ${forge.repo}` })).body);
262
+ },
263
+
260
264
  async checks(ref) {
261
265
  const at = segments(ref);
262
266
  const what = `the checks on ${ref} in ${forge.repo}`;
package/server/forge.js CHANGED
@@ -20,6 +20,8 @@
20
20
  * comments(n, { since }) the comments on an issue or pull request, oldest first; `since` (an ISO time) only those
21
21
  * created or edited after it, which is how a thread is followed without reading it all again
22
22
  * comment(n, body) posts one, and answers it
23
+ * editComment(id, body) replaces the text of a comment (by the id `comment` answered) and answers it: how a run's one status comment
24
+ * in its thread is kept up to date (server/agent-runs.js, docs/agents.md#a-thread-for-every-run)
23
25
  * checks(ref) the checks on a commit (a branch, a tag or a sha)
24
26
  * rerun(check) re-runs one that can be (`check.rerunnable`)
25
27
  * merge(n, { onlyIfGreen: true }) lands an open, ready pull request whose checks are all green, at the head they ran on
@@ -94,6 +96,7 @@
94
96
  * compare(base: string, head: string): Promise<PullFile[]>, // the files a branch changes against another (optional: a forge that cannot list them throws `invalid`)
95
97
  * comments(n: number, opts?: { since?: string }): Promise<Comment[]>,
96
98
  * comment(n: number, body: string): Promise<Comment>,
99
+ * editComment(id: string, body: string): Promise<Comment>,
97
100
  * checks(ref: string): Promise<Check[]>,
98
101
  * rerun(check: Check): Promise<void>,
99
102
  * merge(n: number, opts: { onlyIfGreen: true, method?: MergeMethod, sha?: string }): Promise<{ sha: string }>,
@@ -124,7 +127,7 @@ import { ForgeError, FILE_MAX_BYTES } from './forge-http.js';
124
127
  export { ForgeError, rateLimitWords } from './forge-http.js';
125
128
 
126
129
  /** The calls of the interface (spec 0001 section 3, with `pull(n)`), and `rateLimit()`: what the last answer said is left */
127
- export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'changed', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
130
+ export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'changed', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'editComment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
128
131
  export const PERMISSIONS = Object.freeze(['admin', 'maintain', 'write', 'triage', 'read', 'none']);
129
132
  /** A check that has finished and does not stand in the way: success, or one the forge says does not count */
130
133
  export const GREEN_STATES = Object.freeze(['success', 'neutral', 'skipped']);
@@ -305,6 +308,10 @@ export function wrap(a, forge) {
305
308
  return a.comments(number(n), since === undefined ? {} : { since: new Date(since).toISOString() });
306
309
  },
307
310
  comment: async (n, body) => a.comment(number(n), text(body, 'The comment')),
311
+ editComment: async (id, body) => {
312
+ if (typeof id !== 'string' || !/^[0-9]{1,20}$/.test(id)) throw invalid('A comment is named by its id, the digits the forge gave it.');
313
+ return a.editComment(id, bounded(body, 'The comment', MAX_BODY));
314
+ },
308
315
  checks: async (ref) => a.checks(text(ref, 'The commit')),
309
316
  rerun: async (check) => {
310
317
  if (!check || typeof check.id !== 'string') throw invalid('Re-run which check?');
@@ -0,0 +1,103 @@
1
+ /**
2
+ * @module server/run-thread
3
+ *
4
+ * The text of a run's **status comment** (issue #104, docs/agents.md#a-thread-for-every-run): the one comment cornfield keeps in the
5
+ * thread a run is about and edits in place as the run moves. Pure; server/agent-runs.js decides when to post and when to edit.
6
+ *
7
+ * What the comment never is, so that mirroring can start no run and move none:
8
+ *
9
+ * - **No `cornfield-run` block.** Not a request, not a report, not a stop request, not an answer: no fence at all. A follow reads
10
+ * reports from a maintainer and the comment is written as one, so a copy of a report would be read back as a second report; a
11
+ * request block would be a hand-written request (`discover`). The runner's note is quoted line by line (`> `), as the contract's own
12
+ * comments do, after every line end the forge knows (`\r` too) is made `\n`, and its backticks and runs of tildes are broken: no fence
13
+ * opens in it, and a `/agent` line (server/triggers.js) or a heading in it is text inside a quote.
14
+ * - **Defused.** Every mention, reference and link in what a runner or a person wrote is broken (core/defuse.js), and a `[[node]]`
15
+ * mention is broken too, so the comment pings nobody, links nothing and lights nothing on the map; `<` and `[` are escaped, so no HTML,
16
+ * Markdown link or image (`[x](//elsewhere)`) is made of it either. The only live link is the run's pull request, whose number and
17
+ * address are the forge's own; the runner's `url` is never written (the dashboard shows it).
18
+ * - **Only what moves.** No time a runner sends changes the text: a runner reporting the same state every few seconds writes the same
19
+ * comment, so its hash is unchanged and nothing is edited.
20
+ * - **No secret.** It is made of the run's public form (`publicRun`), which holds none, and a report's text was checked for credentials
21
+ * when it was accepted (core/agent-contract.js); the text is cut short besides.
22
+ *
23
+ * The marker on its first line names the run, so a person reading the source of the comment knows whose it is. cornfield finds its comment
24
+ * by the id it kept (`run_mirrors`), never by the marker: the marker is not trusted as an address.
25
+ */
26
+
27
+ import { defuse, inert, quoteInert, ZW } from '../core/defuse.js';
28
+
29
+ /** The marker on the first line (an HTML comment, which the forge does not show). It does not contain the contract's tag, `cornfield-run` */
30
+ export const MIRROR_TAG = 'cornfield:run-status';
31
+
32
+ /** The most of a runner's note the comment holds */
33
+ export const NOTE_SHOWN = 1000;
34
+
35
+ const STATUS_WORDS = {
36
+ requested: 'Requested', claimed: 'Claimed', working: 'Working', waiting: 'Waiting', done: 'Done', failed: 'Failed', stopped: 'Stopped',
37
+ 'stop-requested': 'Stop requested', quiet: 'Quiet', merged: 'Merged', closed: 'Closed',
38
+ };
39
+
40
+ /** The state of a run as a word, the one the dashboard shows */
41
+ export const statusWord = (status) => STATUS_WORDS[status] ?? String(status);
42
+
43
+ /** Text for someone else's eyes: mentions, references and links broken, no link, image or HTML made of it, and made one line */
44
+ const plain = (s) => inert(defuse(String(s ?? '').replace(/\s+/g, ' ').trim()));
45
+
46
+ /** A run's note, quoted line by line and cut short */
47
+ function quote(note) {
48
+ const text = String(note ?? '').trim();
49
+ if (!text) return '';
50
+ const cut = text.length > NOTE_SHOWN ? `${text.slice(0, NOTE_SHOWN)} …` : text;
51
+ // Cut before it is made inert, so the cut never lands inside an escape (core/defuse.js)
52
+ return quoteInert(cut);
53
+ }
54
+
55
+ /** An address the forge gave, safe to put in a link; null for anything else */
56
+ const forgeUrl = (u) => (typeof u === 'string' && /^https?:\/\/[^\s<>()[\]`"']{1,500}$/.test(u) ? u : null);
57
+
58
+ /** Who made a report, in words: `runner:<label>` for a runner token, else the login */
59
+ function whoWords(by) {
60
+ if (by && typeof by === 'object') return `runner ${plain(by.label)}`;
61
+ return by ? plain(by) : '';
62
+ }
63
+
64
+ /**
65
+ * The status comment for a run.
66
+ * @param {{ runId: string, kind: string, profile: string | null, status: string, requestedBy: string, via?: string, transport?: string,
67
+ * report: { state: string, at: string, by: any, note: string | null, url: string | null } | null,
68
+ * stopRequested: { at: string, by: string } | null, answer: { action: string, by?: string } | null,
69
+ * pull: { number: number, state: string, url: string | null, trusted: boolean } | null,
70
+ * branch: string | null, checks: string | null }} run a run as `publicRun` gives it
71
+ * @returns {string}
72
+ */
73
+ export function formatRunStatus(run) {
74
+ const lines = [`<!-- ${MIRROR_TAG} ${run.runId} -->`];
75
+ const profile = run.profile ? `, profile ${plain(run.profile)}` : '';
76
+ lines.push(`**Run \`${run.runId}\`: ${statusWord(run.status)}**`);
77
+ lines.push('', `A ${plain(run.kind)} run${profile}, asked by ${plain(run.requestedBy)}${run.via === 'hand' ? ' (written by hand)' : ''}.`);
78
+
79
+ const facts = [];
80
+ const r = run.report;
81
+ // Not the report's time: a runner that says the same thing again must not edit the comment (the dashboard has the time)
82
+ if (r) facts.push(`Reported ${plain(r.state)}${whoWords(r.by) ? ` by ${whoWords(r.by)}` : ''}.`);
83
+ else facts.push('No report from a runner yet.');
84
+ if (run.stopRequested) facts.push(`${plain(run.stopRequested.by)} asked it to stop (${plain(run.stopRequested.at)}); the runner decides what that means.`);
85
+ if (run.answer) facts.push(`${plain(run.answer.by ?? 'A maintainer')} answered: ${plain(run.answer.action)}.`);
86
+ const p = run.pull;
87
+ if (p && Number.isInteger(p.number)) {
88
+ const url = forgeUrl(p.url);
89
+ const where = url ? `[#${p.number}](${url})` : `#${ZW}${p.number}`;
90
+ const checks = run.checks && run.checks !== 'none' ? `, checks ${run.checks === 'success' ? 'passing' : run.checks === 'failure' ? 'failing' : 'running'}` : '';
91
+ facts.push(`Pull request ${where} (${p.state}${p.trusted ? '' : ', not verified as the run\'s'}${checks}).`);
92
+ } else if (run.branch) facts.push(`Branch \`${plain(run.branch)}\`.`);
93
+ lines.push('', ...facts.map((f) => `- ${f}`));
94
+
95
+ const note = r ? quote(r.note) : '';
96
+ if (note) lines.push('', note);
97
+
98
+ lines.push('', '_cornfield keeps this one comment up to date as the run moves, and starts nothing from it._');
99
+ return lines.join('\n');
100
+ }
101
+
102
+ /** Whether a text is a status comment of cornfield's (by its marker): for a test or a person; cornfield itself trusts only the id it kept */
103
+ export const isRunStatus = (text) => typeof text === 'string' && text.startsWith(`<!-- ${MIRROR_TAG} `);