cornfield 0.41.0 → 0.43.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.
Files changed (45) hide show
  1. package/core/contrast.js +68 -2
  2. package/core/delta-e.js +66 -0
  3. package/core/schema.js +29 -7
  4. package/core/strings.js +11 -0
  5. package/explorer/capped.js +6 -5
  6. package/explorer/cloud-model.js +10 -7
  7. package/explorer/decision-model.js +231 -0
  8. package/explorer/diff-marks.js +3 -1
  9. package/explorer/edge-key.js +59 -0
  10. package/explorer/explorer.css +55 -9
  11. package/explorer/flows.js +0 -2
  12. package/explorer/forge-panel.js +30 -8
  13. package/explorer/glyphs.js +130 -0
  14. package/explorer/house-model.js +2 -2
  15. package/explorer/index.html +7 -18
  16. package/explorer/keyboard-model.js +4 -1
  17. package/explorer/keyboard.js +14 -2
  18. package/explorer/kind-letters.js +9 -5
  19. package/explorer/labels.js +33 -34
  20. package/explorer/layers.js +16 -5
  21. package/explorer/main.js +3 -2
  22. package/explorer/map-style.js +3 -0
  23. package/explorer/panels.js +92 -7
  24. package/explorer/proposal-model.js +24 -0
  25. package/explorer/proposal.js +13 -6
  26. package/explorer/render.js +2 -2
  27. package/explorer/renderer-canvas2d.js +169 -26
  28. package/explorer/renderer-webgl.js +51 -17
  29. package/explorer/review-column.js +22 -4
  30. package/explorer/review.js +413 -44
  31. package/explorer/runs-model.js +1 -1
  32. package/explorer/scene.js +58 -47
  33. package/explorer/selection-model.js +150 -0
  34. package/explorer/selection-view.js +36 -0
  35. package/explorer/shaders.js +76 -13
  36. package/explorer/spatial.js +7 -4
  37. package/explorer/state.js +8 -0
  38. package/explorer/tokens.css +1 -0
  39. package/explorer/whatif.js +84 -7
  40. package/package.json +1 -1
  41. package/server/decision.js +117 -0
  42. package/server/proposal-pulls.js +1 -1
  43. package/server/proposals.js +58 -9
  44. package/server/server.js +19 -2
  45. package/server/submit-review.js +52 -7
@@ -139,6 +139,7 @@
139
139
  --corn-map-glow: auto;
140
140
  /* The smallest a map label is drawn on screen (spec 0008): auto is 11px; a theme may raise it, not lower it. A hub's title is 2px more */
141
141
  --corn-map-label-min: auto;
142
+ --corn-map-glyph: auto;
142
143
  /* Diff, selection and focus */
143
144
  --corn-map-added: auto;
144
145
  --corn-map-changed: auto;
@@ -22,7 +22,8 @@
22
22
 
23
23
  import { state, touchScene, onSceneTouch, nameOf, nodeById, escHtml } from './state.js';
24
24
  import { render, isNodeVisible } from './render.js';
25
- import { hooks, rebuildProposalMap, closeProposal } from './proposal.js';
25
+ import { hooks, rebuildProposalMap, closeProposal, focusChange } from './proposal.js';
26
+ import { t } from './strings.js';
26
27
  import { getPlayer, playScenario, stopScenario, tickScenario } from './scenario-ui.js';
27
28
  import { kindOfMark } from './proposal-model.js';
28
29
  import { announce } from './keyboard.js';
@@ -78,9 +79,33 @@ export function onEditsChange(fn) {
78
79
  return () => listeners.delete(fn);
79
80
  }
80
81
 
82
+ /**
83
+ * The what-if form that is open with something in it, for the decision to ask about before it drops it (spec 0007 D2): `{ name }` or null. The add-node
84
+ * form counts once it has a label or a description, the edge form while it is open (it holds the pair), a new step once it has words.
85
+ */
86
+ export function openFormInfo() {
87
+ if (!state.proposal || !root) return null;
88
+ if (ui.form && ui.form.kind === 'node') {
89
+ const f = q('[data-form="node"]');
90
+ const typed = f && f.elements ? [f.elements.namedItem('label'), f.elements.namedItem('desc')].some((el) => el && String(el.value).trim()) : false;
91
+ return typed ? { name: 'Add a node' } : null;
92
+ }
93
+ if (ui.form && ui.form.kind === 'edge') return { name: 'Draw an edge' };
94
+ if (ui.panel === 'steps' && (ui.stepDraft.trim() || ui.titleDraft.trim())) return { name: 'New step' };
95
+ return null;
96
+ }
97
+
98
+ /** One line for each applied edit, as "Your edits" words them (what a send back keeps readable, spec 0007 D4) */
99
+ export function describeEditsNow() {
100
+ const proposal = state.effectiveProposal || state.proposal;
101
+ const words = { nameOf, scenarioTitle: (id) => (scenariosOf(proposal).find((x) => x.id === id) || { title: id }).title };
102
+ return state.whatIf.edits.map((edit) => M.describeEdit(edit, words));
103
+ }
104
+
81
105
  /** Empties the list and the stored copy (once the edits were sent) and draws the proposal as the robot wrote it */
82
106
  export function clearEdits() {
83
107
  if (!state.proposal) return;
108
+ state.whatIfOff = false; // no edits left to hide
84
109
  apply({ whatIf: M.emptyWhatIf(), effective: state.proposal });
85
110
  }
86
111
 
@@ -88,6 +113,7 @@ function load(proposal) {
88
113
  const key = keyOf();
89
114
  loadedFor = proposal;
90
115
  loadedKey = key;
116
+ state.whatIfOff = false;
91
117
  resetUi();
92
118
  let stored = M.emptyWhatIf();
93
119
  const store = storage();
@@ -105,7 +131,7 @@ function load(proposal) {
105
131
  /** hooks.effective: the proposal the map is drawn from. Loads this proposal's stored edits the first time it is asked about it. */
106
132
  function effectiveFor(proposal) {
107
133
  if (proposal !== loadedFor || keyOf() !== loadedKey) load(proposal);
108
- return M.evaluate(base(), proposal, state.whatIf.edits).effective;
134
+ return state.whatIfOff ? proposal : M.evaluate(base(), proposal, state.whatIf.edits).effective;
109
135
  }
110
136
 
111
137
  hooks.effective = effectiveFor;
@@ -118,6 +144,7 @@ hooks.beforeClose = () => {
118
144
  };
119
145
  hooks.closed = () => {
120
146
  state.whatIf = M.emptyWhatIf();
147
+ state.whatIfOff = false;
121
148
  loadedFor = null;
122
149
  loadedKey = null;
123
150
  resetUi();
@@ -164,8 +191,9 @@ function apply({ whatIf, effective }) {
164
191
  const before = scenariosOf(state.effectiveProposal);
165
192
  state.whatIf = whatIf;
166
193
  save();
167
- rebuildProposalMap(effective);
168
- const sync = M.scenarioSync(state.scenario ? state.scenario.id : null, before, scenariosOf(effective));
194
+ const shown = state.whatIfOff ? state.proposal : effective; // My edits off: the proposal as written, the edits kept
195
+ rebuildProposalMap(shown);
196
+ const sync = M.scenarioSync(state.scenario ? state.scenario.id : null, before, scenariosOf(shown));
169
197
  if (sync.action === 'update') {
170
198
  const player = getPlayer();
171
199
  if (player) { player.setScenario(sync.scenario); tickScenario(performance.now()); }
@@ -185,6 +213,7 @@ const clearMessages = () => { ui.messages = {}; };
185
213
  /** An intent from a control, as an edit: refused with a message next to the control, or applied */
186
214
  function doIntent(intent, where) {
187
215
  if (!state.proposal) return false;
216
+ if (state.whatIfOff) return refuse(where, turnOnWords());
188
217
  const effective = state.effectiveProposal || state.proposal;
189
218
  const taken = new Set([...state.baseNodes.map((n) => n.id), ...asList(effective?.nodes?.add).map((n) => n.id)]);
190
219
  const edit = M.editFromIntent(intent, { takenIds: taken, scenarios: scenariosOf(effective), now: now() });
@@ -193,16 +222,45 @@ function doIntent(intent, where) {
193
222
  if (!result.ok) return refuse(where, result.message);
194
223
  clearMessages();
195
224
  apply(result);
225
+ bringIntoView(edit);
226
+ return true;
227
+ }
228
+
229
+ /** "Turn My edits on to edit.": the tools do nothing while the map is the proposal as written */
230
+ const turnOnWords = () => `Turn ${t('myEdits')} on to edit.`;
231
+
232
+ /**
233
+ * An edit that adds a node or an edge brings it into view, in the part of the map the review column and the panels leave free, and says it once
234
+ * (a new node used to land off screen, issue #166). Other edits move nothing.
235
+ */
236
+ function bringIntoView(edit) {
237
+ if (!edit) return;
238
+ if (edit.op === 'add-node') focusChange('node', edit.id, { select: false });
239
+ else if (edit.op === 'add-edge') focusChange('edge', edgeKey(edit), { select: false });
240
+ }
241
+
242
+ /** The My edits toggle: off draws the proposal as written (the edits are kept, and still go with Approve and Send back); on draws them again */
243
+ export function setMyEdits(on) {
244
+ if (!state.proposal || !M.hasEdits(state.whatIf)) return false;
245
+ state.whatIfOff = !on;
246
+ if (!on) { setDrawing(false); ui.form = null; }
247
+ rebuildProposalMap(on ? M.evaluate(base(), state.proposal, state.whatIf.edits).effective : state.proposal);
248
+ touchScene();
249
+ render();
250
+ renderUi();
251
+ emit();
252
+ const n = state.whatIf.edits.length;
253
+ announce(on ? `${t('myEdits')} on: your ${n === 1 ? 'edit is' : `${n} edits are`} on the map.` : `${t('myEdits')} off: the map shows the proposal as written. Your ${n === 1 ? 'edit is' : `${n} edits are`} kept, and still go with Approve and Send back.`);
196
254
  return true;
197
255
  }
198
256
 
199
257
  export function undoEdit() {
200
- if (!state.proposal || !M.canUndo(state.whatIf)) return false;
258
+ if (!state.proposal || state.whatIfOff || !M.canUndo(state.whatIf)) return false;
201
259
  const edit = state.whatIf.edits[state.whatIf.edits.length - 1];
202
260
  return step(M.undo(state.whatIf), edit, 'Undid');
203
261
  }
204
262
  export function redoEdit() {
205
- if (!state.proposal || !M.canRedo(state.whatIf)) return false;
263
+ if (!state.proposal || state.whatIfOff || !M.canRedo(state.whatIf)) return false;
206
264
  const edit = state.whatIf.undone[state.whatIf.undone.length - 1];
207
265
  return step(M.redo(state.whatIf), edit, 'Redid');
208
266
  }
@@ -217,6 +275,7 @@ function step(whatIf, edit, verb) {
217
275
  }
218
276
 
219
277
  function removeEditAt(index) {
278
+ if (state.whatIfOff) return refuse('edits', turnOnWords());
220
279
  const result = M.tryRemoveEdit(base(), state.proposal, state.whatIf, index);
221
280
  if (!result.ok) return refuse('edits', result.message);
222
281
  clearMessages();
@@ -257,6 +316,8 @@ function mount() {
257
316
  body.appendChild(root);
258
317
  const edit = $('proposal-edit');
259
318
  if (edit) edit.addEventListener('click', () => setEditing(!ui.editing));
319
+ const mine = $('proposal-myedits');
320
+ if (mine) mine.addEventListener('click', () => setMyEdits(!!state.whatIfOff));
260
321
  root.addEventListener('click', onClick);
261
322
  root.addEventListener('submit', onSubmit);
262
323
  root.addEventListener('change', onChange);
@@ -278,6 +339,13 @@ function renderUi() {
278
339
  edit.classList.toggle('hx-btn--active', ui.editing);
279
340
  edit.textContent = state.whatIf.edits.length ? `Edit · ${state.whatIf.edits.length}` : 'Edit';
280
341
  }
342
+ const mine = $('proposal-myedits');
343
+ if (mine) {
344
+ mine.hidden = !open || !M.hasEdits(state.whatIf);
345
+ mine.setAttribute('aria-pressed', String(!state.whatIfOff));
346
+ mine.classList.toggle('hx-btn--active', !state.whatIfOff);
347
+ mine.textContent = t('myEdits');
348
+ }
281
349
  if (!open) { paintDrawer(); return; }
282
350
 
283
351
  const wi = state.whatIf;
@@ -295,6 +363,10 @@ function renderUi() {
295
363
  q('[data-whatif="edits"]').textContent = M.editsLabel(wi.edits.length);
296
364
  const addNode = q('[data-whatif="add-node"]');
297
365
  addNode.classList.toggle('hx-btn--active', ui.form?.kind === 'node');
366
+ // My edits off: the tools say why they do nothing
367
+ for (const btn of q('[data-whatif="add-node"]').parentElement.querySelectorAll('button')) {
368
+ if (state.whatIfOff) btn.setAttribute('aria-disabled', 'true'); else btn.removeAttribute('aria-disabled');
369
+ }
298
370
 
299
371
  const notice = q('[data-notice]');
300
372
  notice.hidden = !ui.notice;
@@ -319,7 +391,7 @@ function setEditing(on) {
319
391
  function paintMessages() {
320
392
  if (!root) return;
321
393
  for (const el of root.querySelectorAll('[data-msg]')) {
322
- const text = ui.messages[el.dataset.msg] || '';
394
+ const text = ui.messages[el.dataset.msg] || (el.dataset.msg === 'toolbar' && state.whatIfOff ? turnOnWords() : '');
323
395
  el.hidden = !text;
324
396
  el.textContent = text;
325
397
  }
@@ -680,10 +752,14 @@ const ACTIONS = {
680
752
  },
681
753
  };
682
754
 
755
+ /** What changes the edits: with My edits off these do nothing and say why */
756
+ const EDITING = new Set(['add-node', 'draw-edge', 'undo', 'redo', 'steps', 'edge-to', 'remove-node', 'remove-edge', 'bring-back', 'remove-edit', 'step-up', 'step-down', 'step-delete']);
757
+
683
758
  function onClick(e) {
684
759
  const el = e.target.closest ? e.target.closest('[data-whatif]') : null;
685
760
  const action = el && ACTIONS[el.dataset.whatif];
686
761
  if (!action || el.disabled) return;
762
+ if (state.whatIfOff && EDITING.has(el.dataset.whatif)) { refuse('toolbar', turnOnWords()); return; }
687
763
  action(el);
688
764
  }
689
765
 
@@ -944,4 +1020,5 @@ export function resetWhatIfForTests() {
944
1020
  listeners.clear();
945
1021
  Object.assign(ui, { editing: false, panel: null, form: null, drawing: false, confirm: false, closing: false, scenarioId: null, stepDraft: '', titleDraft: '', notice: '', messages: {}, recentParents: [], lastSelected: null });
946
1022
  state.whatIf = M.emptyWhatIf();
1023
+ state.whatIfOff = false;
947
1024
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.41.0",
3
+ "version": "0.43.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)",
@@ -0,0 +1,117 @@
1
+ /**
2
+ * @module server/decision
3
+ *
4
+ * The facts the line above Approve is made from (spec 0007 D1): `GET /proposals/<slug>/decision?source=pull/<n>`, for the maintainer
5
+ * who is signed in, like the review routes. The page decides nothing from what it was told earlier; this is the server's answer, and
6
+ * the server's own checks (server/submit-review.js) are the rule whatever the page does with it.
7
+ *
8
+ * { pull: { number, draft, head }, checks: { total, passed, running, failed: [names] } | null,
9
+ * lands: boolean, landing: { by, since } | null, run: null | { kind, transport, runner, lastSeen, quietAfterMs, open, fired } }
10
+ *
11
+ * - `pull`: the PR, read from the forge. A PR that is not open, or that does not hold the proposal, is 404.
12
+ * - `checks`: the checks on the PR's head, counted: `passed` is the ones that finished green (`success`), `running` the queued and running,
13
+ * `failed` the names of the ones that failed or were cancelled (text from the forge: the page sets it as text). `null` when the forge
14
+ * could not list them (the pull is still answered; the line then says it could not read them).
15
+ * - `lands`: `proposals.approveLands` is on; `landing`: a landing is waiting on this PR now (Cancel landing, spec 0007 D3).
16
+ * - `run`: what an approval would ask for, from `agents.on['spec.approved']`, or null. `runner` is `online`, `quiet` (it polled once, not within
17
+ * the window) or `never` on the pull transport (the only one with runners that ask), and null on the forge and push transports. `open` is the
18
+ * id of a run already open on the PR or the proposal, and `fired` says the trigger already asked for a run at this head: either way an approval
19
+ * now asks for none (the trigger skips it), and the line says so.
20
+ *
21
+ * **What it costs** (the idle-cost rule): the page asks when a proposal with a PR opens, every 30 s while it is open and the tab is visible, when
22
+ * the window gets focus and at the end of the hold. Each read is the PR and its checks: two forge calls on Forgejo, three on GitHub (the check runs
23
+ * and the commit status are two calls there), so about 30 in five minutes for one visible tab; the PR's files are kept by head sha like the Specs list's. The answer is kept `FRESH_MS` for the whole server, so two tabs read the forge once; a read asked `fresh` (the end of the
24
+ * hold, where a stale answer could let a decision through) skips the kept one and replaces it. A review posted from cornfield forgets it.
25
+ */
26
+
27
+ import { ForgeError } from './forge.js';
28
+ import { PROPOSAL_FILE } from './files.js';
29
+ import { filesAt, folderOf } from './proposal-pulls.js';
30
+ import path from 'node:path';
31
+
32
+ /** How long a read of a PR and its checks is kept for every tab: under the page's 30 s, so each of its looks is a new read, and two tabs share one */
33
+ export const FRESH_MS = 20_000;
34
+ /** How long a landing waits for its checks, in minutes (server/lander.js TIMEOUT_MS): the line says "marked ready within 60 minutes" */
35
+ export const LAND_WITHIN_MINUTES = 60;
36
+ /** The most checks counted by name in an answer */
37
+ const NAMES_MAX = 20;
38
+
39
+ /** @type {WeakMap<object, Map<number, { at: number, read: Promise<{ pull: import('./forge.js').Pull, checks: import('./forge.js').Check[] | null }> }>>} */
40
+ const kept = new WeakMap();
41
+
42
+ /** Forgets what was read of PR `n` (a review was just posted on it, which can start a landing) */
43
+ export function forgetDecision(where, n) {
44
+ kept.get(where)?.delete(n);
45
+ }
46
+
47
+ /** The PR and the checks on its head, from the forge or from the read kept for every tab */
48
+ function readPull(forge, where, n, { fresh, now }) {
49
+ let byPull = kept.get(where);
50
+ if (!byPull) kept.set(where, (byPull = new Map()));
51
+ const had = byPull.get(n);
52
+ if (had && !fresh && now() - had.at < FRESH_MS) return had.read;
53
+ const read = (async () => {
54
+ const pull = await forge.pull(n);
55
+ let checks = null;
56
+ if (pull.state === 'open' && pull.head.sha) {
57
+ try { checks = await forge.checks(pull.head.sha); } catch { checks = null; } // the pull is still known: the line says the checks could not be read
58
+ }
59
+ return { pull, checks };
60
+ })();
61
+ byPull.set(n, { at: now(), read });
62
+ // A read that failed, or whose checks could not be listed, is not kept: the next look asks again
63
+ const forgetIf = (bad) => { if (bad && byPull.get(n)?.read === read) byPull.delete(n); };
64
+ read.then(({ checks }) => forgetIf(checks === null), () => forgetIf(true));
65
+ return read;
66
+ }
67
+
68
+ /** The checks, counted (see the module's head) */
69
+ export function countChecks(checks) {
70
+ if (!Array.isArray(checks)) return null;
71
+ const failed = checks.filter((c) => c.state === 'failure' || c.state === 'cancelled').map((c) => String(c.name).slice(0, 80));
72
+ return {
73
+ total: checks.length,
74
+ passed: checks.filter((c) => c.state === 'success').length,
75
+ running: checks.filter((c) => c.state === 'queued' || c.state === 'running').length,
76
+ failed: failed.slice(0, NAMES_MAX),
77
+ };
78
+ }
79
+
80
+ /**
81
+ * @param {import('./forge.js').Forge} forge
82
+ * @param {{ proposals: string }} where
83
+ * @param {{ slug: string, n: number, fresh?: boolean, now?: () => number,
84
+ * lands?: boolean, landing?: (n: number) => ({ by: string, since: string } | null) | null,
85
+ * run?: null | { kind: string, transport: string, presence: () => Promise<null | { online: boolean, lastSeen: string | null, quietAfterMs: number }>,
86
+ * already?: (n: number, slug: string, headSha: string) => Promise<{ open: string | null, fired: boolean }> } }} opts
87
+ * @returns {Promise<object>} the answer; throws a ForgeError (`not-found` when the PR is not open or does not hold the proposal)
88
+ */
89
+ export async function readDecision(forge, where, { slug, n, fresh = false, now = Date.now, lands = false, landing = null, run = null }) {
90
+ const { pull, checks } = await readPull(forge, where, n, { fresh, now });
91
+ if (pull.state !== 'open') throw new ForgeError(`Pull request #${n} is not open.`, { code: 'not-found' });
92
+ const folder = folderOf(where);
93
+ const files = await filesAt(forge, where, pull); // kept by head sha, as the Specs list keeps it
94
+ if (!files.some((f) => f.status !== 'removed' && path.posix.dirname(f.path) === folder && PROPOSAL_FILE.exec(path.posix.basename(f.path))?.[1] === slug && !f.path.endsWith('.review.json'))) {
95
+ throw new ForgeError(`Pull request #${n} does not hold the proposal ${slug}.`, { code: 'not-found' });
96
+ }
97
+ let runOut = null;
98
+ if (run) {
99
+ runOut = { kind: run.kind, transport: run.transport, runner: null, lastSeen: null, quietAfterMs: null, open: null, fired: false };
100
+ // An approval asks for no new run while one is open on the PR or the proposal, or when one was asked for at this head already (server/triggers.js)
101
+ if (typeof run.already === 'function') {
102
+ try { Object.assign(runOut, await run.already(n, slug, pull.head.sha)); } catch { /* not known: the line says a run is asked for, as the config does */ }
103
+ }
104
+ if (run.transport === 'pull') {
105
+ const seen = await run.presence();
106
+ if (seen) Object.assign(runOut, { runner: seen.online ? 'online' : seen.lastSeen ? 'quiet' : 'never', lastSeen: seen.lastSeen, quietAfterMs: seen.quietAfterMs });
107
+ }
108
+ }
109
+ const landingNow = landing ? landing(n) : null;
110
+ return {
111
+ pull: { number: n, draft: !!pull.draft, head: pull.head.sha },
112
+ checks: countChecks(checks),
113
+ lands: !!lands,
114
+ landing: landingNow ? { by: landingNow.by, since: landingNow.since } : null,
115
+ run: runOut,
116
+ };
117
+ }
@@ -53,7 +53,7 @@ async function atSha(where, key, read) {
53
53
  }
54
54
 
55
55
  /** The files of a pull request at its head, from the cache when that head was read before */
56
- const filesAt = (forge, where, pull) => atSha(where, `files ${pull.number}@${pull.head.sha}`, () => forge.pullFiles(pull.number));
56
+ export const filesAt = (forge, where, pull) => atSha(where, `files ${pull.number}@${pull.head.sha}`, () => forge.pullFiles(pull.number));
57
57
 
58
58
  /** `pull/<n>` for a pull request's proposals */
59
59
  export const pullSource = (n) => `pull/${n}`;
@@ -45,8 +45,10 @@ import path from 'node:path';
45
45
  import { findProposalFile, listProposalFiles } from './files.js';
46
46
  import { summarize, proposalProblems } from '../core/proposal.js';
47
47
  import { ForgeError } from './forge.js';
48
- import { REVIEW_LIMIT, latestReview, migrateStage1Reviews } from './reviews.js';
49
- import { submitReview, refusal } from './submit-review.js';
48
+ import { REVIEW_LIMIT, latestReview, migrateStage1Reviews, proposalHash } from './reviews.js';
49
+ import { submitReview, refusal, standsApproved, stillLanding } from './submit-review.js';
50
+ import { hashPullMockups } from './mockups.js';
51
+ import { readDecision } from './decision.js';
50
52
  import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal, reviewStates } from './proposal-pulls.js';
51
53
  import { serveMockups } from './mockups.js';
52
54
 
@@ -237,19 +239,38 @@ async function servePull(res, where, forgeFor, slug, source) {
237
239
  } catch (err) {
238
240
  return send(res, 422, { error: `Not valid JSON: ${err.message}` });
239
241
  }
240
- return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
242
+ // The file's SHA-256 as served: the page sends it back with a review, so a push that changed the file since is refused, not approved unseen
243
+ return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source), 'X-Proposal-Sha256': proposalHash(text) });
241
244
  }
242
245
 
243
246
  /** The words for a refusal of the forge: the status to answer with, and what to say */
244
247
  const forgeStatus = (err) => (err instanceof ForgeError ? (err.code === 'not-found' ? 404 : err.code === 'invalid' ? 400 : 502) : 500);
245
248
 
246
249
  /** GET /proposals/<slug>/review?source=pull/<n>: the latest admin comment's review, or 404 */
247
- async function getPullReview(res, where, forgeFor, slug, n) {
250
+ async function getPullReview(res, where, forgeFor, slug, n, lander = null) {
248
251
  try {
249
252
  const forge = forgeFor();
250
- if (!(await findPullProposal(forge, where, slug, n))) return send(res, 404, { error: 'No such proposal' });
253
+ const entry = await findPullProposal(forge, where, slug, n);
254
+ if (!entry) return send(res, 404, { error: 'No such proposal' });
251
255
  const found = await latestReview(forge, n, slug);
252
- return found ? send(res, 200, found) : send(res, 404, { error: 'No review yet' });
256
+ if (!found) return send(res, 404, { error: 'No review yet' });
257
+ // An approval says whether approving again would do nothing (`current`): it is of the file and its mockups as the head holds them now and,
258
+ // with landing on approval, a landing waits at this head. The Approve button reads Approved only then (spec 0007 D2); a push that changes the
259
+ // proposal, or (with landing on approval) any push, a cancelled landing or one left open, makes it live again
260
+ const current = found.verdict === 'approved'
261
+ ? standsApproved(found, proposalHash(await readPullProposal(forge, where, entry)), await hashPullMockups(forge, where, entry)) && (!lander || stillLanding(lander, n, entry.sha))
262
+ : undefined;
263
+ return send(res, 200, current === undefined ? found : { ...found, current });
264
+ } catch (err) {
265
+ return send(res, forgeStatus(err), { error: forgeWords(err) });
266
+ }
267
+ }
268
+
269
+ /** GET /proposals/<slug>/decision?source=pull/<n>[&fresh=1]: the facts the line above Approve is made from (server/decision.js) */
270
+ async function getDecision(res, where, forgeFor, signedIn, slug, n, fresh) {
271
+ try {
272
+ const answer = await readDecision(forgeFor(), where, { slug, n, fresh, now: signedIn.limits?.now, ...(signedIn.decision || {}) });
273
+ return send(res, 200, answer, { 'Cache-Control': 'no-store' });
253
274
  } catch (err) {
254
275
  return send(res, forgeStatus(err), { error: forgeWords(err) });
255
276
  }
@@ -276,11 +297,19 @@ async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
276
297
  }
277
298
  // What an approval covers is the server's to record, from the files themselves, never the page's word
278
299
  if (parsed !== null && typeof parsed === 'object' && ('mockups' in parsed || 'proposal' in parsed)) return send(res, 400, { error: 'What an approval covers (the proposal and its mockups) is recorded by the server; a review does not send it.' });
300
+ // What the page was shown (spec 0007): the proposal file's SHA-256 (`sha256`, from X-Proposal-Sha256) and the PR's head commit (`headSha`, from the
301
+ // decision's facts). Each is optional; named, a head that holds another is refused (409), so what posts is what was on screen at the press
302
+ let review = parsed;
303
+ let sha256 = null;
304
+ let headSha = null;
305
+ if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) && ('sha256' in parsed || 'headSha' in parsed)) {
306
+ ({ sha256 = null, headSha = null, ...review } = parsed);
307
+ }
279
308
  try {
280
309
  // The checks and the post are submitReview's, shared with the review API (server/submit-review.js)
281
310
  const found = await submitReview({
282
311
  forge: forgeFor, where, repo: signedIn.repo, who: { login: signedIn.login, userId: signedIn.userId }, record: signedIn.record, limits: signedIn.limits, hooks: signedIn.hooks, lander: signedIn.lander,
283
- }, { pull: n, slug, review: parsed });
312
+ }, { pull: n, slug, review, sha256, headSha });
284
313
  return send(res, 200, found);
285
314
  } catch (err) {
286
315
  const out = refusal(err);
@@ -304,6 +333,25 @@ async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
304
333
  export function serveProposals(req, res, reqPath, url, where, forgeFor = null, signedIn = null) {
305
334
  if (reqPath !== '/proposals' && !reqPath.startsWith('/proposals/')) return false;
306
335
 
336
+ // What Approve would do in this state (spec 0007 D1): read-only, for the signed-in maintainer, only for a proposal of a spec PR
337
+ const decision = /^\/proposals\/([^/]+)\/decision$/.exec(reqPath);
338
+ if (decision) {
339
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
340
+ req.resume();
341
+ send(res, 405, { error: 'The facts of a decision are read with GET' }, { Allow: 'GET, HEAD' });
342
+ return true;
343
+ }
344
+ const n = forgeFor && signedIn ? pullNumber(url.searchParams.get('source')) : null;
345
+ if (n === null || !forgeFor || !signedIn) {
346
+ send(res, 404, { error: 'A decision is about a spec PR: this proposal is not on one (or you are not signed in).' });
347
+ return true;
348
+ }
349
+ getDecision(res, where, forgeFor, signedIn, decision[1], n, url.searchParams.get('fresh') === '1').catch(() => {
350
+ if (!res.headersSent) send(res, 500, { error: 'The decision could not be read' });
351
+ });
352
+ return true;
353
+ }
354
+
307
355
  // The review of one proposal: a comment on its spec PR, the only thing here that can be written
308
356
  const review = /^\/proposals\/([^/]+)\/review$/.exec(reqPath);
309
357
  if (review) {
@@ -320,7 +368,7 @@ export function serveProposals(req, res, reqPath, url, where, forgeFor = null, s
320
368
  });
321
369
  } else if (req.method === 'GET' || req.method === 'HEAD') {
322
370
  if (n !== null && forgeFor) {
323
- getPullReview(res, where, forgeFor, slug, n).catch(() => {
371
+ getPullReview(res, where, forgeFor, slug, n, signedIn?.lander ?? null).catch(() => {
324
372
  if (!res.headersSent) send(res, 500, { error: 'The review could not be read' });
325
373
  });
326
374
  } else {
@@ -389,5 +437,6 @@ async function serveFile(res, where, forgeFor, slug, source) {
389
437
  } catch (err) {
390
438
  return send(res, 422, { error: `Not valid JSON: ${err.message}` });
391
439
  }
392
- return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source) });
440
+ // The file's SHA-256 as served: the page sends it back with a review, so a push that changed the file since is refused, not approved unseen
441
+ return send(res, 200, text, { 'X-Proposal-Source': encodeURIComponent(entry.source), 'X-Proposal-Sha256': proposalHash(text) });
393
442
  }
package/server/server.js CHANGED
@@ -74,7 +74,7 @@ import { createAuth, signInSettings } from './auth.js';
74
74
  import { createHooks, hooksSettings } from './hooks.js';
75
75
  import { createLander } from './lander.js';
76
76
  import { createSpecPoll } from './spec-poll.js';
77
- import { createRunnerWatch } from './runner-presence.js';
77
+ import { createRunnerWatch, runnerPresence } from './runner-presence.js';
78
78
  import { createTriggers } from './triggers.js';
79
79
  import { brandHead, escapeHtml, themeHead, themeHtmlTag } from './page-head.js';
80
80
  import { compressResponse } from './compress.js';
@@ -310,13 +310,30 @@ export function createCornfieldServer(config, opts = {}) {
310
310
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
311
311
  const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
312
312
  const fixtureCache = new Map();
313
+ // What the line above Approve says an approval does besides posting (spec 0007 D1, server/decision.js): landing, and the run a trigger asks for
314
+ const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
315
+ const decisionFacts = {
316
+ lands: !!config.approveLands,
317
+ landing: null,
318
+ run: approvalRun ? { kind: approvalRun[1].kind, transport: config.agents?.transport ?? 'forge', presence: async () => runnerPresence(await auth.store(), (opts.now ?? Date.now)(), runnerQuietAfterMs(config)) } : null,
319
+ };
313
320
  const lander = config.approveLands ? createLander({ config, where, auth, hooks, now: opts.now, timer: opts.landTimer }) : null;
314
321
  if (lander) {
322
+ decisionFacts.landing = (n) => lander.pending(n);
315
323
  // What a restart left waiting: looked at again, in the background
316
324
  lander.resume().catch((err) => console.error(`[cornfield] pending landings could not be picked up: ${err instanceof Error ? err.message : err}`));
317
325
  }
318
326
  // Agent runs (server/agent-runs.js) need a signed-in maintainer to ask as and a forge to ask on; the runs are followed on the spec poll's tick
319
327
  const runs = config.forge && auth.enabled && hasAdapter(config.forge.type) ? createRuns({ config, where, auth, hooks, now: opts.now, onAsk: () => specPoll?.start() }) : null;
328
+ // Whether an approval now would ask for a run at all (server/triggers.js): not while a run is open on the PR or the proposal (`run-open`), and
329
+ // not twice for one head (the trigger fires once per head). The line above Approve says so instead of promising a run that will be skipped
330
+ if (decisionFacts.run && runs) {
331
+ decisionFacts.run.already = async (n, slug, headSha) => {
332
+ const open = await runs.openOn({ number: n, refs: { proposal: slug } });
333
+ const fired = !!(await auth.store()).prepare('SELECT 1 FROM thread_seen WHERE repo = ? AND issue = ? AND comment = ?').get(config.forge.repo, n, `trigger:spec.approved:${headSha ?? ''}`);
334
+ return { open: open || null, fired };
335
+ };
336
+ }
320
337
  // Push and pull need the same two things a request on the forge does (a maintainer's sign-in to ask as, a forge to check against), and push needs the hook that delivers it
321
338
  const transport = config.agents?.transport ?? 'forge';
322
339
  if (transport !== 'forge' && !runs) throw new Error(`agents.transport is "${transport}", which needs sign-in and a forge to ask as a maintainer and to check them: set them up (docs/sign-in.md, docs/config.md#forge).`);
@@ -451,7 +468,7 @@ export function createCornfieldServer(config, opts = {}) {
451
468
  for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
452
469
  const session = gate.session;
453
470
  const forgeFor = session ? () => auth.forgeFor(session) : null;
454
- const reviewer = session ? { login: session.login, userId: session.userId, repo: config.forge.repo, record: (entry) => auth.record(entry), limits: { auth, now: opts.now }, hooks, lander } : null;
471
+ const reviewer = session ? { login: session.login, userId: session.userId, repo: config.forge.repo, record: (entry) => auth.record(entry), limits: { auth, now: opts.now }, hooks, lander, decision: decisionFacts } : null;
455
472
  if (serveProposals(req, res, reqPath, url, where, forgeFor, reviewer)) return;
456
473
 
457
474
  if (req.method !== 'GET' && req.method !== 'HEAD') {
@@ -18,10 +18,16 @@
18
18
  * remembered 15 minutes ago; a different person, or one who is no longer a maintainer, is 403
19
19
  * 6. the PR is open and holds the proposal (404)
20
20
  * 7. the proposal file's SHA-256 at the PR's head: when the caller names the version it read (`sha256`; the API
21
- * requires it) and the head holds another, 409, so a review counts only for the version that was read. An
22
- * approval records the head's hash (`proposal`) and its mockups' (`mockups`), as the server read them, never the caller's word
21
+ * requires it, the button sends the one it was shown) and the head holds another, 409, so a review counts only for the
22
+ * version that was read. The button also names the PR's head commit it was shown (`headSha`): another head now is 409 too,
23
+ * so an approval never covers (or lands) a push the maintainer did not see. An approval records the head's hash
24
+ * (`proposal`) and its mockups' (`mockups`), as the server read them, never the caller's word
23
25
  * 8. with the API, the token once more (`stillAllowed`): one revoked or expired while the forge was being asked is 403
24
- * 9. the comment is posted as that person (`postReview`)
26
+ * 9. a repeat (spec 0007: a second tab, a retried call): the same approval, by the same person, of the same version, that
27
+ * already stands as the latest review, and would start nothing new (no landing on approval, or one already waiting at this
28
+ * head) is answered 200 with the review that stands and `"posted": false`, and nothing is posted or fired. Anything else
29
+ * (another maintainer, another note or edits, a landing that was cancelled or left open) is posted as before
30
+ * 10. the comment is posted as that person (`postReview`)
25
31
  *
26
32
  * Every attempt that gets past step 1 is a row in `actions` (`record`), whatever the answer: a posted review and a forge
27
33
  * that refused it are written by `postReview`, every refusal before that here. The audit never holds a token's secret,
@@ -38,7 +44,8 @@ import { ForgeError, isMaintainer } from './forge.js';
38
44
  import { PROPOSAL_FILE } from './files.js';
39
45
  import { findPullProposal, forgeWords, forgetReviewState, readPullProposal } from './proposal-pulls.js';
40
46
  import { hashPullMockups } from './mockups.js';
41
- import { postReview, proposalHash, validateReview } from './reviews.js';
47
+ import { latestReview, postReview, proposalHash, validateReview } from './reviews.js';
48
+ import { forgetDecision } from './decision.js';
42
49
  import { Refused, countAttempt, throttle } from './throttle.js';
43
50
  import { proposalPayload } from './hooks.js';
44
51
 
@@ -71,7 +78,7 @@ const MAX_PULL = 999_999_999;
71
78
  * JSON, it was too large): it is refused here, after the flood count and with a row, like every other refusal
72
79
  * @returns {Promise<import('./reviews.js').FoundReview>}
73
80
  */
74
- export async function submitReview(ctx, { pull, slug, review, sha256 = null, problem }) {
81
+ export async function submitReview(ctx, { pull, slug, review, sha256 = null, headSha = null, problem }) {
75
82
  const { who, repo, via } = ctx;
76
83
  const now = ctx.limits.now ?? Date.now;
77
84
  const validPull = typeof pull === 'number' && Number.isInteger(pull) && pull >= 1 && pull <= MAX_PULL;
@@ -79,7 +86,7 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
79
86
  // What the audit row says was asked: only what is small, plain and of the right shape, never the whole body
80
87
  // A slug or a hash only when it has the shape of one: anything else the caller sent is not kept (it could be a secret pasted in the wrong field)
81
88
  const slugShown = typeof slug === 'string' && slug.length <= 200 && PROPOSAL_FILE.test(`${slug}.json`) ? slug : undefined;
82
- const asked = /** @type {Record<string, unknown>} */ ({ slug: slugShown, pull: validPull ? pull : undefined, ...(isSha256(sha256) ? { sha256 } : {}), ...(via ? { via: 'api', token: via.token } : {}) });
89
+ const asked = /** @type {Record<string, unknown>} */ ({ slug: slugShown, pull: validPull ? pull : undefined, ...(isSha256(sha256) ? { sha256 } : {}), ...(isCommit(headSha) ? { headSha: headSha.toLowerCase() } : {}), ...(via ? { via: 'api', token: via.token } : {}) });
83
90
 
84
91
  const flood = countAttempt(ctx.limits, who.userId, now());
85
92
  if (flood) throw flood;
@@ -97,6 +104,7 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
97
104
  if ((sha256 !== null && sha256 !== undefined) || ctx.requireSha256) {
98
105
  if (!isSha256(sha256)) throw new Refused(400, 'Say which version you read: "sha256" is the proposal file\'s SHA-256, 64 lower-case hex digits.', 'invalid');
99
106
  }
107
+ if (headSha !== null && headSha !== undefined && !isCommit(headSha)) throw new Refused(400, 'Say which head you were shown: "headSha" is a commit\'s SHA, 40 or 64 hex digits.', 'invalid');
100
108
  release = throttle(ctx.limits, who.userId, `review|${pull}|${slug}`, now());
101
109
 
102
110
  if (review !== null && typeof review === 'object') {
@@ -110,13 +118,14 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
110
118
  const forge = await ctx.forge();
111
119
  const me = await forge.me();
112
120
  if (String(me.id) !== who.userId) throw new Refused(403, 'The forge says this sign-in is someone else now; sign in again.', 'forbidden');
113
- if (!isMaintainer(await forge.permission(repo, me.login))) throw new Refused(403, `Only the repo's maintainers review proposals; ${me.login} is not one now.`, 'forbidden');
121
+ if (!isMaintainer(await forge.permission(repo, me.login))) throw new Refused(403, `${me.login} no longer maintains this repo, so the forge would not count the review.`, 'forbidden');
114
122
 
115
123
  const entry = await findPullProposal(forge, ctx.where, slug, pull);
116
124
  if (!entry) throw new Refused(404, `Pull request #${pull} is not open or does not hold the proposal ${slug}.`, 'not-found');
117
125
  // The proposal as the head holds it now: a later push that changes it is not this review's
118
126
  const head = proposalHash(await readPullProposal(forge, ctx.where, entry));
119
127
  if (typeof sha256 === 'string' && sha256 !== head) throw new Refused(409, `${slug} has changed since you read it (the head of pull request #${pull} holds ${head.slice(0, 12)}…, not ${sha256.slice(0, 12)}…); read it again and review that version.`, 'conflict');
128
+ if (typeof headSha === 'string' && headSha.toLowerCase() !== String(entry.sha).toLowerCase()) throw new Refused(409, `Pull request #${pull} was pushed to since you looked (its head is ${String(entry.sha).slice(0, 7)} now, not ${headSha.slice(0, 7)}); nothing was posted. Look at it again, then review that.`, 'conflict');
120
129
 
121
130
  let checkedReview = checked.value;
122
131
  if (checkedReview.verdict === 'approved') {
@@ -129,8 +138,18 @@ export async function submitReview(ctx, { pull, slug, review, sha256 = null, pro
129
138
  const why = await ctx.stillAllowed();
130
139
  if (why) throw new Refused(403, why, 'forbidden');
131
140
  }
141
+ // A repeat (step 9): this person's approval of this version stands already, and posting it again would start nothing new. The answer is
142
+ // the review that stands, with nothing posted, no hook fired and no landing begun; it is a row in the audit table like every attempt.
143
+ if (checkedReview.verdict === 'approved') {
144
+ const standing = await latestReview(forge, pull, slug);
145
+ if (isRepeat(standing, checkedReview, me.login) && (!ctx.lander || stillLanding(ctx.lander, pull, entry.sha))) {
146
+ await record({ login: me.login, action: 'review', target, request: asked, status: 200, answer: { posted: false, comment: standing.comment?.id ?? null } });
147
+ return { ...standing, posted: false };
148
+ }
149
+ }
132
150
  const posted = await postReview(forge, pull, slug, checkedReview, { login: me.login, record, via });
133
151
  forgetReviewState(ctx.where, pull); // the listing's review state for this PR is read again (spec 0010)
152
+ forgetDecision(ctx.where, pull); // and the line above Approve: an approval can start a landing
134
153
  // The one place a review is posted, so the button and the API fire the same event; the actor is who the forge says
135
154
  // the poster is (with the API, the token's owner), never a name the caller sent
136
155
  ctx.hooks?.emit(posted.verdict === 'approved' ? 'spec.approved' : 'spec.sentBack', () => proposalPayload(forge, ctx.where, entry, { actor: me.login, note: checkedReview.note, edits: checkedReview.edits }));
@@ -174,5 +193,31 @@ export function refusal(err) {
174
193
  return { status: 500, body: { error: 'The review could not be saved; the log says why.', code: 'unavailable' }, headers: {} };
175
194
  }
176
195
 
196
+ /**
197
+ * Whether `review`, about to be posted by `login`, says nothing that the review standing does not already say: the same person's approval of
198
+ * the same version (the file and its mockups as the head holds them), with the same note and edits.
199
+ * @param {import('./reviews.js').FoundReview | null} standing
200
+ * @param {import('./reviews.js').Review} review the checked approval, with what the server recorded it covers
201
+ * @param {string} login
202
+ */
203
+ export function isRepeat(standing, review, login) {
204
+ if (!standing || standing.by !== login || !standsApproved(standing, review.proposal, review.mockups ?? [])) return false;
205
+ return (standing.note ?? '') === (review.note ?? '') && JSON.stringify(standing.edits ?? []) === JSON.stringify(review.edits ?? []);
206
+ }
207
+
208
+ /** Whether a landing on approval already waits on PR `n` at this head (so an approval again would begin nothing new) */
209
+ export const stillLanding = (lander, n, sha) => String(lander.pending(n)?.sha ?? '').toLowerCase() === String(sha).toLowerCase();
210
+
211
+ /**
212
+ * Whether a review that stands is an approval of exactly this: the proposal file as the head holds it and its mockups (what an approval covers).
213
+ * @param {import('./reviews.js').FoundReview | null} standing
214
+ * @param {string} head the proposal file's SHA-256 at the head
215
+ * @param {{ node: string, path: string, sha256: string }[]} mockups the mockups as the head holds them
216
+ */
217
+ export const standsApproved = (standing, head, mockups) => !!standing && standing.verdict === 'approved' && standing.proposal === head && JSON.stringify(standing.mockups ?? []) === JSON.stringify(mockups);
218
+
219
+ /** A commit's SHA as a caller names it: 40 hex digits (SHA-1) or 64 (SHA-256 repositories) */
220
+ export const isCommit = (v) => typeof v === 'string' && /^(?:[0-9a-fA-F]{40}|[0-9a-fA-F]{64})$/.test(v);
221
+
177
222
  /** The checks on a `sha256` the caller names: 64 lower-case hex digits */
178
223
  export const isSha256 = (v) => typeof v === 'string' && SHA256.test(v);