@popcorn245/cornfield 0.37.0 → 0.38.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.
@@ -0,0 +1,287 @@
1
+ /**
2
+ * @module explorer/waiting-model
3
+ *
4
+ * What is waiting on the maintainer (spec 0010), the pure half: no DOM, no `window`, no clock of its own (`nowMs` is handed in).
5
+ * One number says what asks for a decision: the specs to decide plus the runs waiting on an answer (D1). Everything else the
6
+ * panel shows of it is a function of the two lists it is handed:
7
+ *
8
+ * specStateOf a listing entry's review state: its group, its pill and since when it has been that way (D3, D4)
9
+ * specGroups the Specs tab's groups: To decide, With the agent, Approved, Drafts (D3), with the search applied (D5)
10
+ * waitingSpecs the specs to decide, as counted (a spec whose review could not be read is not counted: nobody knows it waits)
11
+ * runGroups the Runs tab's groups: Needs you, In motion, Finished, each in its order (D6)
12
+ * waitingRuns the open runs that wait on an answer (`canAnswer`)
13
+ * waiting the one number, and the tab with the oldest thing waiting (D2)
14
+ *
15
+ * The review state is the server's (`review: { verdict, by, at, current }` on a listing entry, server/proposal-pulls.js); the words that
16
+ * come from the forge (a login, a date) are data and are escaped by the view, never here.
17
+ */
18
+
19
+ import { canAnswer, groupRuns } from './runs-model.js';
20
+ import { relativeTime } from './review-model.js';
21
+ import { t } from './strings.js';
22
+
23
+ /** The groups of the Specs tab, in order, with the key each carries as `data-group` and the `strings` key of its title */
24
+ export const SPEC_GROUPS = Object.freeze([
25
+ { key: 'decide', title: 'toDecide' },
26
+ { key: 'agent', title: 'withAgent' },
27
+ { key: 'approved', title: 'approvedGroup' },
28
+ { key: 'drafts', title: 'drafts' },
29
+ ]);
30
+
31
+ /** The groups of the Runs tab, in order */
32
+ export const RUN_GROUPS = Object.freeze([
33
+ { key: 'needs', title: 'needsYou' },
34
+ { key: 'motion', title: 'inMotion' },
35
+ { key: 'finished', title: 'finished' },
36
+ ]);
37
+
38
+ /** The words of a Specs group's header (a repo may say them in its own voice: `strings`) */
39
+ export function specGroupTitle(key) {
40
+ switch (key) {
41
+ case 'decide': return t('toDecide');
42
+ case 'agent': return t('withAgent');
43
+ case 'approved': return t('approvedGroup');
44
+ default: return t('drafts');
45
+ }
46
+ }
47
+
48
+ /** The words of a Runs group's header */
49
+ export function runGroupTitle(key) {
50
+ switch (key) {
51
+ case 'needs': return t('needsYou');
52
+ case 'motion': return t('inMotion');
53
+ default: return t('finished');
54
+ }
55
+ }
56
+
57
+ /** The words of the proposal bar's button that goes to the run waiting on the proposal */
58
+ export const answerWord = () => t('answer');
59
+
60
+ /** Drafts past this many rows are collapsed behind their header (D3) */
61
+ export const DRAFTS_OPEN_MAX = 10;
62
+
63
+ /** The states of a spec row's pill, in the order the contract lists them; each is a fixed word (`SPEC_STATE_WORDS`), never the forge's */
64
+ export const SPEC_STATES = Object.freeze(['to-decide', 'changed', 'sent-back', 'approved', 'draft-pr', 'local', 'unknown']);
65
+
66
+ /** The pill's words for each state */
67
+ export const SPEC_STATE_WORDS = Object.freeze({
68
+ 'to-decide': 'To decide',
69
+ changed: 'Changed since approved',
70
+ 'sent-back': 'Sent back',
71
+ approved: 'Approved',
72
+ 'draft-pr': 'Draft PR',
73
+ local: 'Local',
74
+ unknown: 'Review state unknown',
75
+ });
76
+
77
+ /**
78
+ * The public `data-corn-state` of each pill (docs/theming.md): a spec to decide and a changed one are `waiting`, approved is `success`,
79
+ * and `sent-back` is this spec's own. A draft PR and a local copy are the `draft` they already were; an unread review is a `failure` line.
80
+ */
81
+ export const SPEC_STATE_CORN = Object.freeze({
82
+ 'to-decide': 'waiting', changed: 'waiting', 'sent-back': 'sent-back', approved: 'success', 'draft-pr': 'draft', local: 'draft', unknown: 'failure',
83
+ });
84
+
85
+ const time = (iso) => {
86
+ const ms = typeof iso === 'string' ? Date.parse(iso) : NaN;
87
+ return Number.isFinite(ms) ? ms : null;
88
+ };
89
+
90
+ /**
91
+ * What a listing entry's review says, in one of the states above, which group it is in, and since when (ms, or null when the forge gave no date):
92
+ *
93
+ * - no pull request: a draft in a checkout or a worktree (`local`, Drafts);
94
+ * - a draft pull request: with the agent (`draft-pr`), whatever was said on it before;
95
+ * - a review that could not be read (`review.error`): `unknown`. It is shown under To decide, so it is not missed, and not counted;
96
+ * - never reviewed, or pushed to since a send-back: to decide;
97
+ * - approved at the file's current hash: Approved; approved and the file changed since (`current` false): to decide, `changed`;
98
+ * - sent back and not pushed since: with the agent.
99
+ * `since` is the push that is being waited on for a spec to decide (else the pull request's own dates), the review's time for the others.
100
+ * @param {{ pull?: { draft?: boolean, createdAt?: string, updatedAt?: string, pushedAt?: string | null }, review?: { verdict?: string, at?: string, current?: boolean, error?: string } | null }} entry
101
+ * @returns {{ group: 'decide' | 'agent' | 'approved' | 'drafts', state: string, since: number | null, counted: boolean }}
102
+ */
103
+ export function specStateOf(entry) {
104
+ const pull = entry && entry.pull;
105
+ if (!pull) return { group: 'drafts', state: 'local', since: null, counted: false };
106
+ const pushed = time(pull.pushedAt) ?? time(pull.updatedAt) ?? time(pull.createdAt);
107
+ if (pull.draft) return { group: 'agent', state: 'draft-pr', since: time(pull.updatedAt) ?? time(pull.createdAt), counted: false };
108
+ const review = entry.review;
109
+ if (review && review.error) return { group: 'decide', state: 'unknown', since: pushed, counted: false };
110
+ const at = review ? time(review.at) : null;
111
+ if (!review || !['approved', 'notes'].includes(review.verdict)) return { group: 'decide', state: 'to-decide', since: pushed, counted: true };
112
+ if (review.verdict === 'approved') {
113
+ return review.current === true
114
+ ? { group: 'approved', state: 'approved', since: at, counted: false }
115
+ : { group: 'decide', state: 'changed', since: pushed, counted: true };
116
+ }
117
+ return review.current === true
118
+ ? { group: 'agent', state: 'sent-back', since: at, counted: false }
119
+ : { group: 'decide', state: 'to-decide', since: pushed, counted: true };
120
+ }
121
+
122
+ /** The specs that ask for a decision, as the number counts them (Drafts, draft PRs, sent-back, approved and unread ones are not) */
123
+ export const waitingSpecs = (entries) => (Array.isArray(entries) ? entries.filter((e) => specStateOf(e).counted) : []);
124
+
125
+ /** Whether a row matches the search: its title, slug or summary contains every word typed, in any case (D5) */
126
+ export function specMatches(entry, query) {
127
+ const words = String(query || '').toLowerCase().split(/\s+/).filter(Boolean);
128
+ if (!words.length) return true;
129
+ const hay = `${entry.title || ''}\n${entry.slug || ''}\n${entry.summary || ''}`.toLowerCase();
130
+ return words.every((w) => hay.includes(w));
131
+ }
132
+
133
+ /** Oldest first; a row with no date is last */
134
+ const oldest = (a, b) => (a.since ?? Infinity) - (b.since ?? Infinity);
135
+ /** Newest first; a row with no date is last */
136
+ const newest = (a, b) => (b.since ?? -Infinity) - (a.since ?? -Infinity);
137
+
138
+ /**
139
+ * The Specs tab's groups. Empty groups are left out (D3), unless the search emptied them: then the header still says "0 of 6" so the
140
+ * list does not seem to lose them. Each row is `{ entry, state, since }`. Within a group: To decide waiting longest first, With the agent
141
+ * and Approved newest first, Drafts by slug (spec number first, as the files are named).
142
+ * @param {object[]} entries one row for each proposal (`mergeSpecs`)
143
+ * @param {{ query?: string }} [opts]
144
+ * @returns {{ key: string, title: string, total: number, shown: number, rows: { entry: object, state: string, since: number | null, counted: boolean }[], collapsed: boolean }[]}
145
+ */
146
+ export function specGroups(entries, { query = '' } = {}) {
147
+ const rows = (Array.isArray(entries) ? entries : []).map((entry) => ({ entry, ...specStateOf(entry) }));
148
+ const filtering = String(query || '').trim() !== '';
149
+ const out = [];
150
+ for (const g of SPEC_GROUPS) {
151
+ const all = rows.filter((r) => r.group === g.key);
152
+ if (!all.length) continue;
153
+ const kept = all.filter((r) => specMatches(r.entry, query));
154
+ if (filtering && !kept.length) continue; // a search with no match in a group drops its header: "2 of 6" is for a group with something to show
155
+ const sorted = [...kept].sort(g.key === 'decide' ? oldest : g.key === 'drafts' ? (a, b) => String(a.entry.slug).localeCompare(String(b.entry.slug)) : newest);
156
+ out.push({ key: g.key, title: g.title, total: all.length, shown: kept.length, rows: sorted, collapsed: g.key === 'drafts' && !filtering && all.length > DRAFTS_OPEN_MAX });
157
+ }
158
+ return out;
159
+ }
160
+
161
+ // ---------------------------------------------------------------------------
162
+ // Runs
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /** Statuses that are under way: asked for, claimed, working, or asked to stop and not stopped yet (D6) */
166
+ const IN_MOTION = new Set(['requested', 'claimed', 'working', 'stop-requested']);
167
+
168
+ /**
169
+ * Which group a run is in: `needs` (`waiting`, nobody asked it to stop: `canAnswer`), `motion`, or `finished` (done, failed, stopped, and quiet,
170
+ * which no longer counts as open). A status this does not know is finished: it is not asking anything.
171
+ * @returns {'needs' | 'motion' | 'finished'}
172
+ */
173
+ export function runGroupOf(run) {
174
+ if (canAnswer(run)) return 'needs';
175
+ if (run.open === true && IN_MOTION.has(run.status)) return 'motion';
176
+ return 'finished';
177
+ }
178
+
179
+ /** The runs waiting on an answer */
180
+ export const waitingRuns = (runs) => (Array.isArray(runs) ? runs.filter(canAnswer) : []);
181
+
182
+ /** When a run began to wait: its latest report (the question), else when it was asked (ms, or null) */
183
+ export function waitingSinceOf(run) {
184
+ const reports = (run.timeline || []).filter((e) => e && e.kind === 'report' && time(e.at) !== null);
185
+ if (reports.length) return Math.max(...reports.map((e) => time(e.at)));
186
+ return time(run.requestedAt);
187
+ }
188
+
189
+ /**
190
+ * The Runs list in groups (D6): Needs you, oldest question first; In motion, newest first; Finished, newest first. Runs of one request under
191
+ * several profiles stay together (`groupRuns`), in the group of the most urgent of them. Empty groups are left out.
192
+ * @param {object[]} runs
193
+ * @returns {{ key: string, title: string, items: ReturnType<typeof groupRuns>, count: number }[]}
194
+ */
195
+ export function runGroups(runs) {
196
+ const rank = { needs: 0, motion: 1, finished: 2 };
197
+ const placed = groupRuns(Array.isArray(runs) ? runs : []).map((item) => {
198
+ const members = item.kind === 'run' ? [item.run] : item.runs;
199
+ const key = members.map(runGroupOf).sort((a, b) => rank[a] - rank[b])[0];
200
+ const here = members.filter((r) => runGroupOf(r) === key);
201
+ const when = key === 'needs' ? Math.min(...here.map((r) => waitingSinceOf(r) ?? Infinity)) : Math.max(...members.map((r) => time(r.requestedAt) ?? -Infinity));
202
+ return { item, key, when, count: members.length };
203
+ });
204
+ return RUN_GROUPS.map((g) => {
205
+ const mine = placed.filter((p) => p.key === g.key).sort((a, b) => (g.key === 'needs' ? a.when - b.when : b.when - a.when));
206
+ return { key: g.key, title: g.title, items: mine.map((p) => p.item), count: mine.reduce((n, p) => n + p.count, 0) };
207
+ }).filter((g) => g.items.length);
208
+ }
209
+
210
+ // ---------------------------------------------------------------------------
211
+ // The number
212
+ // ---------------------------------------------------------------------------
213
+
214
+ /**
215
+ * What waits on the maintainer: `specs` (to decide) plus `runs` (waiting on an answer), `total`, and the tab that holds the oldest thing
216
+ * waiting: Specs or Runs ('work' is the Runs tab's kind), null when nothing waits. A list that has not been read counts nothing.
217
+ * @param {{ specs?: object[] | null, runs?: object[] | null }} lists
218
+ * @returns {{ specs: number, runs: number, total: number, oldest: 'specs' | 'work' | null }}
219
+ */
220
+ export function waiting({ specs, runs } = {}) {
221
+ const s = waitingSpecs(specs);
222
+ const r = waitingRuns(runs);
223
+ const sSince = s.length ? Math.min(...s.map((e) => specStateOf(e).since ?? Infinity)) : null;
224
+ const rSince = r.length ? Math.min(...r.map((x) => waitingSinceOf(x) ?? Infinity)) : null;
225
+ let oldest = null;
226
+ if (s.length && r.length) oldest = (rSince ?? Infinity) < (sSince ?? Infinity) ? 'work' : 'specs';
227
+ else if (s.length) oldest = 'specs';
228
+ else if (r.length) oldest = 'work';
229
+ return { specs: s.length, runs: r.length, total: s.length + r.length, oldest };
230
+ }
231
+
232
+ /** "3 waiting on you" (the Work button's name, spoken: "Work, 3 waiting on you"), or '' when nothing waits */
233
+ export const waitingWords = (n) => (n > 0 ? `${n} ${t('waitingOnYou')}` : '');
234
+
235
+ /** The Work button's accessible name: its label, then what waits ("Work, 3 waiting on you") */
236
+ export const workButtonName = (label, n) => (n > 0 ? `${label}, ${waitingWords(n)}` : label);
237
+
238
+ /** What a group's header says: "To decide · 2", or "To decide · 2 of 6" while a search narrows it */
239
+ export const groupCountWords = (g) => (g.shown === g.total ? String(g.total) : `${g.shown} of ${g.total}`);
240
+
241
+ /**
242
+ * The words under a spec row's pill: who and when ("Approved by maintainer-one · 2 h ago", "Sent back by maintainer-one · yesterday",
243
+ * "Waiting 2 days"), or '' when there is nothing to add. `by` and the dates come from the forge: the caller escapes the result.
244
+ * @param {{ pull?: object, review?: { verdict?: string, by?: string, at?: string, error?: string } | null }} entry
245
+ * @param {number} nowMs
246
+ */
247
+ export function specStateWords(entry, nowMs) {
248
+ const s = specStateOf(entry);
249
+ const review = entry.review;
250
+ const ago = (ms) => (ms === null ? '' : relativeTime(new Date(ms).toISOString(), nowMs) || '');
251
+ const by = (verb) => [`${verb}${review && review.by ? ` by ${review.by}` : ''}`, ago(time(review && review.at))].filter(Boolean).join(' · ');
252
+ switch (s.state) {
253
+ case 'approved': return by('Approved');
254
+ case 'sent-back': return by('Sent back');
255
+ case 'changed': return `${by('Approved')}; changed since`;
256
+ case 'to-decide': {
257
+ const w = s.since === null ? '' : ago(s.since);
258
+ return !w ? '' : w === 'just now' ? 'Just arrived' : `Waiting ${w.replace(/ ago$/, '')}`;
259
+ }
260
+ default: return '';
261
+ }
262
+ }
263
+
264
+ // ---------------------------------------------------------------------------
265
+ // The proposal bar's line
266
+ // ---------------------------------------------------------------------------
267
+
268
+ /** The open run waiting on an answer that is about proposal `slug`, the one that has waited longest; null when none is */
269
+ export function runWaitingOn(runs, slug) {
270
+ if (!slug) return null;
271
+ const mine = waitingRuns(runs).filter((r) => r.refs && r.refs.proposal === slug);
272
+ return mine.sort((a, b) => (waitingSinceOf(a) ?? Infinity) - (waitingSinceOf(b) ?? Infinity))[0] || null;
273
+ }
274
+
275
+ /** The longest the runner's question is shown in the bar's line, in characters */
276
+ export const LINE_NOTE_MAX = 90;
277
+
278
+ /**
279
+ * The bar's line: "A run is waiting on you: Plan ready: approve to build, or say what to change". The runner's own words are cut to
280
+ * `LINE_NOTE_MAX` characters (the whole of it is in the run's card) and are data: the caller sets them as text.
281
+ * @param {{ report?: { note?: string } | null }} run
282
+ */
283
+ export function waitingLineWords(run) {
284
+ const note = run && run.report && typeof run.report.note === 'string' ? run.report.note.replace(/\s+/g, ' ').trim() : '';
285
+ const cut = note.length > LINE_NOTE_MAX ? `${note.slice(0, LINE_NOTE_MAX - 1).trimEnd()}\u2026` : note;
286
+ return `A run is waiting on you${cut ? `: ${cut}` : ''}`;
287
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @module explorer/waiting-view
3
+ *
4
+ * The markup of what is waiting on the maintainer (spec 0010), as strings: the Specs tab's groups with their headers, and the Runs tab's group
5
+ * headings. Pure: no DOM, no clock of its own. Every word from the forge is escaped (a row's own markup is proposal-model.js `specRowHtml`).
6
+ */
7
+
8
+ import { escHtml } from './state.js';
9
+ import { specRowHtml } from './proposal-model.js';
10
+ import { specGroupTitle, runGroupTitle, groupCountWords } from './waiting-model.js';
11
+
12
+ /**
13
+ * The Specs tab's groups, each a heading with its count and its rows. Drafts past ten rows are folded behind a button on the header
14
+ * (`draftsOpen` says whether the person opened it). With a search, a group's count reads "2 of 6".
15
+ * @param {ReturnType<import('./waiting-model.js').specGroups>} groups
16
+ * @param {{ current?: { slug: string, source: string } | null, nowMs?: number, draftsOpen?: boolean | null }} [opts]
17
+ */
18
+ export function specGroupsHtml(groups, { current = null, nowMs = Date.now(), draftsOpen = null } = {}) {
19
+ return groups.map((g) => {
20
+ const id = `spec-group-${g.key}`;
21
+ const words = `${specGroupTitle(g.key)} · ${groupCountWords(g)}`;
22
+ const foldable = g.key === 'drafts' && g.total > 10 && g.shown === g.total; // not while a search narrows it: then it is open
23
+ const folded = foldable && (draftsOpen === null ? g.collapsed : !draftsOpen);
24
+ const title = foldable
25
+ ? `<button type="button" class="hx-forge-gtoggle" data-spec-group-toggle="${escHtml(g.key)}" aria-expanded="${!folded}" aria-controls="${id}-list" data-corn-kind="quiet">${escHtml(words)}</button>`
26
+ : escHtml(words);
27
+ const rows = g.rows.map((r) => specRowHtml(r.entry, { current, nowMs })).join('');
28
+ return `<li class="hx-forge-group hx-spec-group" data-key="${id}" data-corn="spec-group" data-group="${escHtml(g.key)}"><h3 class="hx-forge-gtitle" id="${id}">${title}</h3>`
29
+ + `<ul class="hx-forge-list" id="${id}-list" aria-labelledby="${id}"${folded ? ' hidden' : ''}>${rows}</ul></li>`;
30
+ }).join('');
31
+ }
32
+
33
+ /** The heading that starts a group of the Runs list: "Needs you · 1". It is an item of the flat list (a run's card is never moved into a section) */
34
+ export function runGroupHeadingHtml(g) {
35
+ const id = `run-group-${g.key}`;
36
+ return `<li class="hx-run-heading" data-key="${id}" data-corn="run-group" data-group="${escHtml(g.key)}"><h4 class="hx-forge-gtitle" id="${id}">${escHtml(`${runGroupTitle(g.key)} · ${g.count}`)}</h4></li>`;
37
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.37.0",
3
+ "version": "0.38.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)",
@@ -83,7 +83,7 @@ const toFile = (f) => ({ path: f.filename, status: FILE_STATUS[f.status] || 'mod
83
83
 
84
84
  /** @returns {import('./forge.js').Comment} */
85
85
  /** @returns {import('./forge.js').PullCommit} */
86
- const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '' });
86
+ const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '', date: c.commit?.committer?.date ?? c.commit?.author?.date ?? null });
87
87
 
88
88
  const toComment = (c) => ({ id: String(c.id), author: author(c.user), body: c.body ?? '', url: c.html_url, createdAt: c.created_at, updatedAt: c.updated_at });
89
89
 
@@ -67,7 +67,7 @@ const toPull = (p) => ({
67
67
  });
68
68
 
69
69
  /** @returns {import('./forge.js').PullCommit} */
70
- const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '' });
70
+ const toCommit = (c) => ({ sha: String(c.sha ?? ''), message: typeof c.commit?.message === 'string' ? c.commit.message : '', date: c.commit?.committer?.date ?? c.commit?.author?.date ?? null });
71
71
 
72
72
  const FILE_STATUS = { added: 'added', copied: 'added', removed: 'removed', renamed: 'renamed', modified: 'modified', changed: 'modified', unchanged: 'modified' };
73
73
  /** @returns {import('./forge.js').PullFile} */
package/server/forge.js CHANGED
@@ -60,7 +60,7 @@
60
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
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
- * @typedef {{ sha: string, message: string }} PullCommit
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
64
64
  * @typedef {'queued' | 'running' | 'success' | 'failure' | 'neutral' | 'skipped' | 'cancelled'} CheckState
65
65
  * @typedef {{ id: string, name: string, state: CheckState, url: string | null, rerunnable: boolean }} Check
66
66
  * @typedef {{ name: string, sha: string, protected: boolean }} Branch
@@ -16,12 +16,22 @@
16
16
  * head. Every maintainer of the repo sees the same PRs, so what one maintainer's token read is shown to another.
17
17
  * Answers are kept only when the forge gave them; a failure is asked again next time.
18
18
  *
19
- * @typedef {{ slug: string, source: string, path: string, sha: string, pull: { number: number, title: string, url: string, draft: boolean, author: string | null } }} PullEntry
19
+ * **What the review state costs** (spec 0010 D4). A listed proposal of a ready PR also carries its review state (`reviewStates`): the
20
+ * latest maintainer review, whether it still holds (`current`), and when the head was pushed. It is read once for a PR at a head and kept
21
+ * for `REVIEW_KEEP_MS` (5 minutes): one `comments` call for the PR, a `permission` call for each author of a review block (once per listing, whatever the number of PRs), and a
22
+ * `pullCommits` call for the head (kept by sha for good: a commit never changes). A draft PR is not read at all. A review posted from cornfield
23
+ * is forgotten at once (`forgetReviewState`); one posted on the forge shows within the 5 minutes. A read that fails is never kept, and says so
24
+ * (`review: { error }`), so a PR whose review could not be read never looks unreviewed.
25
+ *
26
+ * @typedef {{ slug: string, source: string, path: string, sha: string, pull: { number: number, title: string, url: string, draft: boolean, author: string | null, createdAt: string, updatedAt: string } }} PullEntry
27
+ * @typedef {{ verdict: 'approved' | 'notes', by: string, at: string, current: boolean }} ReviewState `current`: an approval is of the file as the head holds it now; a send-back has had no push since
28
+ * @typedef {{ pushedAt: string | null, review: ReviewState | { error: string } | null }} PullReviewState
20
29
  */
21
30
 
22
31
  import path from 'node:path';
23
32
  import { ForgeError } from './forge.js';
24
33
  import { PROPOSAL_FILE } from './files.js';
34
+ import { latestReview, proposalHash } from './reviews.js';
25
35
 
26
36
  /** How many pull requests have their files asked at once */
27
37
  const PARALLEL = 6;
@@ -72,7 +82,7 @@ function entryOf(pull, file) {
72
82
  source: pullSource(pull.number),
73
83
  path: file.path,
74
84
  sha: pull.head.sha,
75
- pull: { number: pull.number, title: pull.title, url: pull.url, draft: pull.draft, author: pull.author ? pull.author.login : null },
85
+ pull: { number: pull.number, title: pull.title, url: pull.url, draft: pull.draft, author: pull.author ? pull.author.login : null, createdAt: pull.createdAt, updatedAt: pull.updatedAt },
76
86
  };
77
87
  }
78
88
 
@@ -161,3 +171,84 @@ export async function readPullProposal(forge, where, entry) {
161
171
  if (text === null) throw new ForgeError(`${entry.path} is not at the head of pull request #${entry.pull.number}.`, { code: 'not-found' });
162
172
  return text;
163
173
  }
174
+
175
+ // ---------------------------------------------------------------------------
176
+ // The review state of each listed proposal (spec 0010 D4)
177
+ // ---------------------------------------------------------------------------
178
+
179
+ /** How long a PR's review state is kept at one head: a review posted on the forge itself shows within this */
180
+ export const REVIEW_KEEP_MS = 5 * 60_000;
181
+
182
+ /** @type {WeakMap<object, Map<string, { at: number, value: { byIndex: Record<string, PullReviewState> } }>>} */
183
+ const reviewCaches = new WeakMap();
184
+
185
+ /** Forgets what was kept of PR `n`'s reviews (a review was just posted on it), so the next listing reads it again */
186
+ export function forgetReviewState(where, n) {
187
+ const kept = reviewCaches.get(where);
188
+ if (!kept) return;
189
+ for (const key of [...kept.keys()]) if (key.startsWith(`${n}@`)) kept.delete(key);
190
+ }
191
+
192
+ /**
193
+ * The review state of every listed proposal, in the order of `entries`: `{ pushedAt, review }`. A draft PR is not read (it waits on the agent,
194
+ * whatever was said on it before): `{ pushedAt: null, review: null }`. For a ready PR, `review` is null (none yet), the latest maintainer review
195
+ * with `current`, or `{ error }` when the forge could not say. Never throws.
196
+ * @param {import('./forge.js').Forge} forge
197
+ * @param {{ proposals: string }} where
198
+ * @param {PullEntry[]} entries
199
+ * @param {{ now?: () => number }} [opts]
200
+ * @returns {Promise<PullReviewState[]>}
201
+ */
202
+ export async function reviewStates(forge, where, entries, { now = Date.now } = {}) {
203
+ let kept = reviewCaches.get(where);
204
+ if (!kept) reviewCaches.set(where, (kept = new Map()));
205
+ const out = entries.map(() => ({ pushedAt: null, review: null }));
206
+ /** @type {Map<number, number[]>} the indexes of the ready PRs' entries, by PR number */
207
+ const byPull = new Map();
208
+ entries.forEach((e, i) => { if (!e.pull.draft) byPull.set(e.pull.number, [...(byPull.get(e.pull.number) || []), i]); });
209
+ const numbers = [...byPull.keys()];
210
+ /** Who is a maintainer, asked once for this listing whatever the number of PRs they reviewed (not kept past it: a role can change) */
211
+ const admins = new Map();
212
+ let next = 0;
213
+ const worker = async () => {
214
+ while (next < numbers.length) {
215
+ const n = numbers[next++];
216
+ const at = byPull.get(n);
217
+ const head = entries[at[0]].sha;
218
+ const key = `${n}@${head}`;
219
+ const hit = kept.get(key);
220
+ if (hit && now() - hit.at < REVIEW_KEEP_MS && at.every((i) => hit.value.byIndex[entries[i].slug])) {
221
+ at.forEach((i) => { out[i] = hit.value.byIndex[entries[i].slug]; });
222
+ continue;
223
+ }
224
+ let pushedAt = null;
225
+ try {
226
+ const commits = await atSha(where, `commits ${n}@${head}`, () => forge.pullCommits(n));
227
+ pushedAt = commits.length ? commits[commits.length - 1].date : null;
228
+ const comments = await forge.comments(n);
229
+ /** @type {Record<string, PullReviewState>} */
230
+ const byIndex = {};
231
+ for (const i of at) {
232
+ const entry = entries[i];
233
+ const found = await latestReview(forge, n, entry.slug, comments, admins);
234
+ let review = null;
235
+ if (found) {
236
+ let current;
237
+ if (found.verdict === 'approved') current = found.proposal === proposalHash(await readPullProposal(forge, where, entry));
238
+ else current = !(pushedAt && Date.parse(pushedAt) > Date.parse(found.at)); // a send-back stands until something is pushed after it
239
+ review = { verdict: found.verdict, by: found.by, at: found.at, current };
240
+ }
241
+ byIndex[entry.slug] = { pushedAt, review };
242
+ out[i] = byIndex[entry.slug];
243
+ }
244
+ kept.set(key, { at: now(), value: { byIndex } });
245
+ if (kept.size > CACHE_MAX) kept.delete(kept.keys().next().value);
246
+ } catch (err) {
247
+ const failed = { pushedAt, review: { error: forgeWords(err) } }; // not kept: asked again next time
248
+ at.forEach((i) => { out[i] = failed; });
249
+ }
250
+ }
251
+ };
252
+ await Promise.all(Array.from({ length: Math.min(PARALLEL, numbers.length) }, worker));
253
+ return out;
254
+ }
@@ -47,7 +47,7 @@ import { summarize, proposalProblems } from '../core/proposal.js';
47
47
  import { ForgeError } from './forge.js';
48
48
  import { REVIEW_LIMIT, latestReview, migrateStage1Reviews } from './reviews.js';
49
49
  import { submitReview, refusal } from './submit-review.js';
50
- import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal } from './proposal-pulls.js';
50
+ import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal, reviewStates } from './proposal-pulls.js';
51
51
  import { serveMockups } from './mockups.js';
52
52
 
53
53
  // The review's checks live in server/reviews.js; these are re-exported for the callers that always had them here
@@ -211,7 +211,9 @@ async function listWithPulls(where, forgeFor, signedIn) {
211
211
  }
212
212
  const { entries, problem } = await listPullProposals(forge, where, { hooks: signedIn?.hooks });
213
213
  if (signedIn && entries.length) await migrateStage1Reviews({ forge, dataDir: where.dataDir, entries, login: signedIn.login, record: signedIn.record });
214
- const pulls = await Promise.all(entries.map((entry) => describePull(entry, forge, where, topology)));
214
+ // Each ready PR's review state rides along (spec 0010 D4), kept by head; a draft PR is not read
215
+ const [pulls, states] = await Promise.all([Promise.all(entries.map((entry) => describePull(entry, forge, where, topology))), reviewStates(forge, where, entries)]);
216
+ pulls.forEach((p, i) => { p.review = states[i].review; if (p.pull) p.pull = { ...p.pull, pushedAt: states[i].pushedAt }; });
215
217
  const list = [...local, ...pulls].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
216
218
  return { list, problem };
217
219
  }
package/server/reviews.js CHANGED
@@ -187,19 +187,20 @@ export function parseReviewBlocks(body) {
187
187
  * @param {number} n
188
188
  * @param {string} slug
189
189
  * @param {import('./forge.js').Comment[]} [comments] when the caller already has them
190
+ * @param {Map<string, Promise<boolean>>} [admins] who was found to be a maintainer, shared by the caller across one read of several PRs (never kept longer)
190
191
  * @returns {Promise<FoundReview | null>}
191
192
  */
192
- export async function latestReview(forge, n, slug, comments) {
193
+ export async function latestReview(forge, n, slug, comments, admins = new Map()) {
193
194
  const all = comments ?? (await forge.comments(n));
194
- const admins = new Map();
195
195
  for (let i = all.length - 1; i >= 0; i--) {
196
196
  const c = all[i];
197
197
  if (!c.author) continue; // a deleted account: nobody to ask about
198
198
  const found = parseReviewBlocks(c.body).filter((b) => b.slug === slug).pop();
199
199
  if (!found) continue;
200
200
  const login = c.author.login;
201
- if (!admins.has(login)) admins.set(login, isMaintainer(await forge.permission(forge.repo, login)));
202
- if (!admins.get(login)) continue;
201
+ // the answer is kept as a promise, so PRs read side by side ask about one person once
202
+ if (!admins.has(login)) admins.set(login, Promise.resolve(forge.permission(forge.repo, login)).then(isMaintainer));
203
+ if (!(await admins.get(login))) continue;
203
204
  // A maintainer's review someone may have rewritten: it does not stand, and an older one does not take its place
204
205
  if (wasEdited(c)) return null;
205
206
  return { version: 1, slug, ...found.review, at: c.createdAt, by: login, comment: { id: c.id, url: c.url } };
@@ -36,7 +36,7 @@
36
36
 
37
37
  import { ForgeError, isMaintainer } from './forge.js';
38
38
  import { PROPOSAL_FILE } from './files.js';
39
- import { findPullProposal, forgeWords, readPullProposal } from './proposal-pulls.js';
39
+ import { findPullProposal, forgeWords, forgetReviewState, readPullProposal } from './proposal-pulls.js';
40
40
  import { hashPullMockups } from './mockups.js';
41
41
  import { postReview, proposalHash, validateReview } from './reviews.js';
42
42
  import { Refused, countAttempt, throttle } from './throttle.js';
@@ -130,6 +130,7 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
130
130
  if (why) throw new Refused(403, why, 'forbidden');
131
131
  }
132
132
  const posted = await postReview(forge, pull, slug, checkedReview, { login: me.login, record, via });
133
+ forgetReviewState(ctx.where, pull); // the listing's review state for this PR is read again (spec 0010)
133
134
  // The one place a review is posted, so the button and the API fire the same event; the actor is who the forge says
134
135
  // the poster is (with the API, the token's owner), never a name the caller sent
135
136
  ctx.hooks?.emit(posted.verdict === 'approved' ? 'spec.approved' : 'spec.sentBack', () => proposalPayload(forge, ctx.where, entry, { actor: me.login, note: checkedReview.note, edits: checkedReview.edits }));