@popcorn245/cornfield 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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` */
@@ -191,6 +191,14 @@ export function createForgejoForge(forge, { token = null, fetch, apiUrl, timeout
191
191
  return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
192
192
  },
193
193
 
194
+ async changed({ since, limit }) {
195
+ // Without `type` the issues listing holds both kinds; it has no sort, so every page is read and sorted here, oldest update first
196
+ const q = new URLSearchParams({ state: 'open', since, limit: String(PER_PAGE) });
197
+ const all = (await client.list(`repos/${repo}/issues?${q}`, { what: `the open issues and pull requests of ${forge.repo} updated since ${since}` }))
198
+ .map((i) => ({ number: i.number, pull: Boolean(i.pull_request), labels: labelNames(i.labels), updatedAt: i.updated_at }));
199
+ return all.sort((x, y) => Date.parse(x.updatedAt) - Date.parse(y.updatedAt) || x.number - y.number).slice(0, limit);
200
+ },
201
+
194
202
  async pull(n) {
195
203
  return toPull((await client.request('GET', `repos/${repo}/pulls/${n}`, { what: pullWhat(n) })).body);
196
204
  },
@@ -190,6 +190,13 @@ export function createGitHubForge(forge, { token = null, fetch, apiUrl, timeoutM
190
190
  return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
191
191
  },
192
192
 
193
+ async changed({ since, limit }) {
194
+ // The issues listing holds the pull requests too: one call for both, oldest update first so a busy repo's earliest change is never cut off
195
+ const q = new URLSearchParams({ state: 'open', sort: 'updated', direction: 'asc', since, per_page: String(PER_PAGE) });
196
+ return (await client.list(`repos/${repo}/issues?${q}`, { what: `the open issues and pull requests of ${forge.repo} updated since ${since}`, limit }))
197
+ .map((i) => ({ number: i.number, pull: Boolean(i.pull_request), labels: labelNames(i.labels), updatedAt: i.updated_at }));
198
+ },
199
+
193
200
  async pull(n) {
194
201
  return toPull((await client.request('GET', `repos/${repo}/pulls/${n}`, { what: pullWhat(n) })).body);
195
202
  },
package/server/forge.js CHANGED
@@ -10,6 +10,8 @@
10
10
  * permission(repo, login) their permission on a repo: admin | maintain | write | triage | read | none
11
11
  * issues({ state, labels, limit }) issues, not pull requests, newest first
12
12
  * pulls({ state, limit }) pull requests, newest first
13
+ * changed({ since, limit }) the open issues and pull requests updated at or after `since`, the least recently updated first:
14
+ * `{ number, pull, labels, updatedAt }` each, one listing for both (what a look for hand-written requests reads)
13
15
  * pull(n) one pull request (its head, its state)
14
16
  * issue(n) one issue (not a pull request: that is `not-found`)
15
17
  * searchIssues(words) the issues whose text holds the words (one page; the forge's search, which can lag a moment)
@@ -70,6 +72,8 @@
70
72
  * @typedef {{ state?: 'open' | 'closed' | 'all', labels?: string[], limit?: number }} IssueQuery
71
73
  * @typedef {{ state?: 'open' | 'closed' | 'all', limit?: number }} PullQuery
72
74
  * @typedef {{ limit?: number }} RunQuery
75
+ * @typedef {{ since: string, limit?: number }} ChangedQuery
76
+ * @typedef {{ number: number, pull: boolean, labels: string[], updatedAt: string }} Changed
73
77
  * @typedef {'merge' | 'squash' | 'rebase'} MergeMethod
74
78
  * @typedef {{
75
79
  * forge: 'github' | 'forgejo', repo: string,
@@ -77,6 +81,7 @@
77
81
  * permission(repo: string, login: string): Promise<Permission>,
78
82
  * issues(query?: IssueQuery): Promise<Issue[]>,
79
83
  * pulls(query?: PullQuery): Promise<Pull[]>,
84
+ * changed(query: ChangedQuery): Promise<Changed[]>,
80
85
  * pull(n: number): Promise<Pull>,
81
86
  * issue(n: number): Promise<Issue>,
82
87
  * searchIssues(words: string): Promise<Issue[]>,
@@ -102,7 +107,8 @@
102
107
  * createReleaseDraft(input: ReleaseDraftInput): Promise<ReleaseDraft>,
103
108
  * rateLimit(): import('./forge-http.js').RateLimit | null,
104
109
  * }} Forge
105
- * @typedef {Omit<Forge, 'forge' | 'repo' | 'merge' | 'issues' | 'pulls' | 'runs'> & {
110
+ * @typedef {Omit<Forge, 'forge' | 'repo' | 'merge' | 'issues' | 'pulls' | 'runs' | 'changed'> & {
111
+ * changed(query: Required<ChangedQuery>): Promise<Changed[]>,
106
112
  * issues(query: Required<IssueQuery>): Promise<Issue[]>,
107
113
  * pulls(query: Required<PullQuery>): Promise<Pull[]>,
108
114
  * runs(query: Required<RunQuery>): Promise<Run[]>,
@@ -118,7 +124,7 @@ import { ForgeError, FILE_MAX_BYTES } from './forge-http.js';
118
124
  export { ForgeError, rateLimitWords } from './forge-http.js';
119
125
 
120
126
  /** The calls of the interface (spec 0001 section 3, with `pull(n)`), and `rateLimit()`: what the last answer said is left */
121
- export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
127
+ export const FORGE_METHODS = Object.freeze(['me', 'permission', 'issues', 'searchIssues', 'pulls', 'changed', 'pull', 'issue', 'pullFiles', 'pullCommits', 'comments', 'comment', 'checks', 'rerun', 'merge', 'runs', 'branches', 'file', 'fileBytes', 'defaultBranch', 'tags', 'tag', 'createReleaseDraft', 'createBranch', 'createFile', 'createPull', 'createIssue', 'rateLimit']);
122
128
  export const PERMISSIONS = Object.freeze(['admin', 'maintain', 'write', 'triage', 'read', 'none']);
123
129
  /** A check that has finished and does not stand in the way: success, or one the forge says does not count */
124
130
  export const GREEN_STATES = Object.freeze(['success', 'neutral', 'skipped']);
@@ -273,6 +279,13 @@ export function wrap(a, forge) {
273
279
  },
274
280
  issues: async (q) => a.issues(/** @type {Required<IssueQuery>} */ (query(q, true))),
275
281
  pulls: async (q) => a.pulls(/** @type {Required<PullQuery>} */ (query(q, false))),
282
+ changed: async (q) => {
283
+ if (!q || typeof q !== 'object' || Array.isArray(q)) throw invalid('A query is an object.');
284
+ const { since, limit = DEFAULT_LIMIT } = q;
285
+ if (typeof since !== 'string' || !ISO_TIME.test(since) || Number.isNaN(Date.parse(since))) throw invalid('since is a time like 2026-11-05T09:00:00Z.');
286
+ if (!Number.isSafeInteger(limit) || limit < 1) throw invalid('The limit is a whole number above 0.');
287
+ return a.changed({ since: new Date(since).toISOString(), limit });
288
+ },
276
289
  pull: async (n) => a.pull(number(n)),
277
290
  issue: async (n) => a.issue(number(n)),
278
291
  searchIssues: async (words) => {
package/server/hooks.js CHANGED
@@ -30,9 +30,11 @@
30
30
  * Its body is its own: `{ event, at, trigger: { event, by, ref }, by, reason, mapUrl }`
31
31
  * runner.offline on the pull transport, the last live runner token has not polled for `agents.runnerQuietAfter` (3 minutes unless set; server/runner-presence.js).
32
32
  * Once, and again only after a runner has been seen online again. Its body is its own: `{ event, at, label, lastSeen, mapUrl }`, never a token
33
- * run.claimed run.state run.stopRequested run.finished a run was claimed by its runner, changed state, was asked to stop, ended. They are
33
+ * run.claimed run.state run.waiting run.answered run.stopRequested run.finished a run was claimed by its runner, changed state, reported
34
+ * `waiting` (it asks a maintainer), was answered, was asked to stop, ended. They are
34
35
  * seen when cornfield looks (the spec poll, server/spec-poll.js), each once. Their body is their own:
35
- * `{ event, at, runId, state, pull?, issue?, actor, mapUrl }`
36
+ * `{ event, at, runId, state, pull?, issue?, action?, actor, mapUrl }`; `action` (continue, stop or reply) is only on `run.answered`,
37
+ * and a reply's words are never in it
36
38
  *
37
39
  * **Triggers listen in-process.** `subscribe(fn)` hands a function the same moments the hooks fire at, with the payload resolved, whether or not
38
40
  * any hook asks for them (server/triggers.js: `spec.approved`, `build.opened`, `thread.message`). A thread's payload then also holds the
@@ -226,11 +228,12 @@ export function createHooks({ hooks, secret, fetch: doFetch = globalThis.fetch,
226
228
  if (!checked.ok) throw new Error(checked.error);
227
229
  return JSON.stringify({ event, at: new Date(now()).toISOString(), request: checked.value, actor: p.actor ?? null, mapUrl: publicUrl || null });
228
230
  }
229
- // The events of a run (claimed, state, stopRequested, finished) say which run, in what state, and about what
231
+ // The events of a run (claimed, state, waiting, answered, stopRequested, finished) say which run, in what state, and about what
230
232
  if (event.startsWith('run.')) {
231
233
  return JSON.stringify({
232
234
  event, at: new Date(now()).toISOString(), runId: p.runId ?? null, state: p.state ?? null,
233
- ...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}), actor: p.actor ?? null, mapUrl: publicUrl || null,
235
+ ...(p.pull != null ? { pull: p.pull } : {}), ...(p.issue != null ? { issue: p.issue } : {}),
236
+ ...(event === 'run.answered' && ['continue', 'stop', 'reply'].includes(p.action) ? { action: p.action } : {}), actor: p.actor ?? null, mapUrl: publicUrl || null,
234
237
  });
235
238
  }
236
239
  // A thread's event is only which thread, which comment, who and what it links to: never the words said
package/server/server.js CHANGED
@@ -239,7 +239,9 @@ export function createCornfieldServer(config, opts = {}) {
239
239
  if (specMs !== null) specPoll?.start();
240
240
  else if (specPoll && runs) {
241
241
  // Runs asked for before a restart are followed again from the start
242
- runs.hasWork().then((work) => { if (work && !serverClosed) specPoll.start(); }).catch(() => {});
242
+ // (or, with agents.handWritten on, even with none: a request written by hand is found by the same look)
243
+ if (runs.discovers) specPoll.start();
244
+ else runs.hasWork().then((work) => { if (work && !serverClosed) specPoll.start(); }).catch(() => {});
243
245
  }
244
246
  });
245
247
  server.on('close', () => { serverClosed = true; specPoll?.close(); runnerWatch?.close(); lander?.close(); hooks?.close(); auth.close(); });
@@ -28,6 +28,10 @@
28
28
  * database alone, so an idle repo costs the forge nothing), the same tick hands the same maintainer's forge to `runs.follow`, which reads the
29
29
  * runs' comments and pull requests. A server with no `spec.ready` hook still polls for runs (`specs: false`) and then does nothing else.
30
30
  *
31
+ * **Requests written by hand** (issue #98, `agents.handWritten`, on by default) ride the same tick: before the follow, `runs.discover` lists the open issues and pull requests changed
32
+ * since its last look (one call, empty on an idle repo) and reads the comments of those that changed, so a maintainer's own `cornfield-run` block becomes a run and is followed in this very look.
33
+ * That makes the tick worth running with no run at all, so the server starts it for them too; `handWritten: false` returns to "only runs cornfield asked for".
34
+ *
31
35
  * **Never in the way.** One tick runs at a time (the next is scheduled when one ends, so a slow forge cannot pile them up).
32
36
  * A forge error is logged and never thrown; the next tick waits twice the interval until one succeeds. The timer is
33
37
  * unref'd and `close()` clears it.
@@ -73,7 +77,7 @@ export async function findMaintainerForge({ auth, repo, now = Date.now }) {
73
77
  * where: { proposals: string },
74
78
  * auth: { store: () => Promise<import('node:sqlite').DatabaseSync>, forgeForUser: (userId: string) => Promise<import('./forge.js').Forge> },
75
79
  * hooks: import('./hooks.js').Hooks | null,
76
- * runs?: { hasWork: () => Promise<boolean>, follow: (forge: import('./forge.js').Forge) => Promise<unknown> } | null,
80
+ * runs?: { hasWork: () => Promise<boolean>, follow: (forge: import('./forge.js').Forge) => Promise<unknown>, discovers?: boolean, discover?: (forge: import('./forge.js').Forge) => Promise<{ imported: number }> } | null,
77
81
  * specs?: boolean,
78
82
  * intervalMs: number,
79
83
  * now?: () => number,
@@ -125,7 +129,9 @@ export function createSpecPoll({ config, where, auth, hooks, runs = null, specs
125
129
  } catch (err) {
126
130
  log(`the runs could not be counted: ${words(err)}`);
127
131
  }
128
- if (!specs && !followRuns) return 'ok';
132
+ // Requests written by hand (agents.handWritten) are looked for even when there is no run yet: that is how the first one is found
133
+ const discovers = Boolean(runs && runs.discovers && runs.discover);
134
+ if (!specs && !followRuns && !discovers) return 'ok';
129
135
  let found;
130
136
  try {
131
137
  found = await maintainerForge();
@@ -161,6 +167,16 @@ export function createSpecPoll({ config, where, auth, hooks, runs = null, specs
161
167
  out = 'error';
162
168
  }
163
169
  }
170
+ if (discovers && !closed) {
171
+ try {
172
+ const found2 = await /** @type {any} */ (runs).discover(found.forge);
173
+ // A run just found is followed in this same look
174
+ if (found2 && found2.imported > 0) followRuns = true;
175
+ } catch (err) {
176
+ log(`the requests written by hand could not be looked for: ${words(err)}`);
177
+ out = 'error';
178
+ }
179
+ }
164
180
  if (followRuns && !closed) {
165
181
  try {
166
182
  await /** @type {NonNullable<typeof runs>} */ (runs).follow(found.forge);