cornfield 0.53.0 → 0.54.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/mentions.js CHANGED
@@ -237,3 +237,26 @@ export function threadOfPull(body) {
237
237
  const m = /(?:^|[\s(])(?:thread\s*:|(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)(?:\s*:)?)\s+#([1-9]\d{0,8})\b/i.exec(prose);
238
238
  return m ? Number(m[1]) : null;
239
239
  }
240
+
241
+ /**
242
+ * Every issue a pull request's text says it closes, as GitHub and Forgejo read it: `Closes #n`, and the other keywords both forges
243
+ * honour (close, closes, closed, fix, fixes, fixed, resolve, resolves, resolved; any case; an optional colon), each number once, in
244
+ * the order written. Not in code (a fenced block or an inline span) and not in an HTML comment (a pull request template's
245
+ * `<!-- Fixes #123 -->`), which neither forge reads. An issue in another repo (`owner/name#n`) is not this repo's; with `repo`
246
+ * ("owner/name"), the same repo written out in full is. (`threadOfPull` is the first of these, or a `Thread: #n`; the work graph
247
+ * draws every one, server/work-graph.js.)
248
+ * @param {string} body
249
+ * @param {string | null} [repo] this repo, "owner/name"
250
+ * @returns {number[]}
251
+ */
252
+ export function closesOf(body, repo = null) {
253
+ const prose = scan(String(body ?? '')).prose.replace(/<!--[\s\S]*?(?:-->|$)/g, (c) => c.replace(/[^\n]/g, ' '));
254
+ const self = typeof repo === 'string' ? repo.toLowerCase() : null;
255
+ const out = [];
256
+ for (const m of prose.matchAll(/(?:^|[\s(])(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)(?:\s*:)?\s+([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)?#([1-9]\d{0,8})\b/gi)) {
257
+ if (m[1] && m[1].toLowerCase() !== self) continue;
258
+ const n = Number(m[2]);
259
+ if (!out.includes(n)) out.push(n);
260
+ }
261
+ return out;
262
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.53.0",
3
+ "version": "0.54.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)",
@@ -74,7 +74,7 @@ const isDraft = (p) => p.draft === true || /^\s*(\[WIP\]|WIP:|Draft:)/i.test(p.t
74
74
  const toPull = (p) => ({
75
75
  number: p.number, title: p.title, body: p.body ?? '', state: p.merged || p.merged_at ? 'merged' : p.state === 'closed' ? 'closed' : 'open', draft: isDraft(p),
76
76
  author: author(p.user), labels: labelNames(p.labels), head: { ref: p.head?.ref ?? '', sha: p.head?.sha ?? '' }, base: { ref: p.base?.ref ?? '' },
77
- url: p.html_url, createdAt: p.created_at, updatedAt: p.updated_at, mergedAt: p.merged_at ?? null,
77
+ url: p.html_url, createdAt: p.created_at, updatedAt: p.updated_at, mergedAt: p.merged_at ?? null, mergeSha: p.merged_at || p.merged ? p.merge_commit_sha ?? null : null, closedAt: p.closed_at ?? null,
78
78
  });
79
79
 
80
80
  const FILE_STATUS = { added: 'added', copied: 'added', deleted: 'removed', removed: 'removed', renamed: 'renamed', modified: 'modified', changed: 'modified', unchanged: 'modified' };
@@ -172,9 +172,10 @@ export function createForgejoForge(forge, { token = null, fetch, apiUrl, timeout
172
172
  return LEVELS[body.permission] || 'none';
173
173
  },
174
174
 
175
- async issues({ state, labels, limit }) {
175
+ async issues({ state, labels, limit, since }) {
176
176
  const q = new URLSearchParams({ state, type: 'issues', limit: String(PER_PAGE) });
177
177
  if (labels.length) q.set('labels', labels.join(','));
178
+ if (since) q.set('since', since);
178
179
  const all = await client.list(`repos/${repo}/issues?${q}`, { what: `the issues of ${forge.repo}`, limit, items: (b) => (Array.isArray(b) ? b.filter((i) => !i.pull_request) : b) });
179
180
  return all.map(toIssue);
180
181
  },
@@ -186,8 +187,9 @@ export function createForgejoForge(forge, { token = null, fetch, apiUrl, timeout
186
187
  return (Array.isArray(body) ? body : []).filter((i) => !i.pull_request).map(toIssue);
187
188
  },
188
189
 
189
- async pulls({ state, limit }) {
190
- const q = new URLSearchParams({ state, limit: String(PER_PAGE) });
190
+ async pulls({ state, limit, sort }) {
191
+ // Without `sort` the forge's own order, newest first; `recentupdate` is the most recently updated first
192
+ const q = new URLSearchParams({ state, ...(sort === 'updated' ? { sort: 'recentupdate' } : {}), limit: String(PER_PAGE) });
191
193
  return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
192
194
  },
193
195
 
@@ -63,7 +63,7 @@ const toIssue = (i) => ({
63
63
  const toPull = (p) => ({
64
64
  number: p.number, title: p.title, body: p.body ?? '', state: p.merged_at ? 'merged' : p.state === 'closed' ? 'closed' : 'open', draft: Boolean(p.draft),
65
65
  author: author(p.user), labels: labelNames(p.labels), head: { ref: p.head?.ref ?? '', sha: p.head?.sha ?? '' }, base: { ref: p.base?.ref ?? '' },
66
- url: p.html_url, createdAt: p.created_at, updatedAt: p.updated_at, mergedAt: p.merged_at ?? null,
66
+ url: p.html_url, createdAt: p.created_at, updatedAt: p.updated_at, mergedAt: p.merged_at ?? null, mergeSha: p.merged_at || p.merged ? p.merge_commit_sha ?? null : null, closedAt: p.closed_at ?? null,
67
67
  });
68
68
 
69
69
  /** @returns {import('./forge.js').PullCommit} */
@@ -171,8 +171,9 @@ export function createGitHubForge(forge, { token = null, fetch, apiUrl, timeoutM
171
171
  return LEGACY[body.permission] || 'none';
172
172
  },
173
173
 
174
- async issues({ state, labels, limit }) {
174
+ async issues({ state, labels, limit, since }) {
175
175
  const q = new URLSearchParams({ state, sort: 'created', direction: 'desc', per_page: String(PER_PAGE) });
176
+ if (since) q.set('since', since);
176
177
  if (labels.length) q.set('labels', labels.join(','));
177
178
  const all = await client.list(`repos/${repo}/issues?${q}`, { what: `the issues of ${forge.repo}`, limit, items: (b) => (Array.isArray(b) ? b.filter((i) => !i.pull_request) : b) });
178
179
  return all.map(toIssue);
@@ -185,8 +186,8 @@ export function createGitHubForge(forge, { token = null, fetch, apiUrl, timeoutM
185
186
  return (Array.isArray(body?.items) ? body.items : []).filter((i) => !i.pull_request).map(toIssue);
186
187
  },
187
188
 
188
- async pulls({ state, limit }) {
189
- const q = new URLSearchParams({ state, sort: 'created', direction: 'desc', per_page: String(PER_PAGE) });
189
+ async pulls({ state, limit, sort = 'created' }) {
190
+ const q = new URLSearchParams({ state, sort, direction: 'desc', per_page: String(PER_PAGE) });
190
191
  return (await client.list(`repos/${repo}/pulls?${q}`, { what: `the pull requests of ${forge.repo}`, limit })).map(toPull);
191
192
  },
192
193
 
@@ -25,6 +25,8 @@
25
25
  * GET /api/forge/threads/<n> one thread's messages, as written, to read; replying is on the forge
26
26
  * POST /api/forge/threads { title, body }: a new idea, an issue with the label, as the maintainer (server/forge-actions.js `serveIdea`)
27
27
  * GET /api/forge/work what the agents view groups: pull requests and issues (any state), branches, open spec PRs, and the config's `agents` rules
28
+ * GET /api/forge/work-graph the map of work (spec 0012): issues, PRs, proposals, threads, runs and deploys as nodes, their links to each other
29
+ * and to the map's code as edges, and `problems` for what could not be read (server/work-graph.js; not open to an embedding origin)
28
30
  * GET /api/forge/deploys?limit=100 the latest workflow runs that are deploys, each with what the
29
31
  * config says it restarted (server/deploys.js, docs/deploys.md)
30
32
  * GET /api/forge/release-notes?since=<tag> the merged pull requests since a tag (the latest version tag unless
@@ -60,6 +62,7 @@ import { deploysOf } from './deploys.js';
60
62
  import { readBody, sameOrigin } from './proposals.js';
61
63
  import { releaseNotes } from './release-notes.js';
62
64
  import { inside, readMap, readPlain } from './files.js';
65
+ import { workGraph } from './work-graph.js';
63
66
 
64
67
  /** How long a kept answer is served without asking the forge again */
65
68
  export const FRESH_MS = 60_000;
@@ -122,7 +125,7 @@ function notesInput(config, since) {
122
125
  * The reads: the request's route, the forge call that answers it, and the key it is kept under.
123
126
  * @returns {{ key: string, load: (forge: import('./forge.js').Forge) => Promise<object> } | null}
124
127
  */
125
- function routeOf(reqPath, url, config, where, hooks = null) {
128
+ function routeOf(reqPath, url, config, where, hooks = null, extra = {}) {
126
129
  if (reqPath === '/api/forge/release-notes') {
127
130
  const since = sinceOf(url.searchParams.get('since'));
128
131
  return { key: `release-notes?since=${since ?? ''}&label=${config.releaseNotes?.breakingLabel ?? ''}`, load: (forge) => releaseNotes(forge, notesInput(config, since)) };
@@ -164,6 +167,18 @@ function routeOf(reqPath, url, config, where, hooks = null) {
164
167
  const n = Number(reqPath.split('/').pop());
165
168
  return { key: `threads/${n}&label=${label}`, load: async (forge) => ({ thread: await readThread(forge, config, where || config, n) }) };
166
169
  }
170
+ if (reqPath === '/api/forge/work-graph') {
171
+ // The config is in the key (what is a deploy, whether threads are on), so an answer kept before it changed is never served for the new one
172
+ const mapping = createHash('sha256').update(JSON.stringify([config.deploys || null, config.threads ?? null])).digest('hex').slice(0, 12);
173
+ return {
174
+ key: `work-graph?config=${mapping}`,
175
+ load: async (forge) => {
176
+ let map = null;
177
+ try { map = readMap(config); } catch { map = null; }
178
+ return workGraph(forge, config, map, { where: where || config, runs: extra.runs ?? null, now: extra.now });
179
+ },
180
+ };
181
+ }
167
182
  if (reqPath === '/api/forge/work') {
168
183
  return {
169
184
  key: 'work',
@@ -258,7 +273,7 @@ async function servePlan(req, res, act, url, ctx) {
258
273
  * @param {import('node:http').ServerResponse} res
259
274
  * @param {string} reqPath the decoded path
260
275
  * @param {URL} url
261
- * @param {{ config: object, where?: { proposals: string }, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, session: { userId: string, login: string } | null, publicHost?: string | null, publicOrigin?: string | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function }, now?: () => number }} ctx
276
+ * @param {{ config: object, where?: { proposals: string }, runs?: import('./agent-runs.js').Runs | null, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, session: { userId: string, login: string } | null, publicHost?: string | null, publicOrigin?: string | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function }, now?: () => number }} ctx
262
277
  * `session` is the signed-in maintainer's (null without sign-in)
263
278
  * @returns {Promise<boolean>}
264
279
  */
@@ -319,7 +334,7 @@ export async function serveForge(req, res, reqPath, url, ctx) {
319
334
  return true;
320
335
  }
321
336
  try {
322
- const route = routeOf(reqPath, url, config, ctx.where, ctx.hooks);
337
+ const route = routeOf(reqPath, url, config, ctx.where, ctx.hooks, { runs: ctx.runs, now });
323
338
  if (!route) {
324
339
  send(req, res, 404, { ok: false, error: `${reqPath} is not a forge route.`, code: 'not-found' });
325
340
  return true;
package/server/forge.js CHANGED
@@ -57,7 +57,7 @@
57
57
  * @typedef {{ id: string, login: string, name: string | null, url: string | null, avatarUrl: string | null }} User
58
58
  * @typedef {{ login: string, url: string | null, bot?: true }} Author
59
59
  * @typedef {{ number: number, title: string, state: 'open' | 'closed', author: Author | null, labels: string[], body: string, comments: number, url: string, createdAt: string, updatedAt: string, closedAt: string | null }} Issue
60
- * @typedef {{ number: number, title: string, body: string, state: 'open' | 'closed' | 'merged', draft: boolean, author: Author | null, labels: string[], head: { ref: string, sha: string }, base: { ref: string }, url: string, createdAt: string, updatedAt: string, mergedAt: string | null }} Pull
60
+ * @typedef {{ number: number, title: string, body: string, state: 'open' | 'closed' | 'merged', draft: boolean, author: Author | null, labels: string[], head: { ref: string, sha: string }, base: { ref: string }, url: string, createdAt: string, updatedAt: string, mergedAt: string | null, mergeSha: string | null, closedAt: string | null }} Pull
61
61
  * @typedef {{ path: string, status: 'added' | 'modified' | 'removed' | 'renamed', previousPath: string | null, additions: number, deletions: number }} PullFile
62
62
  * @typedef {{ id: string, author: Author | null, body: string, url: string, createdAt: string, updatedAt: string }} Comment
63
63
  * @typedef {{ sha: string, message: string, date: string | null }} PullCommit `date`: when it was committed (the committer's date, else the author's), or null when the forge gave none
@@ -71,8 +71,8 @@
71
71
  * @typedef {{ name: string, sha: string, date: string }} TagInfo
72
72
  * @typedef {{ tag: string, name: string, body: string }} ReleaseDraftInput
73
73
  * @typedef {{ id: string, url: string, draft: true }} ReleaseDraft
74
- * @typedef {{ state?: 'open' | 'closed' | 'all', labels?: string[], limit?: number }} IssueQuery
75
- * @typedef {{ state?: 'open' | 'closed' | 'all', limit?: number }} PullQuery
74
+ * @typedef {{ state?: 'open' | 'closed' | 'all', labels?: string[], limit?: number, since?: string }} IssueQuery `since`: only the issues updated at or after it
75
+ * @typedef {{ state?: 'open' | 'closed' | 'all', limit?: number, sort?: 'created' | 'updated' }} PullQuery `sort`: newest first by when it was opened (the default) or last updated
76
76
  * @typedef {{ limit?: number }} RunQuery
77
77
  * @typedef {{ since: string, limit?: number }} ChangedQuery
78
78
  * @typedef {{ number: number, pull: boolean, labels: string[], updatedAt: string }} Changed
@@ -240,15 +240,20 @@ function inRepo(ref, path) {
240
240
  if (path.startsWith('/') || path.split('/').some((p) => p === '..' || p === '.' || p === '')) throw invalid(`${JSON.stringify(path)} is not a path inside the repo.`);
241
241
  }
242
242
 
243
- /** A listing's query with the defaults: open, at most `DEFAULT_LIMIT`, any label */
243
+ /** A listing's query with the defaults: open, at most `DEFAULT_LIMIT`, any label; an issue listing's `since` and a pull request listing's `sort` only when asked */
244
244
  function query(q, withLabels) {
245
245
  if (q !== undefined && (q === null || typeof q !== 'object' || Array.isArray(q))) throw invalid('A query is an object.');
246
- const { state = 'open', limit = DEFAULT_LIMIT, labels = [] } = q || {};
246
+ const { state = 'open', limit = DEFAULT_LIMIT, labels = [], since, sort } = q || {};
247
247
  if (!STATES.includes(state)) throw invalid(`The state is one of ${STATES.join(', ')}.`);
248
248
  if (!Number.isSafeInteger(limit) || limit < 1) throw invalid('The limit is a whole number above 0.');
249
- if (!withLabels) return { state, limit };
249
+ if (!withLabels) {
250
+ if (sort !== undefined && sort !== 'created' && sort !== 'updated') throw invalid('The sort is created or updated.');
251
+ return sort === 'updated' ? { state, limit, sort } : { state, limit };
252
+ }
250
253
  if (!Array.isArray(labels) || labels.some((l) => typeof l !== 'string' || l === '' || l.includes(','))) throw invalid('The labels are a list of names.');
251
- return { state, limit, labels };
254
+ if (since === undefined) return { state, limit, labels };
255
+ 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.');
256
+ return { state, limit, labels, since: new Date(since).toISOString() };
252
257
  }
253
258
 
254
259
  /**
@@ -41,15 +41,23 @@ export const CACHE_MAX = 500;
41
41
  /** @type {WeakMap<object, Map<string, unknown>>} */
42
42
  const caches = new WeakMap();
43
43
 
44
- /** What was read at `key` (a head sha is in every key), or `read()`'s answer, kept for next time */
44
+ /**
45
+ * What was read at `key` (a head sha is in every key), or `read()`'s answer, kept for next time. The promise is what is kept, so
46
+ * listings asked side by side (the Specs list and the work graph as a page opens) ask the forge once; a read that fails is forgotten.
47
+ */
45
48
  async function atSha(where, key, read) {
46
49
  let cache = caches.get(where);
47
50
  if (!cache) caches.set(where, (cache = new Map()));
48
51
  if (cache.has(key)) return cache.get(key);
49
- const value = await read();
52
+ const value = Promise.resolve().then(read);
50
53
  cache.set(key, value);
51
54
  if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);
52
- return value;
55
+ try {
56
+ return await value;
57
+ } catch (err) {
58
+ if (cache.get(key) === value) cache.delete(key);
59
+ throw err;
60
+ }
53
61
  }
54
62
 
55
63
  /** The files of a pull request at its head, from the cache when that head was read before */
package/server/server.js CHANGED
@@ -490,7 +490,7 @@ export function createCornfieldServer(config, opts = {}) {
490
490
  // Before the proxies: a repo's `/api/` proxy must not swallow the panel's own routes
491
491
  if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost, publicOrigin })) return;
492
492
  if (await serveRunRoutes(req, res, reqPath, { config, auth, runs, session: gate.session, now: opts.now, publicHost, publicOrigin })) return;
493
- if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost, publicOrigin, embedOrigins: embed.origins })) return;
493
+ if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, runs, lander, now: opts.now, publicHost, publicOrigin, embedOrigins: embed.origins })) return;
494
494
  for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
495
495
  const session = gate.session;
496
496
  const forgeFor = session ? () => auth.forgeFor(session) : null;
@@ -0,0 +1,506 @@
1
+ /**
2
+ * @module server/work-graph
3
+ *
4
+ * The map of work in one answer (spec 0012 D2, D3 and D7): the pieces of work of six kinds as nodes, how they link to each other and to
5
+ * the code they touch as edges, and a line for everything that could not be read. `GET /api/forge/work-graph` (server/forge-routes.js)
6
+ * answers `{ ok, nodes, edges, problems }` from `workGraph`.
7
+ *
8
+ * Kind Id Stage Comes from
9
+ * thread thread:<n> talk an idea (an issue with the threads label) or a spec PR's conversation (server/threads.js's rules)
10
+ * issue issue:<n> talk an issue that is not an idea
11
+ * proposal proposal:<slug> decide a proposal of an open or recent spec PR (`number` says which), else one in the checkout or a worktree;
12
+ * another spec PR holding the same slug is `proposal:<slug>@<n>` (each counts, as the Specs list's rows do)
13
+ * run run:<runId> build an agent run (server/agent-runs.js)
14
+ * pull pull:<n> build a pull request that is not a spec PR
15
+ * deploy deploy:<id> ship a workflow run the config says is a deploy (server/deploys.js)
16
+ *
17
+ * Every node: `{ id, kind, stage, title, state, open, waiting, url, updated, ...}` and its number (`number`), slug (`slug`), run id (`runId`) or
18
+ * deploy id (`deployId`). `waiting` is spec 0010 D1's rule, worked out by the same functions the page's number uses (explorer/waiting-model.js
19
+ * `specStateOf`, explorer/runs-model.js `canAnswer`): a spec to decide, a run waiting on an answer; nothing else asks the maintainer a question.
20
+ * The code a proposal adds, and the map does not hold yet, comes as `{ id, kind: 'code', planned: true, label, type }`; the code that exists is
21
+ * on the map the page already has, and is only named by edges.
22
+ *
23
+ * Rel From -> to Comes from
24
+ * became thread -> proposal the spec PR's text names the thread (`Thread: #n`, `Closes #n`: core/mentions.js `threadOfPull`, `closesOf`)
25
+ * discusses thread -> proposal a spec PR's conversation, by its slug; an idea's `cornfield-thread` block that names a slug
26
+ * agent-on issue or thread or proposal -> run the run's refs (`issue`, `thread`, `proposal`)
27
+ * opened run -> pull or proposal the pull request the run opened (`run.pull`); a spec PR is its proposals
28
+ * closes pull or proposal -> issue or thread `Closes #n` in the text (core/mentions.js `closesOf`); never a spec PR's conversation (a forge closes only issues)
29
+ * implements pull -> proposal the pull request closes the build issue of the proposal (the marker pipeline.js `buildMarker` writes), or a code run on the proposal opened it
30
+ * shipped pull or proposal -> deploy the deploy ran at the pull request's merge commit (its head, when the forge gave none)
31
+ * changes pull, proposal, run -> code a PR's files (explorer/forge-panel-model.js `litFor`, renames included), a proposal's changed and removed nodes, a run's nodes (`litOfRun`)
32
+ * adds proposal -> code the nodes a proposal adds: planned ones, until the map holds them
33
+ * mentions thread, issue -> code the `[[mentions]]` of its text (explorer/forge-panel-model.js `mentionsOf`, `messageNodes`; core/mentions.js)
34
+ * restarts deploy -> code what the config says the deploy restarted (explorer/forge-panel-model.js `litForDeploy`)
35
+ *
36
+ * Never an edge to an id that is neither a node of the answer, nor a node of the map, nor a planned one. A map node whose id looks like a work
37
+ * node's (`pull:3`) is left out, and said in `problems`, so an id names one thing.
38
+ *
39
+ * **Which work.** Open, and closed, merged or finished within `WINDOW_DAYS` (`inWindow`). The closed lists are asked for what moved in the window
40
+ * (pull requests most recently updated first, issues updated since its start), so an old issue closed today is in it; a list that comes back
41
+ * full, or deploys older than the workflow runs read, are said in `problems`.
42
+ *
43
+ * **What it costs.** A pull request's files are read once for a head commit and kept for good (server/proposal-pulls.js `filesAt`, which the
44
+ * spec listing keeps by too), and so is a proposal's file at that head; a warm answer asks the forge for the lists only (open pull requests, recent
45
+ * closed ones, issues, runs), a thread's comments again only when its last activity moved, and a spec PR's review state as the listing does (kept
46
+ * five minutes per head). Every open pull request's files are read (kept per head and shared with the Specs list, which reads the same ones), so
47
+ * every open spec PR is drawn and counted; at most `MAX_OPEN_PULLS` other open pull requests are drawn, and `MAX_PULL_FILES` files of each; what
48
+ * is left out is named in `problems`, as is every source that could not be read: the rest of the graph is still answered.
49
+ *
50
+ * @typedef {{ source: string, text: string }} Problem
51
+ */
52
+
53
+ import fs from 'node:fs';
54
+ import { DEFAULT_LIMIT, ForgeError } from './forge.js';
55
+ import { filesAt, forgeWords, pullProposals, readPullProposal, reviewStates } from './proposal-pulls.js';
56
+ import { listProposalFiles } from './files.js';
57
+ import { deploysOf } from './deploys.js';
58
+ import { ideaLabel } from '../core/config.js';
59
+ import { closesOf, linksOf, threadOfPull } from '../core/mentions.js';
60
+ import { litFor, litForDeploy, mentionsOf, messageNodes } from '../explorer/forge-panel-model.js';
61
+ import { canAnswer, litOfRun, runName } from '../explorer/runs-model.js';
62
+ import { specStateOf } from '../explorer/waiting-model.js';
63
+
64
+ /** Work older than this is not drawn once it is over (spec 0012 D2); the Work list reaches further back */
65
+ export const WINDOW_DAYS = 14;
66
+ /** The most open pull requests drawn (spec PRs are proposals, and all drawn), and the most recently closed ones; the rest is named in `problems` */
67
+ export const MAX_OPEN_PULLS = 50;
68
+ export const MAX_RECENT_PULLS = 50;
69
+ /** The most files of one pull request drawn as edges */
70
+ export const MAX_PULL_FILES = 300;
71
+ /** What each source is asked for (the open pull requests: all of them, as the Specs list asks) */
72
+ export const LIST_PULLS = 100;
73
+ export const LIST_ISSUES = 200;
74
+ export const LIST_RECENT_ISSUES = 100;
75
+ export const LIST_RUNS = 100;
76
+ export const MAX_THREADS = 100;
77
+ export const MAX_LOCAL_PROPOSALS = 100;
78
+ /** The longest text of a pull request or issue that is read for `Closes #n` and `[[mentions]]` */
79
+ export const BODY_READ = 20_000;
80
+ /** How many pull requests have their files, or threads their comments, asked at once */
81
+ const PARALLEL = 6;
82
+ const DAY_MS = 86_400_000;
83
+ /** How many numbers a `problems` line names */
84
+ const NAMED = 12;
85
+
86
+ export const KINDS = Object.freeze(['thread', 'issue', 'proposal', 'run', 'pull', 'deploy']);
87
+ export const STAGES = Object.freeze(['talk', 'decide', 'build', 'ship']);
88
+ export const RELS = Object.freeze(['became', 'discusses', 'agent-on', 'opened', 'closes', 'implements', 'shipped', 'changes', 'adds', 'mentions', 'restarts']);
89
+
90
+ const STAGE_OF = Object.freeze({ thread: 'talk', issue: 'talk', proposal: 'decide', run: 'build', pull: 'build', deploy: 'ship' });
91
+
92
+ // ---------------------------------------------------------------------------
93
+ // The pure half
94
+ // ---------------------------------------------------------------------------
95
+
96
+ /** The stage (lane) of a kind of work: talk, decide, build or ship; null for a kind that is not work */
97
+ export const stageOf = (kind) => STAGE_OF[kind] ?? null;
98
+
99
+ /** Whether a time (ISO text) is within `days` of `nowMs`, a time in the future included; a time that is missing or not a date is not */
100
+ export function inWindow(iso, nowMs, days = WINDOW_DAYS) {
101
+ const t = typeof iso === 'string' ? Date.parse(iso) : NaN;
102
+ return Number.isFinite(t) && t >= nowMs - days * DAY_MS;
103
+ }
104
+
105
+ /** Whether a piece of work is drawn: it is open, or it ended within the window (`ended`: when) */
106
+ export const isDrawn = (open, ended, nowMs, days = WINDOW_DAYS) => open === true || inWindow(ended, nowMs, days);
107
+
108
+ /** The marker of the build issue pipeline.js opens for a spec PR's proposal: `{ pull, slug }`, or null (server/pipeline.js `buildMarker` writes it) */
109
+ export function buildMarkerOf(body) {
110
+ const m = /<!-- cornfield-build pull\/([1-9]\d{0,8}) ([A-Za-z0-9][A-Za-z0-9._-]*) -->/.exec(String(body ?? ''));
111
+ return m ? { pull: Number(m[1]), slug: m[2] } : null;
112
+ }
113
+
114
+ const list = (v) => (Array.isArray(v) ? v : []);
115
+ const text = (v) => (typeof v === 'string' ? v : '');
116
+
117
+ /**
118
+ * What a proposal does to the map: the nodes it adds (`{ id, label, type }`), and the ids it changes or removes. Anything that is not a proposal does nothing.
119
+ * @param {any} proposal
120
+ * @returns {{ adds: { id: string, label: string, type: string | null }[], changes: string[] }}
121
+ */
122
+ export function touchesOf(proposal) {
123
+ const nodes = proposal !== null && typeof proposal === 'object' ? proposal.nodes : null;
124
+ const adds = list(nodes && nodes.add).filter((n) => n && typeof n.id === 'string' && n.id !== '').map((n) => ({ id: n.id, label: text(n.label) || n.id, type: text(n.type) || null }));
125
+ const changes = [...list(nodes && nodes.change), ...list(nodes && nodes.remove)].map((n) => (typeof n === 'string' ? n : n && n.id)).filter((id) => typeof id === 'string' && id !== '');
126
+ return { adds, changes: [...new Set(changes)] };
127
+ }
128
+
129
+ /**
130
+ * The map's nodes a pull request's files are (a rename lights the old path's node too), from the page's own rule (`litFor`), at most `MAX_PULL_FILES` files.
131
+ * @param {{ path: string, previousPath?: string | null, status: string }[]} files
132
+ * @param {{ id: string, file?: string }[]} nodes
133
+ * @returns {string[]}
134
+ */
135
+ export function nodesOfFiles(files, nodes) {
136
+ return [...litFor({ files: files.slice(0, MAX_PULL_FILES), checks: [] }, nodes).changed];
137
+ }
138
+
139
+ /** The order of the answer: newest first, then by id, so the same facts are the same bytes (the ETag) */
140
+ const newest = (a, b) => (a.updated < b.updated ? 1 : a.updated > b.updated ? -1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
141
+
142
+ /** Runs `fn` over `items`, `PARALLEL` at a time, keeping the order */
143
+ async function each(items, fn) {
144
+ const out = new Array(items.length);
145
+ let next = 0;
146
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, items.length) }, async () => {
147
+ while (next < items.length) {
148
+ const at = next++;
149
+ out[at] = await fn(items[at], at);
150
+ }
151
+ }));
152
+ return out;
153
+ }
154
+
155
+ /** An id of the work graph's own: a map node with one would be two things */
156
+ const WORK_ID = /^(?:thread|issue|proposal|run|pull|deploy):/;
157
+ /** A link the page may open: http(s) only; anything else (a runner's report saying `javascript:`) is no link */
158
+ const webUrl = (u) => (typeof u === 'string' && /^https?:\/\/[^\s]+$/i.test(u) ? u : null);
159
+ const DATE = (iso) => String(iso).slice(0, 10);
160
+
161
+ const numbers = (ns) => `${ns.slice(0, NAMED).map((n) => `#${n}`).join(', ')}${ns.length > NAMED ? ` and ${ns.length - NAMED} more` : ''}`;
162
+
163
+ /** What a thread's comments said, kept by the time of the thread's last activity: `${number}` -> `{ stamp, refs, proposal }` */
164
+ const threadMemos = new WeakMap();
165
+
166
+ /** The errors that say the forge as a whole cannot be asked now: with nothing else read, the answer is that error, not an empty graph */
167
+ const wholeForge = (err) => err instanceof ForgeError && ['rate-limited', 'unavailable', 'unauthorized'].includes(err.code);
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // The graph
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /**
174
+ * @param {import('./forge.js').Forge} forge the forge as the signed-in maintainer
175
+ * @param {any} config
176
+ * @param {{ nodes?: { id: string, file?: string, label?: string, type?: string, stack?: string }[] } | null} map the repo's map (null: not read)
177
+ * @param {{ where?: any, runs?: { list: () => Promise<{ runs: any[] }> } | null, now?: () => number }} [opts]
178
+ * `where` is the server's (`root`, `proposals`, the worktrees; also the key what is kept by head is kept under), `runs` the agent runs of the repo
179
+ * @returns {Promise<{ nodes: object[], edges: { from: string, to: string, rel: string }[], problems: Problem[] }>}
180
+ * @throws {ForgeError} when the forge as a whole could not be asked and nothing of it was read (rate-limited, away, the token refused)
181
+ */
182
+ export async function workGraph(forge, config, map, { where = config, runs = null, now = Date.now } = {}) {
183
+ const nowMs = now();
184
+ /** @type {Problem[]} */
185
+ const problems = [];
186
+ const say = (source, words) => problems.push({ source, text: words });
187
+ const allMapNodes = map && Array.isArray(map.nodes) ? map.nodes : [];
188
+ if (!map) say('map', 'The map could not be read, so no work is drawn on the code it touches (run cornfield sync).');
189
+ const workLike = allMapNodes.filter((n) => typeof n.id === 'string' && WORK_ID.test(n.id)).map((n) => n.id);
190
+ if (workLike.length) say('map', `${workLike.length === 1 ? 'A map node has' : `${workLike.length} map nodes have`} an id the work graph uses for work (${workLike.slice(0, NAMED).join(', ')}), so no work is drawn on ${workLike.length === 1 ? 'it' : 'them'}: rename ${workLike.length === 1 ? 'it' : 'them'} in the map.`);
191
+ const mapNodes = workLike.length ? allMapNodes.filter((n) => !workLike.includes(n.id)) : allMapNodes;
192
+ const mapIds = new Set(mapNodes.map((n) => n.id));
193
+ const label = ideaLabel(config);
194
+ const attempt = async (fn) => { try { return { value: await fn() }; } catch (err) { return { err }; } };
195
+
196
+ // What each source gives, read at once; a source that fails says so and the rest goes on
197
+ const windowStart = new Date(nowMs - WINDOW_DAYS * DAY_MS).toISOString();
198
+ const [openPulls, closedPulls, openIssues, closedIssues, deployRuns, runList, localFiles] = await Promise.all([
199
+ // every open one, as the Specs list asks (it reads the same files, kept by head), so every open spec PR is here
200
+ attempt(() => forge.pulls({ state: 'open' })),
201
+ attempt(() => forge.pulls({ state: 'closed', limit: LIST_PULLS, sort: 'updated' })),
202
+ attempt(() => forge.issues({ state: 'open', labels: [], limit: LIST_ISSUES })),
203
+ attempt(() => forge.issues({ state: 'closed', labels: [], limit: LIST_RECENT_ISSUES, since: windowStart })),
204
+ attempt(() => forge.runs({ limit: LIST_RUNS })),
205
+ attempt(async () => {
206
+ if (!runs) throw new Error('no store');
207
+ return (await runs.list()).runs;
208
+ }),
209
+ attempt(() => listProposalFiles(where)),
210
+ ]);
211
+ const forgeRead = [openPulls, closedPulls, openIssues, closedIssues, deployRuns];
212
+ const failed = forgeRead.find((r) => r.err && wholeForge(r.err));
213
+ if (failed && forgeRead.every((r) => r.err)) throw failed.err;
214
+ const fail = (source, what, r) => say(source, `${what} could not be read: ${forgeWords(r.err)}`);
215
+ if (openPulls.err) fail('pulls', 'The open pull requests', openPulls);
216
+ if (closedPulls.err) fail('pulls', 'The recently closed pull requests', closedPulls);
217
+ if (openIssues.err) fail('issues', 'The open issues', openIssues);
218
+ if (closedIssues.err) fail('issues', 'The recently closed issues', closedIssues);
219
+ if (deployRuns.err) fail('deploys', 'The deploys', deployRuns);
220
+ if (runList.err) say('runs', runs ? `The agent runs could not be read: ${forgeWords(runList.err)}` : 'Agent runs are not kept here (they need sign-in and a forge), so none are drawn.');
221
+ if (localFiles.err) say('proposals', `The proposals in the checkout could not be read: ${forgeWords(localFiles.err)}`);
222
+
223
+ /** @type {Map<string, any>} id -> node */
224
+ const nodes = new Map();
225
+ /** @type {{ from: string, to: string, rel: string }[]} */
226
+ const edges = [];
227
+ const edge = (from, to, rel) => edges.push({ from, to, rel });
228
+ /** @type {Map<string, { id: string, label: string, type: string | null }>} */
229
+ const planned = new Map();
230
+ const put = (node) => { nodes.set(node.id, { stage: stageOf(node.kind), waiting: false, ...node }); return node; };
231
+ /** A proposal's `adds`: to the map's node, or a planned one; never one with a work node's id */
232
+ const addsOf = (id, adds) => {
233
+ for (const a of adds) {
234
+ if (WORK_ID.test(a.id)) continue;
235
+ if (!mapIds.has(a.id) && !planned.has(a.id)) planned.set(a.id, a);
236
+ edge(id, a.id, 'adds');
237
+ }
238
+ };
239
+
240
+ // ---- pull requests (and the spec PRs among them) ----
241
+ const byUpdate = (a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : b.number - a.number);
242
+ const openAll = (openPulls.value ?? []).slice().sort(byUpdate);
243
+ const isOpen = new Set(openAll.map((p) => p.number));
244
+ // A pull request closed between the two lists is in both: it is the open one here
245
+ const closedAll = (closedPulls.value ?? []).filter((p) => !isOpen.has(p.number));
246
+ const recentAll = closedAll.filter((p) => isDrawn(false, p.mergedAt || p.closedAt || p.updatedAt, nowMs)).sort(byUpdate);
247
+ const recentShown = recentAll.slice(0, MAX_RECENT_PULLS);
248
+ if (recentAll.length > recentShown.length) say('pulls', `${recentAll.length} pull requests were closed in the last ${WINDOW_DAYS} days: the ${MAX_RECENT_PULLS} newest are drawn, ${numbers(recentAll.slice(MAX_RECENT_PULLS).map((p) => p.number))} are left out.`);
249
+ const lastClosed = (closedPulls.value ?? []).at(-1);
250
+ if ((closedPulls.value ?? []).length >= LIST_PULLS && lastClosed && inWindow(lastClosed.updatedAt, nowMs)) {
251
+ say('pulls', `Only the ${LIST_PULLS} most recently updated closed pull requests were read (back to ${DATE(lastClosed.updatedAt)}); one closed before that in the last ${WINDOW_DAYS} days is not drawn.`);
252
+ }
253
+ const listed = [...openAll, ...recentShown];
254
+
255
+ // A pull request's files, once for a head commit (kept), and the proposals its files add or change
256
+ const gotFiles = await each(listed, (pull) => attempt(() => filesAt(forge, where, pull)));
257
+ const unread = [];
258
+ const cut = [];
259
+ const filesOf = new Map();
260
+ /** @type {Map<number, any[]>} number -> the proposal entries of a spec PR */
261
+ const specEntries = new Map();
262
+ for (const [i, pull] of listed.entries()) {
263
+ if (gotFiles[i].err) { unread.push(pull.number); continue; }
264
+ const files = gotFiles[i].value;
265
+ filesOf.set(pull.number, files.slice(0, MAX_PULL_FILES));
266
+ try {
267
+ const found = await pullProposals(forge, where, pull);
268
+ if (found.length) specEntries.set(pull.number, found);
269
+ } catch (err) { say('proposals', `The proposals of pull request #${pull.number} could not be found: ${forgeWords(err)}`); }
270
+ if (files.length > MAX_PULL_FILES && !specEntries.has(pull.number)) cut.push(pull);
271
+ }
272
+ // The open pull requests drawn as pull requests: every spec PR is a proposal and drawn; of the rest, the most recently updated
273
+ const openPlain = openAll.filter((p) => !specEntries.has(p.number));
274
+ const openShown = openPlain.slice(0, MAX_OPEN_PULLS);
275
+ if (openPlain.length > openShown.length) {
276
+ const many = openAll.length >= DEFAULT_LIMIT ? `${DEFAULT_LIMIT} or more` : String(openPlain.length);
277
+ say('pulls', `${many} pull requests are open: the ${MAX_OPEN_PULLS} most recently updated are drawn, ${numbers(openPlain.slice(MAX_OPEN_PULLS).map((p) => p.number))} are left out.`);
278
+ }
279
+ const shownSet = new Set([...openShown, ...openAll.filter((p) => specEntries.has(p.number)), ...recentShown].map((p) => p.number));
280
+ const pulls = listed.filter((p) => shownSet.has(p.number));
281
+ for (const n of [...specEntries.keys()]) if (!shownSet.has(n)) specEntries.delete(n);
282
+ const unreadShown = unread.filter((n) => shownSet.has(n));
283
+ if (unreadShown.length) {
284
+ const first = gotFiles.find((r) => r.err);
285
+ say('pulls', `The files of ${unreadShown.length === 1 ? 'pull request' : 'pull requests'} ${numbers(unreadShown)} could not be read, so what ${unreadShown.length === 1 ? 'it changes' : 'they change'} is not drawn: ${forgeWords(first.err)}`);
286
+ }
287
+ const cutShown = cut.filter((p) => shownSet.has(p.number)).map((p) => `#${p.number} changes ${gotFiles[listed.indexOf(p)].value.length}`);
288
+ if (cutShown.length) say('pulls', `Only the first ${MAX_PULL_FILES} files of a pull request are drawn: ${cutShown.slice(0, NAMED).join(', ')}${cutShown.length > NAMED ? ` and ${cutShown.length - NAMED} more` : ''} files.`);
289
+
290
+ // The proposals of the spec PRs: their files at the head (kept by it), and the review state of the open ones
291
+ const allEntries = [...specEntries.values()].flat();
292
+ const parsed = new Map();
293
+ let unreadFile = 0;
294
+ let firstUnread = null;
295
+ await each(allEntries, async (entry) => {
296
+ try {
297
+ parsed.set(entry, JSON.parse(await readPullProposal(forge, where, entry)));
298
+ } catch (err) { unreadFile++; firstUnread ??= err instanceof SyntaxError ? `not valid JSON: ${err.message}` : forgeWords(err); }
299
+ });
300
+ if (unreadFile) say('proposals', `${unreadFile} proposal ${unreadFile === 1 ? 'file' : 'files'} in spec pull requests could not be read, so what ${unreadFile === 1 ? 'it adds and changes is' : 'they add and change are'} not drawn: ${firstUnread}`);
301
+ const pullOf = new Map(pulls.map((p) => [p.number, p]));
302
+ const openEntries = allEntries.filter((e) => pullOf.get(e.pull.number).state === 'open');
303
+ let states = [];
304
+ try { states = await reviewStates(forge, where, openEntries, { now: () => nowMs }); } catch { states = []; }
305
+ const stateOf = new Map(openEntries.map((e, i) => [e, states[i] || { pushedAt: null, review: null }]));
306
+ if ([...stateOf.values()].some((s) => s.review && s.review.error)) say('proposals', 'The review of some spec pull requests could not be read, so they are not counted as waiting on you.');
307
+
308
+ /** the proposals of each pull request: number -> ids; and the node ids of a number, for `opened` and `shipped` */
309
+ const byPull = new Map();
310
+ /** a spec PR's proposal by `${number} ${slug}` -> its id: the first spec PR to hold a slug (open ones first, the most recently updated first) is `proposal:<slug>` */
311
+ const proposalAt = new Map();
312
+ /** the nodes each proposal changes, drawn once every planned node is known: a proposal may change what another adds */
313
+ const changed = [];
314
+ for (const [n, entries] of specEntries) {
315
+ const pull = pullOf.get(n);
316
+ for (const entry of entries) {
317
+ const proposal = parsed.get(entry);
318
+ const id = nodes.has(`proposal:${entry.slug}`) ? `proposal:${entry.slug}@${n}` : `proposal:${entry.slug}`;
319
+ proposalAt.set(`${n} ${entry.slug}`, id);
320
+ let state;
321
+ let waiting = false;
322
+ if (pull.state === 'open') {
323
+ const got = stateOf.get(entry);
324
+ const read = specStateOf({ pull: { draft: pull.draft, createdAt: pull.createdAt, updatedAt: pull.updatedAt, pushedAt: got.pushedAt }, review: got.review });
325
+ state = read.state;
326
+ waiting = read.counted;
327
+ } else state = pull.state;
328
+ put({
329
+ id, kind: 'proposal', title: text(proposal && proposal.title) || entry.slug, state, open: pull.state === 'open', waiting, slug: entry.slug, number: n, url: webUrl(pull.url), updated: pull.updatedAt, draft: pull.draft,
330
+ author: pull.author ? pull.author.login : null,
331
+ });
332
+ byPull.set(n, [...(byPull.get(n) || []), id]);
333
+ if (proposal) {
334
+ const t = touchesOf(proposal);
335
+ addsOf(id, t.adds);
336
+ changed.push([id, t.changes]);
337
+ }
338
+ }
339
+ }
340
+
341
+ for (const pull of pulls) {
342
+ if (specEntries.has(pull.number)) continue;
343
+ const id = `pull:${pull.number}`;
344
+ put({ id, kind: 'pull', title: pull.title, state: pull.state, open: pull.state === 'open', number: pull.number, url: webUrl(pull.url), updated: pull.updatedAt, draft: pull.draft, author: pull.author ? pull.author.login : null });
345
+ byPull.set(pull.number, [id]);
346
+ if (filesOf.has(pull.number)) for (const to of nodesOfFiles(filesOf.get(pull.number), mapNodes)) edge(id, to, 'changes');
347
+ }
348
+
349
+ // ---- local proposals (the checkout and its worktrees): the PR's wins ----
350
+ const local = new Map();
351
+ for (const f of localFiles.value ?? []) if (!nodes.has(`proposal:${f.slug}`) && !local.has(f.slug)) local.set(f.slug, f);
352
+ const locals = [...local.values()].map((f) => {
353
+ let at = null;
354
+ try { at = fs.statSync(f.file).mtime.toISOString(); } catch { at = null; }
355
+ return { f, at: at ?? new Date(0).toISOString() };
356
+ }).sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.f.slug < b.f.slug ? -1 : 1));
357
+ if (locals.length > MAX_LOCAL_PROPOSALS) say('proposals', `${locals.length} proposals are drafts in the checkout: the ${MAX_LOCAL_PROPOSALS} most recently written are drawn.`);
358
+ for (const { f, at } of locals.slice(0, MAX_LOCAL_PROPOSALS)) {
359
+ const proposal = f.parsed && f.parsed.proposal;
360
+ const id = `proposal:${f.slug}`;
361
+ put({ id, kind: 'proposal', title: text(proposal && proposal.title) || f.slug, state: 'local', open: true, waiting: false, slug: f.slug, number: null, url: null, updated: at, draft: true, source: f.source });
362
+ const t = touchesOf(proposal);
363
+ addsOf(id, t.adds);
364
+ changed.push([id, t.changes]);
365
+ }
366
+ for (const [from, ids] of changed) for (const to of ids) if (mapIds.has(to) || planned.has(to)) edge(from, to, 'changes');
367
+
368
+ // ---- issues, and the ideas among them as threads ----
369
+ const isIdea = (issue) => label !== null && issue.labels.some((l) => l.toLowerCase() === label.toLowerCase());
370
+ if ((openIssues.value ?? []).length >= LIST_ISSUES) say('issues', `${LIST_ISSUES} or more issues are open: the ${LIST_ISSUES} newest are drawn, the older ones are not.`);
371
+ if ((closedIssues.value ?? []).length >= LIST_RECENT_ISSUES) say('issues', `${LIST_RECENT_ISSUES} or more closed issues moved in the last ${WINDOW_DAYS} days: the ${LIST_RECENT_ISSUES} newest are read, the rest are not drawn.`);
372
+ const openNumbers = new Set((openIssues.value ?? []).map((i) => i.number));
373
+ const issues = [...(openIssues.value ?? []), ...(closedIssues.value ?? []).filter((i) => !openNumbers.has(i.number) && isDrawn(false, i.closedAt || i.updatedAt, nowMs))];
374
+ const ideas = [];
375
+ for (const issue of issues) {
376
+ if (isIdea(issue)) { ideas.push(issue); continue; }
377
+ const open = issue.state === 'open';
378
+ const id = `issue:${issue.number}`;
379
+ put({ id, kind: 'issue', title: issue.title, state: issue.state, open, number: issue.number, url: webUrl(issue.url), updated: issue.updatedAt, author: issue.author ? issue.author.login : null });
380
+ for (const to of messageNodes(text(issue.body).slice(0, BODY_READ), mapNodes).nodes.map((n) => n.id)) edge(id, to, 'mentions');
381
+ }
382
+
383
+ // ---- threads: ideas, and the conversations of the spec PRs ----
384
+ if (label === null) say('threads', 'Threads are off in this config (threads: false), so no thread is drawn.');
385
+ else {
386
+ const ideaItems = ideas.slice(0, MAX_THREADS);
387
+ const specThreads = [...specEntries.keys()].filter((n) => pullOf.get(n).state === 'open');
388
+ if (ideas.length > ideaItems.length) say('threads', `${ideas.length} ideas are in the window: the ${MAX_THREADS} newest are drawn.`);
389
+ let memo = threadMemos.get(where);
390
+ if (!memo) threadMemos.set(where, (memo = new Map()));
391
+ const all = [
392
+ ...ideaItems.map((item) => ({ kind: 'idea', item, texts: [text(item.body).slice(0, BODY_READ)], comments: item.comments ?? 0 })),
393
+ ...specThreads.map((n) => ({ kind: 'proposal', item: pullOf.get(n), texts: [], comments: null })),
394
+ ];
395
+ let unreadThreads = 0;
396
+ let firstThread = null;
397
+ const read = await each(all, async (t) => {
398
+ const key = `${t.kind}:${t.item.number}`;
399
+ const kept = memo.get(key);
400
+ if (kept && kept.stamp === t.item.updatedAt) return kept;
401
+ let comments = [];
402
+ // Nothing to ask for an idea that has no comment: its text is the issue's
403
+ if (!(t.kind === 'idea' && t.comments === 0)) {
404
+ try { comments = await forge.comments(t.item.number); } catch (err) { unreadThreads++; firstThread ??= forgeWords(err); return null; }
405
+ }
406
+ const links = linksOf([...t.texts, ...comments.map((c) => text(c.body).slice(0, BODY_READ))]);
407
+ const done = { stamp: t.item.updatedAt, refs: links.refs, proposal: links.proposal };
408
+ memo.set(key, done);
409
+ if (memo.size > 400) memo.delete(memo.keys().next().value);
410
+ return done;
411
+ });
412
+ if (unreadThreads) say('threads', `The comments of ${unreadThreads} ${unreadThreads === 1 ? 'thread' : 'threads'} could not be read, so what ${unreadThreads === 1 ? 'it mentions is' : 'they mention are'} not drawn: ${firstThread}`);
413
+ all.forEach((t, i) => {
414
+ const links = read[i];
415
+ const { item } = t;
416
+ const id = `thread:${item.number}`;
417
+ put({ id, kind: 'thread', title: item.title, state: item.state, open: item.state === 'open', number: item.number, url: webUrl(item.url), updated: item.updatedAt, threadKind: t.kind, author: item.author ? item.author.login : null });
418
+ if (t.kind === 'proposal') for (const to of byPull.get(item.number) || []) edge(id, to, 'discusses');
419
+ if (!links) return;
420
+ for (const to of mentionsOf(links.refs, mapNodes).ids) edge(id, to, 'mentions');
421
+ if (links.proposal && nodes.has(`proposal:${links.proposal}`)) edge(id, `proposal:${links.proposal}`, 'discusses');
422
+ });
423
+ }
424
+
425
+ /** The node of an issue's or an idea's number, whichever it is here; with `issueOnly`, never a spec PR's conversation (a pull request, which no keyword closes) */
426
+ const talkNode = (n, issueOnly = false) => {
427
+ if (nodes.has(`issue:${n}`)) return `issue:${n}`;
428
+ const thread = nodes.get(`thread:${n}`);
429
+ return thread && !(issueOnly && thread.threadKind === 'proposal') ? thread.id : null;
430
+ };
431
+
432
+ // ---- what a pull request or a spec PR says it closes, and what it implements ----
433
+ const buildOf = new Map();
434
+ for (const issue of issues) { const marker = buildMarkerOf(issue.body); if (marker) buildOf.set(issue.number, marker); }
435
+ for (const pull of pulls) {
436
+ const froms = byPull.get(pull.number) || [];
437
+ if (!froms.length) continue;
438
+ const spec = specEntries.has(pull.number);
439
+ const named = [...closesOf(text(pull.body).slice(0, BODY_READ), forge.repo)];
440
+ const threadN = spec ? threadOfPull(text(pull.body).slice(0, BODY_READ)) : null;
441
+ if (threadN !== null && !named.includes(threadN)) named.push(threadN);
442
+ for (const n of named) {
443
+ const to = talkNode(n, true);
444
+ if (!to) continue;
445
+ if (spec && to.startsWith('thread:')) { for (const from of froms) edge(to, from, 'became'); continue; }
446
+ for (const from of froms) edge(from, to, 'closes');
447
+ // The build issue names its spec PR and slug: that proposal, else the slug's own node
448
+ const marker = buildOf.get(n);
449
+ const built = marker && (proposalAt.get(`${marker.pull} ${marker.slug}`) || (nodes.has(`proposal:${marker.slug}`) ? `proposal:${marker.slug}` : null));
450
+ if (!spec && built) edge(froms[0], built, 'implements');
451
+ }
452
+ }
453
+
454
+ // ---- runs ----
455
+ for (const run of runList.value ?? []) {
456
+ const ended = run.lastActivity || (run.report && run.report.at) || run.requestedAt;
457
+ if (!isDrawn(run.open === true, ended, nowMs)) continue;
458
+ const id = `run:${run.runId}`;
459
+ put({
460
+ id, kind: 'run', title: runName(run), state: run.status, open: run.open === true, waiting: canAnswer(run), runId: run.runId, number: null, url: webUrl(run.report && run.report.url) || webUrl(run.comment && run.comment.url) || webUrl(run.pull && run.pull.url),
461
+ updated: ended, requestedBy: run.requestedBy ?? null,
462
+ });
463
+ const about = [run.refs && run.refs.issue, run.refs && run.refs.thread].filter((n) => n != null).map(talkNode).filter(Boolean);
464
+ for (const from of new Set(about)) edge(from, id, 'agent-on');
465
+ const slug = run.refs && run.refs.proposal;
466
+ if (typeof slug === 'string' && nodes.has(`proposal:${slug}`)) edge(`proposal:${slug}`, id, 'agent-on');
467
+ if (run.pull && run.pull.number != null) {
468
+ for (const to of byPull.get(run.pull.number) || []) {
469
+ edge(id, to, 'opened');
470
+ if (typeof slug === 'string' && to.startsWith('pull:') && run.kind === 'code' && nodes.has(`proposal:${slug}`)) edge(to, `proposal:${slug}`, 'implements');
471
+ }
472
+ }
473
+ for (const to of litOfRun(run).changed) if (mapIds.has(to)) edge(id, to, 'changes');
474
+ }
475
+
476
+ // ---- deploys ----
477
+ const lastRun = (deployRuns.value ?? []).at(-1);
478
+ if ((deployRuns.value ?? []).length >= LIST_RUNS && lastRun && inWindow(lastRun.createdAt, nowMs)) {
479
+ say('deploys', `Only the ${LIST_RUNS} newest workflow runs were read (back to ${DATE(lastRun.createdAt)}); a deploy before that in the last ${WINDOW_DAYS} days is not drawn.`);
480
+ }
481
+ const deploys = deploysOf(deployRuns.value ?? [], config.deploys).filter((d) => isDrawn(d.state === 'queued' || d.state === 'running', d.updatedAt || d.createdAt, nowMs));
482
+ const shippedAt = new Map();
483
+ for (const pull of pulls) {
484
+ const sha = pull.state === 'merged' ? pull.mergeSha || (pull.head && pull.head.sha) : null;
485
+ if (sha) shippedAt.set(sha, [...(shippedAt.get(sha) || []), pull.number]);
486
+ }
487
+ for (const d of deploys) {
488
+ const id = `deploy:${d.id}`;
489
+ put({ id, kind: 'deploy', title: d.title || d.name, state: d.state, open: d.state === 'queued' || d.state === 'running', deployId: d.id, number: null, url: webUrl(d.url), updated: d.updatedAt || d.createdAt, name: d.name, branch: d.branch, sha: d.sha, author: d.actor ? d.actor.login : null });
490
+ for (const n of shippedAt.get(d.sha) || []) for (const from of byPull.get(n) || []) edge(from, id, 'shipped');
491
+ for (const to of litForDeploy(d, mapNodes).nodes.map((x) => x.id)) edge(id, to, 'restarts');
492
+ }
493
+
494
+ // ---- the answer: every edge ends at a node that is there, once; the same facts in the same order ----
495
+ const known = (id) => nodes.has(id) || mapIds.has(id) || planned.has(id);
496
+ const seen = new Set();
497
+ const kept = edges.filter((e) => {
498
+ const key = `${e.from}\u0000${e.to}\u0000${e.rel}`;
499
+ if (seen.has(key) || !known(e.from) || !known(e.to) || e.from === e.to) return false;
500
+ seen.add(key);
501
+ return true;
502
+ }).sort((a, b) => (a.from < b.from ? -1 : a.from > b.from ? 1 : a.to < b.to ? -1 : a.to > b.to ? 1 : a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
503
+ const out = [...nodes.values()].sort((a, b) => KINDS.indexOf(a.kind) - KINDS.indexOf(b.kind) || newest(a, b));
504
+ const plannedOut = [...planned.values()].filter((p) => kept.some((e) => e.to === p.id)).sort((a, b) => (a.id < b.id ? -1 : 1)).map((p) => ({ id: p.id, kind: 'code', planned: true, label: p.label, type: p.type }));
505
+ return { nodes: [...out, ...plannedOut], edges: kept, problems };
506
+ }