cornfield 0.14.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.
- package/core/agent-contract.js +53 -19
- package/core/agent-contract.schema.json +33 -1
- package/core/config.js +17 -4
- package/explorer/forge-panel.js +57 -3
- package/explorer/index.html +2 -0
- package/explorer/runs-model.js +56 -1
- package/explorer/runs-view.js +25 -4
- package/package.json +1 -1
- package/server/agent-api.js +10 -3
- package/server/agent-runs.js +173 -22
- package/server/db.js +78 -1
- package/server/hooks.js +11 -4
- package/server/runner-presence.js +96 -0
- package/server/server.js +8 -2
package/explorer/runs-view.js
CHANGED
|
@@ -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
|
|
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": "cornfield",
|
|
3
|
-
"version": "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)",
|
package/server/agent-api.js
CHANGED
|
@@ -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
|
-
|
|
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 {
|
package/server/agent-runs.js
CHANGED
|
@@ -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.
|
|
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,8 +88,9 @@
|
|
|
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';
|
|
82
|
-
import { quietAfterMs } from '../core/config.js';
|
|
91
|
+
import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, runIdFromBranch, validateAnswer, validateReport, validateRequest, MAX_NOTE_CHARS } from '../core/agent-contract.js';
|
|
92
|
+
import { quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
|
|
93
|
+
import { runnerPresence } from './runner-presence.js';
|
|
83
94
|
import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
|
|
84
95
|
import { readTopology } from '../core/validate.js';
|
|
85
96
|
import { findPullProposal, listPullProposals, pullProposals, readPullProposal } from './proposal-pulls.js';
|
|
@@ -126,13 +137,18 @@ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
|
126
137
|
const words = (err) => (err instanceof Error ? err.message : String(err));
|
|
127
138
|
const maxIso = (a, b) => (Date.parse(b) > Date.parse(a) ? b : a);
|
|
128
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
|
+
|
|
129
143
|
/**
|
|
130
144
|
* What a run is, as of `nowMs`, from the runner's reports and what the forge shows. Pure.
|
|
131
145
|
*
|
|
132
146
|
* done / failed / stopped the runner's latest report
|
|
133
147
|
* merged / closed its (trusted) pull request ended
|
|
134
|
-
* quiet nothing happened within `quietMs
|
|
148
|
+
* quiet nothing happened within `quietMs`, unless it is waiting (below)
|
|
135
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
|
|
136
152
|
* claimed / working the runner's latest report
|
|
137
153
|
* working no report, but a (trusted) pull request or a branch carries its id: a silent runner is seen through what it pushes
|
|
138
154
|
* requested asked for, nothing seen yet
|
|
@@ -148,7 +164,7 @@ export function statusOf(row, nowMs, quietMs) {
|
|
|
148
164
|
let status;
|
|
149
165
|
if (REPORT_FINISHED.includes(row.state)) status = row.state;
|
|
150
166
|
else if (ended) status = /** @type {string} */ (row.pull_state);
|
|
151
|
-
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';
|
|
152
168
|
else if (row.stop_requested_at) status = 'stop-requested';
|
|
153
169
|
else if (row.state !== 'requested') status = row.state;
|
|
154
170
|
else status = (row.pull_trusted === 1 && row.pull) || row.branch ? 'working' : 'requested';
|
|
@@ -173,6 +189,11 @@ function subjectKeys(refs) {
|
|
|
173
189
|
|
|
174
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 ');
|
|
175
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
|
+
|
|
176
197
|
/**
|
|
177
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
|
|
178
199
|
* database's own. Text the runner wrote (a note, a link) is data for the page to escape.
|
|
@@ -193,6 +214,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
|
193
214
|
limits,
|
|
194
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,
|
|
195
216
|
stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
|
|
217
|
+
answer: answerOf(row),
|
|
196
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,
|
|
197
219
|
branch: row.branch, headSha: row.head_sha, checks: row.checks, lastActivity: row.last_activity,
|
|
198
220
|
...extra,
|
|
@@ -269,6 +291,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
269
291
|
const runnerSet = new Set((Array.isArray(agents.runners) ? agents.runners : []).map(lower));
|
|
270
292
|
const authorSet = new Set((Array.isArray(agents.authors) ? agents.authors : []).map(lower));
|
|
271
293
|
const quietMs = quietAfterMs(config);
|
|
294
|
+
const runnerQuietMs = runnerQuietAfterMs(config);
|
|
272
295
|
const refuseCollisions = agents.refuseCollisions === true;
|
|
273
296
|
/** How requests travel from now on (`agents.transport`); a run keeps the transport it was asked for with */
|
|
274
297
|
const transport = /** @type {'forge' | 'push' | 'pull'} */ (agents.transport ?? 'forge');
|
|
@@ -669,6 +692,109 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
669
692
|
}
|
|
670
693
|
}
|
|
671
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
|
+
|
|
672
798
|
/** The body of a run hook event: which run, in what state, about what, caused by whom */
|
|
673
799
|
function runPayload(row, actor) {
|
|
674
800
|
return { runId: row.run_id, state: statusOf(row, now(), quietMs).status, pull: row.pull ?? undefined, issue: row.issue ?? row.thread ?? undefined, actor };
|
|
@@ -695,7 +821,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
695
821
|
return {
|
|
696
822
|
runs: rows.map((r) => publicRun(r, at, quietMs, extras.get(r.run_id))), open: openRows(db, at).length, maxOpen: cap, profiles, limits: agents.limits || {}, quietAfter: agents.quietAfter, runners: [...runnerSet].length,
|
|
697
823
|
triggerSkipped: skipped.length ? { count: skipped.length, last: skipped[0].at, reasons } : null,
|
|
698
|
-
refuseCollisions,
|
|
824
|
+
refuseCollisions, runnerPresence: { transport, ...runnerPresence(db, at, runnerQuietMs) },
|
|
699
825
|
};
|
|
700
826
|
}
|
|
701
827
|
|
|
@@ -706,10 +832,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
706
832
|
return row ? publicRun(row, now(), quietMs, extrasFor(db, [row], now()).get(row.run_id)) : null;
|
|
707
833
|
}
|
|
708
834
|
|
|
709
|
-
/** 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 */
|
|
710
836
|
function followable(db, at) {
|
|
711
837
|
const window = Math.max(2 * quietMs, FOLLOW_FLOOR_MS);
|
|
712
|
-
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 ?`)
|
|
713
839
|
.all(repo, iso(at - window), MAX_FOLLOWED));
|
|
714
840
|
}
|
|
715
841
|
|
|
@@ -865,7 +991,9 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
865
991
|
|
|
866
992
|
const seen = (runId, key) => db.prepare('SELECT 1 FROM run_seen WHERE run_id = ? AND key = ?').get(runId, key) !== undefined;
|
|
867
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); };
|
|
868
|
-
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();
|
|
869
997
|
|
|
870
998
|
// Who counts: runners by the config, maintainers by what the forge says now (asked once per login per look)
|
|
871
999
|
const maintainerOf = new Map();
|
|
@@ -984,8 +1112,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
984
1112
|
const trust = (login, block) => {
|
|
985
1113
|
const who = standing.get(lower(login));
|
|
986
1114
|
if (!who) return false;
|
|
987
|
-
// A report: a runner (agents.runners) or a maintainer. A stop request: a maintainer. A request is not ours to follow
|
|
988
|
-
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;
|
|
989
1117
|
};
|
|
990
1118
|
const found = runBlocksOf(comments, { trust });
|
|
991
1119
|
const counts = new Map();
|
|
@@ -1013,7 +1141,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1013
1141
|
if (!row || !ids.has(b.runId) || b.type === 'request') continue;
|
|
1014
1142
|
const key = keyOf(b.comment.id, b.runId, b.type);
|
|
1015
1143
|
const reason = b.why === 'edited' ? 'edited after it was posted, so it is not believed'
|
|
1016
|
-
: 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`;
|
|
1017
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;
|
|
1018
1146
|
}
|
|
1019
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
|
|
@@ -1032,12 +1160,29 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1032
1160
|
state: r.state, reported_at: when, reported_by: login, note: r.note ?? null, url: r.url ?? null,
|
|
1033
1161
|
tokens: r.tokens ?? row.tokens, cost: r.cost ?? row.cost,
|
|
1034
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
|
+
}
|
|
1035
1168
|
touch(row, when);
|
|
1036
1169
|
out.reports += 1;
|
|
1037
1170
|
cause.set(row.run_id, key);
|
|
1038
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 });
|
|
1039
1172
|
if (r.state === 'claimed') queue(row, 'run.claimed', 'ev:claimed', login, 'claimed');
|
|
1040
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');
|
|
1041
1186
|
} else {
|
|
1042
1187
|
if (!row.stop_requested_at) Object.assign(row, { stop_requested_at: when, stop_requested_by: login });
|
|
1043
1188
|
touch(row, when);
|
|
@@ -1104,6 +1249,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1104
1249
|
last_activity = MAX(last_activity, ?) WHERE run_id = ?`)
|
|
1105
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,
|
|
1106
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);
|
|
1107
1253
|
}
|
|
1108
1254
|
for (const e of events) if (mark.run(e.runId, e.key, iso(at)).changes === 1) fresh.push(e);
|
|
1109
1255
|
for (const ev of happened) keepEvent(db, ev.runId, ev);
|
|
@@ -1117,7 +1263,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1117
1263
|
}
|
|
1118
1264
|
for (const e of fresh) {
|
|
1119
1265
|
const row = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(e.runId));
|
|
1120
|
-
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 } : {}) });
|
|
1121
1267
|
}
|
|
1122
1268
|
return out;
|
|
1123
1269
|
}
|
|
@@ -1132,10 +1278,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1132
1278
|
/** What a runner's act writes into the timeline: the runner, with the maintainer who minted the token kept in `mintedBy` */
|
|
1133
1279
|
const runnerText = (token) => byToText(runnerBy(token));
|
|
1134
1280
|
|
|
1135
|
-
/** A run for a runner: the state it is in as cornfield derives it,
|
|
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 */
|
|
1136
1282
|
function runnerView(row) {
|
|
1137
1283
|
const st = statusOf(row, now(), quietMs);
|
|
1138
|
-
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 };
|
|
1139
1285
|
}
|
|
1140
1286
|
|
|
1141
1287
|
/** The run a runner token names, or a `Refused`: 404 when there is none, 403 when the token may not touch it */
|
|
@@ -1195,7 +1341,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1195
1341
|
return { request: checked.ok ? checked.value : null, run: runnerView(row), row };
|
|
1196
1342
|
}
|
|
1197
1343
|
|
|
1198
|
-
/** 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 */
|
|
1199
1345
|
async function runnerGet(token, runId) {
|
|
1200
1346
|
const db = await auth.store();
|
|
1201
1347
|
return runnerView(runnerRun(db, token, runId));
|
|
@@ -1218,10 +1364,14 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1218
1364
|
const was = statusOf(row, at, quietMs);
|
|
1219
1365
|
if (was.finished) throw new Refused(409, `Run ${row.run_id} is ${was.status}; it takes no more reports.`, 'conflict');
|
|
1220
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';
|
|
1221
1369
|
const changed = db.prepare(`UPDATE runs SET state = ?, reported_at = ?, reported_by = ?, note = ?, url = ?, tokens = COALESCE(?, tokens), cost = COALESCE(?, cost),
|
|
1222
|
-
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
|
|
1223
1373
|
WHERE run_id = ? AND (claimed_by IS NULL OR claimed_by = ?) AND state NOT IN ('done', 'failed', 'stopped')`)
|
|
1224
|
-
.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;
|
|
1225
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');
|
|
1226
1376
|
const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
|
|
1227
1377
|
// A report of `claimed` on a run the claim route already claimed is a report, not a second "Claimed" line
|
|
@@ -1229,6 +1379,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1229
1379
|
const actor = runnerActor(token);
|
|
1230
1380
|
if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
|
|
1231
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 });
|
|
1232
1383
|
if (REPORT_FINISHED.includes(r.state)) hooks?.emit('run.finished', { ...runPayload(after, actor), state: r.state });
|
|
1233
1384
|
return { run: runnerView(after), row: after, was: row };
|
|
1234
1385
|
}
|
|
@@ -1255,7 +1406,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1255
1406
|
return hit ? hit.run_id : null;
|
|
1256
1407
|
}
|
|
1257
1408
|
|
|
1258
|
-
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 };
|
|
1259
1410
|
}
|
|
1260
1411
|
|
|
1261
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` */
|