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
package/core/contrast.js CHANGED
@@ -23,7 +23,8 @@ import path from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
  import { MAX_MIX_DEPTH, readColor, over, toHex, luminance, ratio, splitTop } from './color.js';
25
25
  import { MAX_THEME_BYTES, cssProblems, withoutComments } from './theme.js';
26
- import { NODE_THEMES } from './schema.js';
26
+ import { MIN_SHAPE_DELTA_E, NODE_SHAPES, NODE_THEMES } from './schema.js';
27
+ import { deltaE2000 } from './delta-e.js';
27
28
  import { LAYER_KEY_RE, MAX_KEY, parseKindToken } from './layers.js';
28
29
  import { DIFF_MARK_COLORS, DIFF_LABEL_ALPHA, markOpacity } from '../explorer/diff-marks.js';
29
30
  import { lightColor } from '../explorer/theme-model.js';
@@ -381,6 +382,7 @@ export const PAINTED_TEXT = Object.freeze([
381
382
  ['--corn-bad', tint('--corn-removed', 12), 'a What-if or review message'],
382
383
  ['--corn-bad', tint('--corn-removed', 16), 'a refused check'],
383
384
  ['--corn-warn', tint('--corn-changed', 16), 'a mismatched check'],
385
+ ['--corn-text', tint('--corn-warn', 14), 'the question Approve asks in place (spec 0007)'],
384
386
  ['--corn-text-2', tint('--corn-text-3', 12), 'a verdict, a cloud badge'], ['--corn-text-3', tint('--corn-text-3', 12), 'a cloud plan not known'],
385
387
  ['--corn-text-2', tint('--corn-text-3', 10), 'a check'],
386
388
  ['--corn-text-2', tint('--corn-text-2', 12), 'a web badge'],
@@ -554,6 +556,18 @@ function mapFindings(props, theme, mode, grounds, extra = []) {
554
556
  out.push({ ...base, fg: '--corn-map-stroke', bg: weakest.on, min: MAP_FILL_MIN, kind: 'ui', use: `the outline that carries the fill of ${anOf(label)} ${label} node, which is ${fmt(f.ratio)} on its own`, fgValue: onGround.fgValue, bgValue: weakest.value, ratio: weakest.r });
555
557
  }
556
558
  }
559
+ // The ink of a glyph and of a finer kind's letters (spec 0008 D8), when the theme sets one: against every fill it can sit on (`auto` picks white or dark per fill, which a test holds)
560
+ const glyph = mapToken(props, '--corn-map-glyph');
561
+ if (glyph.problem) out.push({ ...base, fg: '--corn-map-glyph', bg: GROUND, min: MAP_FILL_MIN, kind: 'ui', use: 'the ink of a node\'s glyph', problem: glyph.problem });
562
+ else if (glyph.color) {
563
+ for (const type of Object.keys(NODE_THEMES)) {
564
+ const fill = mapFillOf(props, type, mode);
565
+ if (!fill || !isColor(fill.color)) continue;
566
+ const bg = over(fill.color, ground);
567
+ const ink = over(glyph.color, bg);
568
+ out.push({ ...base, fg: '--corn-map-glyph', bg: fill.name, min: MAP_FILL_MIN, kind: 'ui', use: `the glyph on ${anOf(type)} ${type} node`, fgValue: toHex(ink), bgValue: toHex(bg), ratio: ratio(luminance(ink), luminance(bg)) });
569
+ }
570
+ }
557
571
  // The tokens a theme sets for a finer kind (`--corn-map-kind-<type>-<kind>`) and a project layer (`--corn-map-group-<key>`): the same fill
558
572
  // check, for each one the theme sets (an `auto` one draws the type's own colour, which is checked above)
559
573
  for (const name of extra) {
@@ -726,6 +740,56 @@ export function mapExtraTokens(sheets) {
726
740
  return [...declaredProps(sheets)].filter((n) => parseKindToken(n) || projectGroupOf(n)).sort();
727
741
  }
728
742
 
743
+ // ---------------------------------------------------------------------------
744
+ // The map's palette (spec 0008 D8): types that share a silhouette are told apart by colour alone, so they are kept apart
745
+ // ---------------------------------------------------------------------------
746
+
747
+ /** The colour a type's node is drawn in for one page state: its token, else its group's, else its own from core/schema.js (deepened on the light ground); null when it cannot be read */
748
+ function mapFillOf(props, type, mode) {
749
+ for (const group of MAP_GROUPS_OF(type)) {
750
+ for (const name of [`--corn-map-node-${type}`, `--corn-map-group-${group}`]) {
751
+ const t = mapToken(props, name);
752
+ if (t.color) return { color: t.color, name };
753
+ if (t.problem) return null;
754
+ }
755
+ }
756
+ return { color: readColor(mode === 'light' ? lightColor(NODE_THEMES[type].color) : NODE_THEMES[type].color), name: `--corn-map-node-${type}` };
757
+ }
758
+
759
+ /**
760
+ * The pairs of node types that share a silhouette and are under MIN_SHAPE_DELTA_E apart (CIEDE2000) in one theme, on the dark ground and the light.
761
+ * The default palette has none (a test holds it); a theme that sets map colours may.
762
+ * @param {{ theme: string, sheets: string[], name?: string }[]} themes
763
+ * @returns {{ theme: string, mode: string, a: string, b: string, shape: string, deltaE: number }[]}
764
+ */
765
+ export function paletteProblems(themes) {
766
+ const out = [];
767
+ for (const { theme, sheets, name } of themes) {
768
+ for (const mode of ['light', 'dark']) {
769
+ const props = resolveProps(sheets, { mode, system: mode, name });
770
+ const types = Object.keys(NODE_SHAPES).filter((t) => Object.hasOwn(NODE_THEMES, t));
771
+ const fills = new Map(types.map((t) => [t, mapFillOf(props, t, mode)]));
772
+ for (let i = 0; i < types.length; i++) {
773
+ for (let j = i + 1; j < types.length; j++) {
774
+ const [a, b] = [types[i], types[j]];
775
+ if (NODE_SHAPES[a] !== NODE_SHAPES[b]) continue;
776
+ const [fa, fb] = [fills.get(a), fills.get(b)];
777
+ if (!fa || !fb || !isColor(fa.color) || !isColor(fb.color)) continue;
778
+ const d = deltaE2000(fa.color.slice(0, 3), fb.color.slice(0, 3));
779
+ if (d < MIN_SHAPE_DELTA_E) out.push({ theme, mode, a, b, shape: NODE_SHAPES[a], deltaE: d, tokens: [fa.name, fb.name] });
780
+ }
781
+ }
782
+ }
783
+ }
784
+ return out;
785
+ }
786
+
787
+ /** One line for a palette finding: the two types, their tokens and how far apart they are */
788
+ export function describePalette(f) {
789
+ const who = f.theme === 'standard' ? 'standard theme' : `named theme "${f.theme}"`;
790
+ return `${who} (${f.mode}): ${f.a} (${f.tokens[0]}) and ${f.b} (${f.tokens[1]}) share the ${f.shape} silhouette and are ΔE ${f.deltaE.toFixed(1)} apart, under ${MIN_SHAPE_DELTA_E}: the map tells them apart by colour alone, so give one of them a colour further from the other.`;
791
+ }
792
+
729
793
  /** The pairs under their minimum: { fails, unresolved } */
730
794
  export function contrastProblems(themes) {
731
795
  const all = checkSheets(themes);
@@ -804,5 +868,7 @@ export function checkThemeContrast(config) {
804
868
  const lines = fails.map((f) => `theme contrast: ${describeFinding(f)}`);
805
869
  const warnings = unresolved.map((f) => `theme contrast: ${describeFinding(f)}`);
806
870
  const summary = contrastSummary(themes, total, fails.length, unresolved.length);
807
- return (config.theme || {}).contrast === 'warn' ? { errors: [], warnings: [...lines, ...warnings], summary } : { errors: lines, warnings, summary };
871
+ // Types of one silhouette too close in colour (spec 0008 D8): a warning, never an error: a brand picks its own colours
872
+ const palette = paletteProblems(themes).map((f) => `theme map colours: ${describePalette(f)}`);
873
+ return (config.theme || {}).contrast === 'warn' ? { errors: [], warnings: [...lines, ...warnings, ...palette], summary } : { errors: lines, warnings: [...warnings, ...palette], summary };
808
874
  }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @module core/delta-e
3
+ *
4
+ * Colour distance as the eye reads it: CIEDE2000 (ΔE00, Sharma, Wu and Dalal 2005) between two sRGB colours. Pure, no imports. The map holds the
5
+ * built-in palette to it (core/schema.js `MIN_SHAPE_DELTA_E`, spec 0008 D8): two node types that share a silhouette are told apart by colour,
6
+ * so their colours must be far enough apart to be.
7
+ */
8
+
9
+ const toLinear = (c) => { const v = c / 255; return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; };
10
+
11
+ /** sRGB `[r, g, b]` (0..255) to CIE L*a*b* under D65 */
12
+ export function toLab([r, g, b]) {
13
+ const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)];
14
+ const x = (0.4124564 * lr + 0.3575761 * lg + 0.1804375 * lb) / 0.95047;
15
+ const y = 0.2126729 * lr + 0.7151522 * lg + 0.072175 * lb;
16
+ const z = (0.0193339 * lr + 0.119192 * lg + 0.9503041 * lb) / 1.08883;
17
+ const f = (t) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27 * t + 16) / 116);
18
+ const [fx, fy, fz] = [f(x), f(y), f(z)];
19
+ return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];
20
+ }
21
+
22
+ const rad = (d) => (d * Math.PI) / 180;
23
+ const deg = (r) => (r * 180) / Math.PI;
24
+
25
+ /** CIEDE2000 between two L*a*b* colours */
26
+ export function deltaE2000Lab(lab1, lab2) {
27
+ const [L1, a1, b1] = lab1;
28
+ const [L2, a2, b2] = lab2;
29
+ const C1 = Math.hypot(a1, b1);
30
+ const C2 = Math.hypot(a2, b2);
31
+ const Cbar = (C1 + C2) / 2;
32
+ const G = 0.5 * (1 - Math.sqrt(Cbar ** 7 / (Cbar ** 7 + 25 ** 7)));
33
+ const a1p = (1 + G) * a1;
34
+ const a2p = (1 + G) * a2;
35
+ const C1p = Math.hypot(a1p, b1);
36
+ const C2p = Math.hypot(a2p, b2);
37
+ const hp = (b, a) => (b === 0 && a === 0 ? 0 : (deg(Math.atan2(b, a)) + 360) % 360);
38
+ const h1p = hp(b1, a1p);
39
+ const h2p = hp(b2, a2p);
40
+ const dLp = L2 - L1;
41
+ const dCp = C2p - C1p;
42
+ let dhp = 0;
43
+ if (C1p * C2p !== 0) {
44
+ dhp = h2p - h1p;
45
+ if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360;
46
+ }
47
+ const dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(rad(dhp / 2));
48
+ const Lbp = (L1 + L2) / 2;
49
+ const Cbp = (C1p + C2p) / 2;
50
+ let hbp = h1p + h2p;
51
+ if (C1p * C2p !== 0) {
52
+ if (Math.abs(h1p - h2p) <= 180) hbp /= 2;
53
+ else hbp = (h1p + h2p < 360 ? hbp + 360 : hbp - 360) / 2;
54
+ }
55
+ const T = 1 - 0.17 * Math.cos(rad(hbp - 30)) + 0.24 * Math.cos(rad(2 * hbp)) + 0.32 * Math.cos(rad(3 * hbp + 6)) - 0.2 * Math.cos(rad(4 * hbp - 63));
56
+ const dTheta = 30 * Math.exp(-(((hbp - 275) / 25) ** 2));
57
+ const Rc = 2 * Math.sqrt(Cbp ** 7 / (Cbp ** 7 + 25 ** 7));
58
+ const Sl = 1 + (0.015 * (Lbp - 50) ** 2) / Math.sqrt(20 + (Lbp - 50) ** 2);
59
+ const Sc = 1 + 0.045 * Cbp;
60
+ const Sh = 1 + 0.015 * Cbp * T;
61
+ const Rt = -Math.sin(rad(2 * dTheta)) * Rc;
62
+ return Math.sqrt((dLp / Sl) ** 2 + (dCp / Sc) ** 2 + (dHp / Sh) ** 2 + Rt * (dCp / Sc) * (dHp / Sh));
63
+ }
64
+
65
+ /** CIEDE2000 between two sRGB colours given as `[r, g, b]` (0..255) */
66
+ export const deltaE2000 = (rgb1, rgb2) => deltaE2000Lab(toLab(rgb1), toLab(rgb2));
package/core/schema.js CHANGED
@@ -12,20 +12,20 @@ export const DERIVED_FLOW = 'api';
12
12
 
13
13
  export const NODE_THEMES = {
14
14
  root: { color: '#f59e0b', r: 28 },
15
- app: { color: '#6366f1', r: 24 },
15
+ app: { color: '#5168ec', r: 24 },
16
16
  page: { color: '#38bdf8', r: 18 }, // Mandatory Sky Blue for all pages
17
- pkg: { color: '#06b6d4', r: 24 }, // Vibrant Cyan for Packages / Libraries
17
+ pkg: { color: '#0f8293', r: 24 }, // Cyan for Packages / Libraries, deep enough to sit 15 ΔE from page and core (MIN_SHAPE_DELTA_E)
18
18
  core: { color: '#14b8a6', r: 20 },
19
- token: { color: '#ec4899', r: 20 },
20
- atom: { color: '#10b981', r: 19 },
19
+ token: { color: '#ef409b', r: 20 },
20
+ atom: { color: '#108d4e', r: 19 },
21
21
  molecule: { color: '#a855f7', r: 21 },
22
22
  tool: { color: '#f43f5e', r: 19 },
23
23
  store: { color: '#fb923c', r: 20 }, // Storage tiers & data-flow endpoints (ADR 0020)
24
24
  table: { color: '#fde047', r: 18 }, // One model table; pages read and write it
25
- rom: { color: '#f0abfc', r: 19 }, // Render on Mutation pipeline stage
25
+ rom: { color: '#c398c6', r: 19 }, // Render on Mutation pipeline stage
26
26
  service: { color: '#84cc16', r: 20 }, // An API module that runs on a timer, a webhook or a change hook (MAP-03)
27
27
  external: { color: '#94a3b8', r: 21 }, // An outside system the API calls or that calls it
28
- stack: { color: '#a8a29e', r: 22 }, // One docker-compose stack: its containers, ports and the domains it serves (MAP-06)
28
+ stack: { color: '#b49fa0', r: 22 }, // One docker-compose stack: its containers, ports and the domains it serves (MAP-06)
29
29
  // The physical world (spec 0029). Derived from code: machine, container, persona, and a device with a `file`
30
30
  machine: { color: '#78716c', r: 26 }, // A computer the code runs on, by hostname
31
31
  container: { color: '#d6d3d1', r: 12 }, // One service of a stack
@@ -33,9 +33,31 @@ export const NODE_THEMES = {
33
33
  device: { color: '#2dd4bf', r: 14 }, // A camera, phone, NFC tag or Home Assistant device; `kind` says which (DEVICE_KINDS)
34
34
  // Live only: drawn from the live layer, never in topology.json (LIVE_TYPES)
35
35
  floor: { color: '#a3e635', r: 20 }, // A level of the house
36
- room: { color: '#bef264', r: 16 }, // A room, with its box on the floor plan
36
+ room: { color: '#f7ed81', r: 16 }, // A room, with its box on the floor plan (yellow beside the floor's lime: one silhouette, 15 ΔE apart)
37
37
  };
38
38
 
39
+ /**
40
+ * The silhouette each node type is drawn in (spec 0008 D8), so a type reads at 6 px where no glyph does: a circle for code, a rounded square for
41
+ * data, a hexagon for what is outside, a square for where things run, a diamond for people. A type this table does not know is a circle.
42
+ * The silhouette is not a token: it says what a node is. Colour tells the types of one silhouette apart, so they are kept far apart (below).
43
+ */
44
+ export const NODE_SHAPES = Object.freeze({
45
+ root: 'circle', app: 'circle', page: 'circle', pkg: 'circle', core: 'circle', token: 'circle', atom: 'circle', molecule: 'circle', tool: 'circle', rom: 'circle', service: 'circle',
46
+ store: 'rounded-square', table: 'rounded-square',
47
+ external: 'hexagon',
48
+ stack: 'square', machine: 'square', container: 'square', device: 'square', floor: 'square', room: 'square',
49
+ persona: 'diamond',
50
+ });
51
+ /** The silhouettes, in the order the renderers number them (0 is the circle) */
52
+ export const SHAPES = Object.freeze(['circle', 'rounded-square', 'hexagon', 'square', 'diamond']);
53
+ /** The silhouette of a node type: `circle` for one the table does not know (a type is project data, so it only selects from the table) */
54
+ export const shapeOf = (type) => (typeof type === 'string' && Object.hasOwn(NODE_SHAPES, type) ? NODE_SHAPES[type] : 'circle');
55
+ /**
56
+ * How far apart (CIEDE2000, core/delta-e.js) two types of one silhouette must be, on the dark ground and on the light one. The default palette is held to it
57
+ * by a test; `cornfield validate` warns when a theme's own map colours break it.
58
+ */
59
+ export const MIN_SHAPE_DELTA_E = 15;
60
+
39
61
  /** Kinds of data-flow edge (edge.kind === 'flow'); see docs/adr/0020 */
40
62
  export const FLOW_KINDS = ['outbox', 'changes', 'trigger', 'sync', 'model', 'rom', 'read', 'build', DERIVED_FLOW];
41
63
 
package/core/strings.js CHANGED
@@ -33,6 +33,15 @@ export const STRINGS = Object.freeze({
33
33
  approve: 'Approve',
34
34
  sendBack: 'Send back',
35
35
  sendBackWithNote: 'Send back with this note',
36
+ // The decision (spec 0007): asking in place, the hold, what an approval reads afterwards, the toggle for your edits, a landing that waits, a run that will wait
37
+ approveAnyway: 'Approve anyway',
38
+ sendBackAnyway: 'Send back anyway',
39
+ undo: 'Undo',
40
+ approved: 'Approved',
41
+ myEdits: 'My edits',
42
+ yourEdits: 'Your edits',
43
+ cancelLanding: 'Cancel landing',
44
+ queueIt: 'Queue it',
36
45
  reviewNoteLabel: 'Note for the drafting agent',
37
46
  reviewNotePlaceholder: 'What should change?',
38
47
  openSpecsList: 'Open the Specs list',
@@ -81,6 +90,8 @@ export const STRINGS = Object.freeze({
81
90
  openRoute: 'Open route',
82
91
  startRun: 'Start a run',
83
92
  copySpec: 'Copy Spec',
93
+ frame: 'Frame them',
94
+ throughChildren: "Include its children's lines",
84
95
  // The hint, loading and errors
85
96
  hintInspect: 'Click a node to see what it is',
86
97
  hintInspectTouch: 'Tap a node to see what it is',
@@ -10,14 +10,15 @@ export const CAP = 5;
10
10
  let counter = 0;
11
11
 
12
12
  /**
13
- * The items as HTML, folded after CAP when there are more.
13
+ * The items as HTML, folded after `cap` (CAP by default) when there are more.
14
14
  * @param {string[]} items already-escaped HTML, one per item
15
+ * @param {number} [cap]
15
16
  */
16
- export function capped(items) {
17
- if (items.length <= CAP + 1) return items.join(''); // "and 1 more" saves nothing
17
+ export function capped(items, cap = CAP) {
18
+ if (items.length <= cap + 1) return items.join(''); // "and 1 more" saves nothing
18
19
  const id = `hx-more-${++counter}`;
19
- const rest = items.length - CAP;
20
- return `${items.slice(0, CAP).join('')}<div class="hx-more" id="${id}" hidden>${items.slice(CAP).join('')}</div><button data-corn="more" data-corn-kind="quiet" type="button" class="hx-btn hx-btn--quiet hx-textact hx-more-btn" data-more="${id}" data-rest="${rest}" aria-expanded="false" aria-controls="${id}">and ${rest} more</button>`;
20
+ const rest = items.length - cap;
21
+ return `${items.slice(0, cap).join('')}<div class="hx-more" id="${id}" hidden>${items.slice(cap).join('')}</div><button data-corn="more" data-corn-kind="quiet" type="button" class="hx-btn hx-btn--quiet hx-textact hx-more-btn" data-more="${id}" data-rest="${rest}" aria-expanded="false" aria-controls="${id}">and ${rest} more</button>`;
21
22
  }
22
23
 
23
24
  /** Opens or folds the list a "more" button belongs to; true when the click was one */
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Cloud on the map, the explorer's pure half (spec 0031 sections 1 and 6, CLOUD-06): no DOM, no state.
5
5
  *
6
- * - `WHEN_STYLES`, `whenOf`, `whenDash`: when an outage of a cloud service bites, read from a `calls` edge's
7
- * `when` (absent = `run`), and how each looks: on the map (`dash`: solid, dashed, dotted), in the legend
6
+ * - `WHEN_STYLES`, `whenOf`, `whenTicks`: when an outage of a cloud service bites, read from a `calls` edge's
7
+ * `when` (absent = `run`), and how each looks: on the map (`ticks`: none, one, two), in the legend
8
8
  * (`legend`), in the panel (`title`, `color`). The one place these live: scene.js, the legend, the panel and
9
9
  * the House view's Cloud band (CLOUD-08) all read them here; the outage colours (CLOUD-07) are `color`.
10
10
  * - `externalLayer(node)`: the Layers key of an `external` node, `cloud` or `web` (the public web, spec D3).
@@ -23,16 +23,19 @@ import { capped } from './capped.js';
23
23
  * mark's), null for solid; `color` is the panel's and an outage scenario's for that group.
24
24
  */
25
25
  export const WHEN_STYLES = {
26
- run: { title: 'Breaks now', legend: 'Solid: breaks as soon as it is down', dash: null, color: '#f87171' },
27
- deploy: { title: 'Breaks at the next deploy', legend: 'Dashed: breaks at the next deploy, rebuild or first run', dash: [9, 5], color: '#fbbf24' },
28
- renew: { title: 'Breaks at the next certificate renewal', legend: 'Dotted: breaks at the next certificate renewal', dash: [2, 4], color: '#a78bfa' },
26
+ run: { title: 'Breaks now', legend: 'No tick: breaks as soon as it is down', ticks: 0, color: '#f87171' },
27
+ deploy: { title: 'Breaks at the next deploy', legend: 'One tick: breaks at the next deploy, rebuild or first run', ticks: 1, color: '#fbbf24' },
28
+ renew: { title: 'Breaks at the next certificate renewal', legend: 'Two ticks: breaks at the next certificate renewal', ticks: 2, color: '#a78bfa' },
29
29
  };
30
30
 
31
31
  /** A `calls` edge's `when`: `run` when absent (or not one of the three) */
32
32
  export const whenOf = (edge) => (edge && Object.hasOwn(WHEN_STYLES, edge.when) ? edge.when : 'run');
33
33
 
34
- /** The dash a `calls` edge is drawn with for its `when` (null = solid); any other kind of edge is not styled by it */
35
- export const whenDash = (edge) => (edge && edge.kind === 'calls' ? WHEN_STYLES[whenOf(edge)].dash : null);
34
+ /**
35
+ * The tick marks a `calls` edge carries at its middle for its `when` (spec 0008 D7): none, one for the next deploy, two for the next renewal. A dash
36
+ * means only "proposed" on the map, so `when` is told by ticks; any other kind of edge has none
37
+ */
38
+ export const whenTicks = (edge) => (edge && edge.kind === 'calls' ? WHEN_STYLES[whenOf(edge)].ticks : 0);
36
39
 
37
40
  /** The Layers key of an outside node: the public web (kind `web`) is its own; every other external is Cloud */
38
41
  export const externalLayer = (node) => (node && node.kind === 'web' ? 'web' : 'cloud');
@@ -0,0 +1,231 @@
1
+ /**
2
+ * @module explorer/decision-model
3
+ *
4
+ * The pure half of the decision (spec 0007): what the line above Approve says in this exact state (D1), whether a press is allowed, asks first
5
+ * or is refused (D2), the words of the hold (D3) and of what is sent with a review (D4). No DOM, no `window`, no clock (the time is passed in).
6
+ * review.js is the half that touches the page; the words and the choices are here so each row of the spec's two tables is a test.
7
+ *
8
+ * The facts come from `GET /proposals/<slug>/decision` (server/decision.js): `{ pull: { number, draft, head }, checks: { total, passed, running,
9
+ * failed: [names] } | null, lands, landing, run: null | { kind, transport, runner, lastSeen, open, fired } }`. Everything in them from the forge (names) is text,
10
+ * and it only ever becomes text: this module builds strings, never markup. The server decides; these words are a courtesy before the click.
11
+ *
12
+ * decide(input) { line, approve: 'allowed' | 'asks' | 'done' | 'refused' | 'reading', reasons, ask, askButton }
13
+ * sendBackLine(...) the line under the note: "Posts your note and 2 edits on PR #23 for the drafting agent. No run is asked for."
14
+ * sendBackDecision(...) whether Send back asks (an open form), and the words
15
+ * newReasons(...) the reasons to ask that the maintainer has not already answered (the end of the hold reads the facts again)
16
+ * refusalWords(...) the server's 401 and 403 at the press, in words
17
+ * holdWords / HOLD_MS "Approving in 5 s", and the hold itself (one constant)
18
+ * editsSentWords(n) "Sent with 2 edits"
19
+ */
20
+
21
+ import { agoShort } from './runs-model.js';
22
+ import { pullNumberOf } from './proposal-model.js';
23
+
24
+ /** The hold between a press and anything leaving the page (D3), in milliseconds: one constant */
25
+ export const HOLD_MS = 5000;
26
+ /** How long a landing waits for the PR to be ready and green, in minutes (server/lander.js TIMEOUT_MS; test/server/decision.test.js holds them equal) */
27
+ export const LAND_MINUTES = 60;
28
+ /** The most check names a line spells out; the rest is "and N more" */
29
+ const NAMES_SHOWN = 3;
30
+ /** The longest a check's name is in a line (the forge's text, cut) */
31
+ const NAME_CHARS = 40;
32
+
33
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
34
+ const oneLine = (s) => String(s).replace(/\s+/g, ' ').trim();
35
+ const cut = (s) => { const t = oneLine(s); return t.length > NAME_CHARS ? `${t.slice(0, NAME_CHARS - 1)}…` : t; };
36
+
37
+ /** "lint", "lint and test", "lint, test and e2e", "lint, test, e2e and 2 more": names from the forge, as text */
38
+ export function nameList(names) {
39
+ const shown = names.slice(0, NAMES_SHOWN).map(cut);
40
+ const more = names.length - shown.length;
41
+ if (more > 0) return `${shown.join(', ')} and ${more} more`;
42
+ return shown.length < 2 ? shown.join('') : `${shown.slice(0, -1).join(', ')} and ${shown[shown.length - 1]}`;
43
+ }
44
+
45
+ const failedOf = (facts) => (facts && facts.checks && Array.isArray(facts.checks.failed) ? facts.checks.failed : []);
46
+ const runningOf = (facts) => (facts && facts.checks ? facts.checks.running || 0 : 0);
47
+
48
+ /** "lint failed", "lint and test failed", "3 checks failed"-less: always the names */
49
+ const failedWords = (names) => `${nameList(names)} failed`;
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // The line (D1)
53
+ // ---------------------------------------------------------------------------
54
+
55
+ /** What an approval asks for besides posting, and whether the runner is there: the parts after the PR's (D1's last four rows) */
56
+ export function runWords(run, nowMs) {
57
+ if (!run) return '';
58
+ const kind = ['code', 'summary', 'brief', 'proposal'].includes(run.kind) ? run.kind : 'code';
59
+ const what = kind === 'code' ? 'a code run' : `a ${kind} run`;
60
+ // The trigger skips a run while one is open on the PR or the proposal, and asks once per head: the line must not promise one
61
+ if (run.open) return `No new run is asked for: ${typeof run.open === 'string' ? `run ${oneLine(run.open).slice(0, 40)} is` : 'one is'} still open on it.`;
62
+ if (run.fired) return `No new run is asked for: ${what} was asked for at this head already.`;
63
+ const asked = `Then ${what} is asked for.`;
64
+ if (run.transport !== 'pull') return `${asked} The request is posted for your runner.`;
65
+ if (run.runner === 'online') return `${asked} A runner is online.`;
66
+ const seen = typeof run.lastSeen === 'string' ? Date.parse(run.lastSeen) : NaN;
67
+ if (run.runner === 'quiet' && Number.isFinite(seen)) return `${asked} No runner has polled for ${agoShort(nowMs - seen)}: the run will wait.`;
68
+ return `${asked} No runner has polled yet: the run will wait.`;
69
+ }
70
+
71
+ /** Whether a run would wait for a runner that is not there: the Work button's dot and the notices say so (#183) */
72
+ export const runWaits = (run) => !!run && run.transport === 'pull' && (run.runner === 'quiet' || run.runner === 'never');
73
+
74
+ /** "Your 2 edits go in the comment, for the agent to fold in." */
75
+ export const editsWords = (edits) => (edits > 0 ? `Your ${plural(edits, 'edit')} ${edits === 1 ? 'goes' : 'go'} in the comment, for the agent to fold in.` : '');
76
+
77
+ /** The PR and its checks, and what landing does about them: the first parts of the line (D1's first nine rows) */
78
+ function pullWords(facts) {
79
+ const n = facts.pull.number;
80
+ const lands = !!facts.lands;
81
+ if (facts.pull.draft) {
82
+ return lands
83
+ ? `PR #${n} is a draft. Approve posts an approval; it lands only if the PR is marked ready within ${LAND_MINUTES} minutes.`
84
+ : `PR #${n} is a draft. Approve posts an approval on it.`;
85
+ }
86
+ const head = `Approve posts an approval on PR #${n}.`;
87
+ const checks = facts.checks;
88
+ const failed = failedOf(facts);
89
+ const running = runningOf(facts);
90
+ if (failed.length) return lands ? `${head} It will not land: ${failedWords(failed)}.` : `${head} ${failedWords(failed)}.`;
91
+ if (checks && checks.total === 0) return lands ? `${head} It will not land: the PR has no checks.` : `${head} It does not land it.`;
92
+ if (running) {
93
+ if (!lands) return `${head} ${running === 1 ? '1 check is' : `${running} checks are`} still running.`;
94
+ return `${head} It lands once ${running === 1 ? '1 running check passes' : `${running} running checks pass`}.`;
95
+ }
96
+ if (checks && !checks.passed) return lands ? `${head} It will not land: no check has passed.` : `${head} It does not land it.`; // all skipped or neutral
97
+ return lands ? `Approve posts an approval on PR #${n} and lands it.` : `${head} It does not land it.`;
98
+ }
99
+
100
+ /** The line while Approve reads Approved: what stands, and what makes it live again */
101
+ function doneWords(n, facts) {
102
+ const landing = facts && facts.landing ? ' Its landing waits for the checks.' : '';
103
+ return `An approval of this version of PR #${n} stands.${landing} A push makes Approve live again.`;
104
+ }
105
+
106
+ /**
107
+ * Why a press asks first, in the order of D2's table (checks failed, a draft, an open form, edits with landing). Each is `{ key, text }` where
108
+ * `text` is the reason as a sentence; the question follows it.
109
+ * @param {{ facts: object|null, edits: number, form: { name: string } | null }} input
110
+ */
111
+ export function askReasons({ facts, edits = 0, form = null }) {
112
+ const out = [];
113
+ if (facts && facts.pull) {
114
+ const failed = failedOf(facts);
115
+ if (failed.length) out.push({ key: 'failed', text: `${failedWords(failed)} on PR #${facts.pull.number}.` });
116
+ if (facts.pull.draft) out.push({ key: 'draft', text: `PR #${facts.pull.number} is a draft: its author has not marked it ready.` });
117
+ }
118
+ if (form) out.push({ key: 'form', text: `Your ${oneLine(form.name)} form is not added.` });
119
+ if (facts && facts.pull && facts.lands && edits > 0) out.push({ key: 'edits', text: `PR #${facts.pull.number} lands as written; your ${plural(edits, 'edit')} only go${edits === 1 ? 'es' : ''} in the comment.` });
120
+ return out;
121
+ }
122
+
123
+ /** The question for the reasons that ask: one reason ends as D2's table does, several are said together and end "Approve anyway?" */
124
+ export function askWords(reasons, verb = 'Approve') {
125
+ if (!reasons.length) return '';
126
+ const only = reasons.length === 1 ? reasons[0] : null;
127
+ const last = only && only.key === 'form' ? `${verb} without it?` : `${verb} anyway?`;
128
+ return `${reasons.map((r) => r.text).join(' ')} ${last}`;
129
+ }
130
+
131
+ /** The reasons that ask now and the maintainer has not answered yet (`answered`: the keys confirmed with "Approve anyway"): at the end of the hold, only a new one asks again */
132
+ export const newReasons = (reasons, answered) => reasons.filter((r) => !answered.includes(r.key));
133
+
134
+ /**
135
+ * The line above Approve and what a press of it does, from the facts and the page's own state.
136
+ * @param {object} input
137
+ * @param {string|null} input.source the proposal's source: `pull/<n>`, `checkout` or a worktree
138
+ * @param {object|null} input.facts the route's answer, or null
139
+ * @param {'loading'|'ready'|'unread'} input.factsState `loading` before the first answer, `unread` when it could not be read
140
+ * @param {{ verdict: string, current?: boolean }|null} [input.review] the last review of the proposal
141
+ * @param {number} [input.edits] the applied what-if edits
142
+ * @param {{ name: string }|null} [input.form] a what-if form that is open with something in it
143
+ * @param {string} [input.played] "2 of 3 scenarios played", when there is a record
144
+ * @param {number} [input.now]
145
+ * @returns {{ line: string, approve: 'allowed'|'asks'|'done'|'refused'|'reading', reasons: {key:string,text:string}[], ask: string }}
146
+ */
147
+ export function decide({ source, facts, factsState, review = null, edits = 0, form = null, played = '', now = Date.now() }) {
148
+ const n = pullNumberOf(source);
149
+ const tail = (...parts) => parts.filter(Boolean).join(' ');
150
+ if (!n) {
151
+ const where = !source || source === 'checkout' ? 'the checkout' : `worktree ${oneLine(source)}`;
152
+ return { line: `Draft in ${where}: push it as a spec PR to review it here.`, approve: 'refused', reasons: [], ask: '' };
153
+ }
154
+ const done = !!review && review.verdict === 'approved' && review.current === true;
155
+ if (factsState === 'loading' || (!facts && factsState !== 'unread')) {
156
+ return { line: tail(`Reading PR #${n} …`, played), approve: done ? 'done' : 'reading', reasons: [], ask: '' };
157
+ }
158
+ if (!facts || factsState === 'unread') {
159
+ return { line: tail(`Could not read PR #${n}'s checks. Approve posts an approval on it.`, editsWords(edits), played), approve: done ? 'done' : 'allowed', reasons: askReasons({ facts: null, edits, form }), ask: '' };
160
+ }
161
+ const reasons = askReasons({ facts, edits, form });
162
+ const run = facts.run ? runWords(facts.run, now) : '';
163
+ const line = tail(pullWords(facts), run, editsWords(edits), played);
164
+ // Approve does nothing now (an approval of this version stands): the line says that, not what a press would post
165
+ if (done) return { line: tail(doneWords(n, facts), played), approve: 'done', reasons, ask: '' };
166
+ return { line, approve: reasons.length ? 'asks' : 'allowed', reasons, ask: askWords(reasons) };
167
+ }
168
+
169
+ // ---------------------------------------------------------------------------
170
+ // Send back (D4)
171
+ // ---------------------------------------------------------------------------
172
+
173
+ /** The line under the note: what Send back posts, and that it asks for no run */
174
+ export function sendBackLine({ source, edits = 0 }) {
175
+ const n = pullNumberOf(source);
176
+ if (!n) return '';
177
+ const what = edits > 0 ? `your note and ${plural(edits, 'edit')}` : 'your note';
178
+ return `Posts ${what} on PR #${n} for the drafting agent. No run is asked for.`;
179
+ }
180
+
181
+ /** Whether Send back asks first: only an open form that holds input does (D4). `{ asks, ask }` */
182
+ export function sendBackDecision({ form = null }) {
183
+ const reasons = askReasons({ facts: null, edits: 0, form });
184
+ return { asks: reasons.length > 0, reasons, ask: askWords(reasons, 'Send back') };
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // The server's refusals at the press (D2), in words
189
+ // ---------------------------------------------------------------------------
190
+
191
+ /**
192
+ * What a refused review says. 401: the sign-in has ended; 403: the server's own words (a maintainer who is one no longer, a page that is not
193
+ * cornfield's own); 409: what stands already. Anything else is the server's words with the plain statement that nothing was posted.
194
+ * @param {number} status
195
+ * @param {string} [error] the server's words
196
+ */
197
+ export function refusalWords(status, error = '') {
198
+ if (status === 401) return 'Your sign-in has ended. Sign in again: your edits are kept here.';
199
+ const said = oneLine(error);
200
+ if (status === 403 || status === 409) return said || 'The review was not posted.';
201
+ return `The review was not posted. ${said || `The server answered ${status}.`}`;
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // The hold (D3)
206
+ // ---------------------------------------------------------------------------
207
+
208
+ /** The button's words while the hold runs: "Approving in 5 s", "Sending back in 4 s" */
209
+ export const holdWords = (verdict, seconds) => `${verdict === 'approved' ? 'Approving' : 'Sending back'} in ${Math.max(0, Math.ceil(seconds))} s`;
210
+
211
+ /** What is said once when the hold starts (a live region): not every second */
212
+ export const holdStartWords = (verdict, seconds) => `${verdict === 'approved' ? 'Approving' : 'Sending back'} in ${plural(Math.ceil(seconds), 'second')}. Undo to stop it; nothing has been sent.`;
213
+
214
+ /** What is said when a hold is cancelled, and why: it always ends "Nothing was sent." */
215
+ export function holdCancelledWords(verdict, why) {
216
+ const what = verdict === 'approved' ? 'The approval' : 'The send back';
217
+ const because = {
218
+ undo: `${what} was undone.`,
219
+ escape: `${what} was undone.`,
220
+ closed: `${what} was stopped: the proposal was closed.`,
221
+ other: `${what} was stopped: another proposal was opened.`,
222
+ hidden: `${what} was stopped: this tab was hidden.`,
223
+ offline: `${what} was stopped: you are offline.`,
224
+ edits: `${what} was stopped: your edits changed.`,
225
+ pushed: `${what} was stopped: the PR was pushed to while it was held, so it is not what you looked at. Look again before you decide.`,
226
+ }[why] || `${what} was stopped.`;
227
+ return `${because} Nothing was sent.`;
228
+ }
229
+
230
+ /** What a send back leaves readable: "Sent with 2 edits" (D4) */
231
+ export const editsSentWords = (count) => `Sent with ${plural(count, 'edit')}`;
@@ -31,5 +31,7 @@ export const MARK_SHAPES = Object.freeze({
31
31
  added: Object.freeze({ ringDash: Object.freeze([5, 4]), edgeDash: Object.freeze([7, 5]), strike: false }), // a dashed ring
32
32
  changed: Object.freeze({ ringDash: null, edgeDash: null, strike: false }), // a plain solid ring
33
33
  removed: Object.freeze({ ringDash: null, edgeDash: Object.freeze([3, 4]), strike: true }), // a faded ring, struck through
34
- edit: Object.freeze({ ringDash: Object.freeze([2, 5]), edgeDash: Object.freeze([2, 5]), strike: false }), // a dotted ring: short marks, wide gaps (a 1.5/3.5 dot blurred into a solid ring at 1x)
34
+ // a dotted ring: short marks, wide gaps (a 1.5/3.5 dot blurred into a solid ring at 1x); its line is long-dashed: dashed, as everything not built is
35
+ // (spec 0008 D7), and not dotted, which is a usage link's (a lit one is lilac too)
36
+ edit: Object.freeze({ ringDash: Object.freeze([2, 5]), edgeDash: Object.freeze([12, 4]), strike: false }),
35
37
  });
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @module explorer/edge-key
3
+ *
4
+ * The Key in the Layers menu (spec 0008 D7): each kind of line drawn as the map draws it, with its real style and end mark, not a coloured dot.
5
+ * A pure function of the constants the renderers draw from (scene.js ARROW, END_SHAPES, USAGE_DASH, PROPOSED_DASH), so the Key and the map
6
+ * cannot drift apart. Every word here is fixed text: nothing from the map reaches it.
7
+ */
8
+
9
+ import { ARROW, END_SHAPES, PROPOSED_DASH, USAGE_DASH } from './scene.js';
10
+
11
+ const W = 44; // the swatch's width and height (px)
12
+ const H = 16;
13
+ const MID = H / 2;
14
+ const X0 = 2;
15
+ const TIP = W - 3;
16
+
17
+ /** The end mark of each family, as SVG path data with its tip at (tx, MID), in the same units the map draws it in (ARROW, END_SHAPES) */
18
+ const mark = (kind, tx) => {
19
+ const back = ARROW.length * Math.cos(ARROW.spread);
20
+ const side = ARROW.length * Math.sin(ARROW.spread);
21
+ if (kind === 'triangle') return `<path d="M${tx} ${MID} L${tx - back} ${MID - side} L${tx - back} ${MID + side} Z" fill="currentColor"/>`;
22
+ if (kind === 'chevron') return `<path d="M${tx - back} ${MID - side} L${tx} ${MID} L${tx - back} ${MID + side}" fill="none" stroke="currentColor" stroke-width="${END_SHAPES.strokeWidth}"/>`;
23
+ if (kind === 'bar') return `<path d="M${tx - 1} ${MID - END_SHAPES.barHalf} V${MID + END_SHAPES.barHalf}" fill="none" stroke="currentColor" stroke-width="${END_SHAPES.strokeWidth}"/>`;
24
+ if (kind === 'diamond') {
25
+ const h = END_SHAPES.diamondHalf;
26
+ const a = END_SHAPES.diamondAcross;
27
+ return `<path d="M${tx} ${MID} L${tx - h} ${MID - a} L${tx - 2 * h} ${MID} L${tx - h} ${MID + a} Z" fill="none" stroke="currentColor" stroke-width="${END_SHAPES.strokeWidth}"/>`;
28
+ }
29
+ return '';
30
+ };
31
+
32
+ /** A swatch: a line of `width`, with `dash` (or solid), an end mark, and `ticks` across its middle */
33
+ export function keySwatch({ end = null, dash = null, width = 1.6, ticks = 0 } = {}) {
34
+ const stop = end ? TIP - (end === 'triangle' || end === 'chevron' ? 1 : end === 'diamond' ? 2 * END_SHAPES.diamondHalf : 1) : TIP;
35
+ const line = `<path d="M${X0} ${MID} H${stop}" fill="none" stroke="currentColor" stroke-width="${width}"${dash ? ` stroke-dasharray="${dash.join(' ')}"` : ''}/>`;
36
+ let tickPaths = '';
37
+ for (let i = 0; i < ticks; i++) {
38
+ const x = (X0 + stop) / 2 + (i - (ticks - 1) / 2) * END_SHAPES.tickGap;
39
+ tickPaths += `<path d="M${x} ${MID - END_SHAPES.tickHalf} V${MID + END_SHAPES.tickHalf}" fill="none" stroke="currentColor" stroke-width="${END_SHAPES.tickWidth}"/>`;
40
+ }
41
+ return `<svg class="hx-key-line" data-corn="swatch" viewBox="0 0 ${W} ${H}" width="${W}" height="${H}" aria-hidden="true" focusable="false">${line}${tickPaths}${end ? mark(end, TIP) : ''}</svg>`;
42
+ }
43
+
44
+ /** The rows of the Key: [swatch options, the words] */
45
+ export const KEY_ROWS = Object.freeze([
46
+ [{ width: 1.4 }, 'Owns: a parent and what it holds'],
47
+ [{ dash: USAGE_DASH, width: 1.6 }, 'Uses loosely: dotted'],
48
+ [{ dash: PROPOSED_DASH, end: 'chevron' }, 'Proposed, not built: dashed, with its kind’s mark'],
49
+ [{ end: 'chevron' }, 'Data: flow, reads, writes (towards the page is a read)'],
50
+ [{ end: 'triangle' }, 'Services: calls, triggers, delivers'],
51
+ [{ end: 'bar' }, 'Places: runs on'],
52
+ [{ end: 'diamond' }, 'Tokens: uses, extends'],
53
+ ]);
54
+
55
+ /** The Key's markup (the section's own title and its rows) */
56
+ export function edgeKeyHtml() {
57
+ const rows = KEY_ROWS.map(([opts, words]) => `<div class="hx-legend-row"><span class="hx-legend-swatch hx-legend-swatch--wide">${keySwatch(opts)}</span><span>${words}</span></div>`).join('');
58
+ return `<div class="hx-menu-title" data-corn="menu-title"><span>Key</span></div>${rows}<p class="hx-faint hx-key-note">A line says its kind in words when it is lit.</p>`;
59
+ }