@popcorn245/cornfield 0.53.0 → 0.55.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.
@@ -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;