Public: anyone can read this; the crew can change it.

docs/DESIGN.md holds the rules of attention, and every page has a measured first-view budget #10316

Parked opened this in answer to
Closed without merging

torque/forge:torque/10297-docs-design-md-holds-the-rules-of-attent → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +414 −0
README.md +2
@@ -33,6 +33,8 @@ bun src/main.ts --first-admin # prints a one-time link that makes you the adm
3333 The crew needs the `claude` CLI and a model credential. On Linux, install
3434 `bubblewrap` and `socat` so apps and agents run contained.
3535
36 First-view budgets (`test/attention-budget.json`, 390 px / 1280 px; raising one needs a note in the pull, see `docs/features/attention.md`): home 157w 21b 4c / 170w 26b 4c; repository 137w 27b 3c / 143w 29b 3c; app 137w 27b 3c / 143w 29b 3c; pull 114w 27b 5c / 120w 29b 5c; issue 78w 29b 3c / 78w 29b 3c; issues 47w 19b 4c / 47w 19b 4c; pulls 49w 18b 4c / 49w 18b 4c; apps 68w 16b 4c / 68w 16b 4c; runs 65w 20b 3c / 65w 20b 3c; settings 97w 26b 3c / 117w 28b 3c.
37
3638 ## Learn more
3739
3840 - [What you see and how to use it](docs/STUDIO.md)
docs/DESIGN.md +14
@@ -21,6 +21,20 @@
2121 anywhere ends in one `<a>` (Traffic, Backups), the only interactive colour (5); each row says
2222 its state in a few plain words, with a toned `badge` for the verdict (Recent, Overdue) (8).
2323
24 ## The rules of attention
25
26 The forge exists to minimise the time its owner spends in it. Five rules, in order; each shows a do and a don't from a real page. Rule 5 is enforced by `test/attention.test.ts`.
27
28 1. **One answer.** A page answers its one question at first sight. State is a word and a glyph, not a sentence.
29 Do: the security page's `statusRow` — "Backup" and a toned `Recent` badge. Don't: a paragraph explaining what a backup is and when the last one ran.
30 2. **No notes.** Prose that does not change a decision goes. Help lives in one place, on demand.
31 Do: the home page's composer with one muted line, `The feed`. Don't: a paragraph above a list saying what the list is.
32 3. **Real depth only.** Details, history, logs and evidence open in place, in their own compartment (`<details>` with a real body). The essential is never one tap away, and nothing is a tap with nothing behind it.
33 Do: a run's log under its summary. Don't: a "More" that reveals one more word, or the verdict hidden behind a tap.
34 4. **Compartments.** Each concern sits in one region with one heading, in the same order on every page. Regions never repeat each other.
35 Do: a pull's checks in one region. Don't: the same state in a header badge, a banner and a sentence in the thread (`Status: Open` beside an `Open` badge).
36 5. **Measured.** Every page has a first-view budget at 390 px and 1280 px: visible words, text blocks and distinct colours, in `test/attention-budget.json`. A pass may lower a budget; nothing raises one without a note in the pull. See `docs/features/attention.md`.
37
2438 One vocabulary, two surfaces. The web renders it as HTML and CSS; a terminal UI
2539 renders the same names as cells and boxes. If a component is not in these files,
2640 it does not exist — and if you find yourself hand-rolling markup a page already
docs/features/attention.md added +14
@@ -0,0 +1,14 @@
1 # First-view budgets
2
3 `test/attention.test.ts` renders the home page, a repository, its app, a pull, an issue, the issue and pull lists, apps, runs and settings (signed in, on a small forge) and measures the first view at 390 px and 1280 px with `test/helpers/first-view.ts`.
4
5 It is an estimate from the server-rendered HTML, because the first paint is server-rendered and the test runs without a browser:
6
7 - Left out: `<head>`, scripts, styles, svg, `hidden`, `.sr-only`, and the body of a closed `<details>` (its summary counts).
8 - A text block is the text between two block boundaries. A block is 20 px per wrapped line (7.5 px a character, a column of the width less 32 px, at most 960 px) plus 8 px.
9 - The first view is the blocks starting above the viewport's bottom edge (390×844, 1280×800).
10 - Colours are roles, not hex values: text, muted, accent (a link or button), and each `data-tone` and `data-series` value seen.
11
12 The app page redirects to the repository today, so those two rows match.
13
14 Budgets live in `test/attention-budget.json`; the README paragraph repeats them and a test checks the two agree. To lower a budget after a pass: run `ATTENTION_UPDATE=1 bun test test/attention.test.ts`, copy the printed JSON, and update the README paragraph. To raise one, do the same and say why in the pull.
test/attention-budget.json added +122
@@ -0,0 +1,122 @@
1 {
2 "home": {
3 "phone": {
4 "words": 157,
5 "blocks": 21,
6 "colours": 4
7 },
8 "desktop": {
9 "words": 170,
10 "blocks": 26,
11 "colours": 4
12 }
13 },
14 "repository": {
15 "phone": {
16 "words": 137,
17 "blocks": 27,
18 "colours": 3
19 },
20 "desktop": {
21 "words": 143,
22 "blocks": 29,
23 "colours": 3
24 }
25 },
26 "app": {
27 "phone": {
28 "words": 137,
29 "blocks": 27,
30 "colours": 3
31 },
32 "desktop": {
33 "words": 143,
34 "blocks": 29,
35 "colours": 3
36 }
37 },
38 "pull": {
39 "phone": {
40 "words": 114,
41 "blocks": 27,
42 "colours": 5
43 },
44 "desktop": {
45 "words": 120,
46 "blocks": 29,
47 "colours": 5
48 }
49 },
50 "issue": {
51 "phone": {
52 "words": 78,
53 "blocks": 29,
54 "colours": 3
55 },
56 "desktop": {
57 "words": 78,
58 "blocks": 29,
59 "colours": 3
60 }
61 },
62 "issues": {
63 "phone": {
64 "words": 47,
65 "blocks": 19,
66 "colours": 4
67 },
68 "desktop": {
69 "words": 47,
70 "blocks": 19,
71 "colours": 4
72 }
73 },
74 "pulls": {
75 "phone": {
76 "words": 49,
77 "blocks": 18,
78 "colours": 4
79 },
80 "desktop": {
81 "words": 49,
82 "blocks": 18,
83 "colours": 4
84 }
85 },
86 "apps": {
87 "phone": {
88 "words": 68,
89 "blocks": 16,
90 "colours": 4
91 },
92 "desktop": {
93 "words": 68,
94 "blocks": 16,
95 "colours": 4
96 }
97 },
98 "runs": {
99 "phone": {
100 "words": 65,
101 "blocks": 20,
102 "colours": 3
103 },
104 "desktop": {
105 "words": 65,
106 "blocks": 20,
107 "colours": 3
108 }
109 },
110 "settings": {
111 "phone": {
112 "words": 97,
113 "blocks": 26,
114 "colours": 3
115 },
116 "desktop": {
117 "words": 117,
118 "blocks": 28,
119 "colours": 3
120 }
121 }
122 }
test/attention.test.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * Rule 5 of docs/DESIGN.md, "Measured" (#10297): every main page has a
3 * first-view budget at phone and desktop width, in `test/attention-budget.json`.
4 * A page over its budget fails. A pass may lower a budget; raising one needs a
5 * note in the pull, and the README baseline must say the same numbers.
6 *
7 * bun test test/attention.test.ts prints each page against its budget
8 * ATTENTION_UPDATE=1 bun test test/attention.test.ts prints the budget file for today's numbers
9 */
10 import { afterAll, expect, test } from "bun:test";
11 import { mkdtempSync, readFileSync, rmSync } from "node:fs";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { enableApp } from "../src/actions/apps.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { openPull } from "../src/actions/pulls.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { createUser } from "../src/core/users.ts";
19 import { createIssue } from "../src/core/issues.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { proveAll } from "./helpers/verified.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { DESKTOP, firstView, PHONE, type Count } from "./helpers/first-view.ts";
24
25 quietLogs();
26
27 const PAGES: [string, string][] = [
28 ["home", "/"],
29 ["repository", "/alice/vault"],
30 ["app", "/alice/vault/app"],
31 ["pull", "/alice/vault/pulls/1"],
32 ["issue", "/alice/vault/issues/2"],
33 ["issues", "/alice/vault/issues"],
34 ["pulls", "/alice/vault/pulls"],
35 ["apps", "/apps"],
36 ["runs", "/alice/vault/runs"],
37 ["settings", "/settings"],
38 ];
39
40 type Budget = Record<string, { phone: Count; desktop: Count }>;
41 const budget = JSON.parse(readFileSync(new URL("./attention-budget.json", import.meta.url), "utf8")) as Budget;
42
43 let root = "";
44 let app: App;
45 let servers!: Servers;
46 let cookie = "";
47
48 // Set up before the tests are registered, so each test's name carries the numbers measured:
49 // a red check names the page and what it saw.
50 await (async () => {
51 root = mkdtempSync(join(tmpdir(), "forge-attention-"));
52 app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" });
53 const u = await createUser(app.db, {
54 origin: "seed",
55 trusted: true,
56 username: "alice",
57 email: "[email protected]",
58 password: "a-good-passphrase",
59 adminIfFirst: true,
60 });
61 if (!u.ok) throw new Error(u.error);
62 proveAll(app);
63 const made = await createRepo(app, { id: u.value.id, username: "alice" } as never, { name: "vault" });
64 if (!made.ok) throw new Error(String(made.error));
65 const seeded = await commitToBranch(app, u.value, made.value, {
66 message: "Start",
67 files: [{ path: "README.md", content: "A vault.\n" }],
68 });
69 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
70 const branched = await commitToBranch(app, u.value, made.value, {
71 branch: "feature",
72 message: "Add a note",
73 files: [{ path: "note.txt", content: "yes\n" }],
74 });
75 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
76 const pull = await openPull(app, u.value, made.value, { title: "Add a note", baseBranch: "main", headBranch: "feature" });
77 if (!pull.ok) throw new Error(String(pull.error));
78 createIssue(app.db, { repoId: made.value.id, authorId: u.value.id, title: "Lock is slow", body: "It takes a second." });
79 const enabled = await enableApp(app, u.value, made.value, { slug: "vault" });
80 if (!enabled.ok) throw new Error(String(enabled.error));
81 servers = await serve(app);
82 const signin = await fetch(`${servers.url}/signin`, {
83 method: "POST",
84 headers: { origin: servers.url },
85 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
86 redirect: "manual",
87 });
88 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
89 })();
90 afterAll(() => {
91 servers.stop();
92 app.close();
93 rmSync(root, { recursive: true, force: true });
94 });
95
96 const row = (c: Count): string => `${String(c.words)}w ${String(c.blocks)}b ${String(c.colours)}c`;
97
98 const measured: Budget = {};
99 for (const [name, path] of PAGES) {
100 let res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
101 if (res.status !== 200) res = await fetch(`${servers.url}${path}`, { headers: { cookie } });
102 const html = await res.text();
103 const status = res.status;
104 const phone = firstView(html, PHONE);
105 const desktop = firstView(html, DESKTOP);
106 measured[name] = { phone, desktop };
107 const b = budget[name];
108 const title = `${name} stays inside its first-view budget: 390 ${row(phone)} of ${b ? row(b.phone) : "none"}, 1280 ${row(desktop)} of ${b ? row(b.desktop) : "none"} (HTTP ${String(status)})`;
109 test(title, () => {
110 expect(status, `${path}: ${html.slice(0, 200)}`).toBe(200);
111 expect(b, `${name} has no budget`).toBeDefined();
112 const over: string[] = [];
113 for (const [width, got, max] of [["390", phone, b!.phone], ["1280", desktop, b!.desktop]] as const) {
114 for (const k of ["words", "blocks", "colours"] as const) {
115 if (got[k] > max[k]) over.push(`${name} at ${width}: ${String(got[k])} ${k} is over the budget of ${String(max[k])}`);
116 }
117 }
118 expect(over).toEqual([]);
119 });
120 }
121 if (process.env.ATTENTION_UPDATE) console.log(JSON.stringify(measured, null, 2));
122
123 test("the README baseline lists the budget file's numbers", () => {
124 const readme = readFileSync(new URL("../README.md", import.meta.url), "utf8");
125 for (const [name] of PAGES) {
126 const b = budget[name]!;
127 const line = `${name} ${row(b.phone)} / ${row(b.desktop)}`;
128 expect(readme.includes(line), `README baseline row: ${line}`).toBe(true);
129 }
130 });
131
132 test("the measure counts what is visible and leaves out what is not", () => {
133 const html = `<body><h1>One answer</h1><p class="muted">two words</p><details><summary>More</summary><p>hidden hidden hidden</p></details><span class="sr-only">nope</span><p hidden>no</p><script>x()</script><p><a href="/">Go</a> <b data-tone="danger">Failed</b></p></body>`;
134 expect(firstView(html, PHONE)).toEqual({ words: 7, blocks: 4, colours: 4 });
135 const long = `<body>${"<p>word word word word word word word word word word</p>".repeat(60)}</body>`;
136 expect(firstView(long, PHONE).blocks).toBeLessThan(60);
137 });
test/helpers/first-view.ts added +125
@@ -0,0 +1,125 @@
1 /**
2 * What a reader sees on first view, estimated from the server-rendered HTML
3 * alone (no browser: the sandbox has none, and the first paint is server-rendered).
4 *
5 * The model, deliberately plain:
6 * - skipped: <head>, script, style, template, noscript, svg, anything `hidden`,
7 * `.sr-only`, and the body of a closed <details> (its <summary> stays);
8 * - a text block is the text between two block boundaries; a block is
9 * LINE_PX per wrapped line (CHARS_PER_PX per character of the column) plus GAP_PX;
10 * - the first view is the blocks that start above the viewport's bottom edge;
11 * - words: whitespace-separated words in those blocks;
12 * - colours: distinct colour roles in them: text, muted (class muted/dim),
13 * accent (a link or button), and each `data-tone` / `data-series` value.
14 */
15
16 export interface View {
17 readonly width: number;
18 readonly height: number;
19 }
20 export const PHONE: View = { width: 390, height: 844 };
21 export const DESKTOP: View = { width: 1280, height: 800 };
22
23 export interface Count {
24 readonly words: number;
25 readonly blocks: number;
26 readonly colours: number;
27 }
28
29 const LINE_PX = 20; // 14px type on a 20px line
30 const GAP_PX = 8;
31 const CHAR_PX = 7.5; // average advance of 14px text
32 const PAD_PX = 32; // side padding on a phone
33 const MAX_COLUMN_PX = 960; // the page's reading column on a desktop
34
35 const VOID = new Set(["br", "hr", "img", "input", "meta", "link", "source", "wbr", "col", "area", "base"]);
36 const SKIP = new Set(["head", "script", "style", "template", "noscript", "svg", "title"]);
37 const BLOCK = new Set([
38 "p", "div", "section", "article", "header", "footer", "nav", "main", "aside", "h1", "h2", "h3", "h4", "h5", "h6",
39 "li", "ul", "ol", "dl", "dt", "dd", "tr", "table", "form", "details", "summary", "pre", "blockquote", "figure",
40 "figcaption", "fieldset", "legend", "label", "button", "br", "hr", "textarea", "select", "option", "caption",
41 ]);
42
43 function attr(tag: string, name: string): string | undefined {
44 const m = new RegExp(`\\s${name}(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+)))?(?=[\\s/>])`, "i").exec(tag);
45 if (m === null) return undefined;
46 return m[1] ?? m[2] ?? m[3] ?? "";
47 }
48
49 function decode(text: string): string {
50 return text
51 .replace(/&nbsp;/g, " ")
52 .replace(/&amp;/g, "&")
53 .replace(/&lt;/g, "<")
54 .replace(/&gt;/g, ">")
55 .replace(/&quot;/g, '"')
56 .replace(/&#(\d+);/g, (_, n: string) => String.fromCodePoint(Number(n)));
57 }
58
59 export function firstView(html: string, view: View): Count {
60 const column = Math.min(view.width - PAD_PX, MAX_COLUMN_PX);
61 const perLine = Math.max(10, Math.floor(column / CHAR_PX));
62 const stack: { name: string; skip: boolean; closed: boolean }[] = [];
63 const colours = new Set<string>(["text"]);
64 let words = 0;
65 let blocks = 0;
66 let y = 0;
67 let pending = "";
68 let pendingColours: string[] = [];
69 let done = false;
70
71 const flush = (): void => {
72 const text = pending.replace(/\s+/g, " ").trim();
73 const found = pendingColours;
74 pending = "";
75 pendingColours = [];
76 if (text === "" || done) return;
77 blocks += 1;
78 words += text.split(" ").length;
79 for (const c of found) colours.add(c);
80 y += Math.ceil(text.length / perLine) * LINE_PX + GAP_PX;
81 if (y >= view.height) done = true;
82 };
83
84 const body = /<body[\s>]/i.exec(html);
85 const source = body === null ? html : html.slice(body.index);
86 for (const m of source.matchAll(/<!--[\s\S]*?-->|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*)>|([^<]+)/g)) {
87 if (done) break;
88 if (m[0].startsWith("<!--")) continue;
89 if (m[4] !== undefined) {
90 if (!(stack.at(-1)?.skip ?? false)) pending += decode(m[4]);
91 continue;
92 }
93 const name = m[2]!.toLowerCase();
94 const raw = m[0];
95 if (m[1] === "/") {
96 const at = stack.map((e) => e.name).lastIndexOf(name);
97 if (at < 0) continue;
98 const skipped = stack[at]!.skip;
99 stack.length = at;
100 if (!skipped && BLOCK.has(name)) flush();
101 continue;
102 }
103 const parent = stack.at(-1);
104 const classes = ` ${attr(raw, "class") ?? ""} `;
105 const skip =
106 (parent?.skip ?? false) ||
107 SKIP.has(name) ||
108 attr(raw, "hidden") !== undefined ||
109 /\ssr-only\s/.test(classes) ||
110 ((parent?.closed ?? false) && name !== "summary");
111 if (!skip) {
112 if (BLOCK.has(name)) flush();
113 if (/\s(muted|dim)\s/.test(classes)) pendingColours.push("muted");
114 if (name === "a" || name === "button") pendingColours.push("accent");
115 const tone = attr(raw, "data-tone");
116 if (tone !== undefined) pendingColours.push(`tone:${tone}`);
117 const series = attr(raw, "data-series");
118 if (series !== undefined) pendingColours.push(`series:${series}`);
119 }
120 if (VOID.has(name) || raw.endsWith("/>")) continue;
121 stack.push({ name, skip, closed: name === "details" && attr(raw, "open") === undefined });
122 }
123 flush();
124 return { words, blocks, colours: colours.size };
125 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs