@byronbroughten/code-style 0.0.0 → 0.1.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.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # @byronbroughten/code-style
2
+
3
+ General tooling for TypeScript projects: an ESLint flat-config preset, the prettier config, a base tsconfig, a doc linter and the general style docs. Plain JS, no build step; one version of each peer (eslint, prettier, typescript) is needed only for the export that uses it.
4
+
5
+ | Export | Consume it with |
6
+ | --- | --- |
7
+ | `@byronbroughten/code-style/eslint` | `eslintPreset` spread first in `defineConfig(...)`, with project rules after it. `styleSyntax` and `variableNaming` are exported for a project block that overrides `no-restricted-syntax` or `@typescript-eslint/naming-convention`. |
8
+ | `@byronbroughten/code-style/prettier` | `"prettier": "@byronbroughten/code-style/prettier"` in `package.json`. |
9
+ | `@byronbroughten/code-style/tsconfig.base.json` | `"extends"` in a `tsconfig.json`, which adds its own `target`, `module` and `types`. |
10
+ | `lint-docs` (bin) | A `package.json` script such as `"lint:docs": "lint-docs --published packages/<name>"`. It lints the git repo it runs in; see below. |
11
+ | `docs/code-style.md` (files) | Read from `node_modules/@byronbroughten/code-style/docs/`, with its reasoning under `docs/code-style/`. A project keeps its own style doc for the rules only it needs and says it layers on this one, as the framework's does. |
12
+
13
+ ## The doc linter
14
+
15
+ `lint-docs` lists the repo's tracked and new files via git and checks its markdown docs, exiting non-zero on a violation:
16
+
17
+ - **Links and anchors** resolve, in `AGENTS.md`, `CLAUDE.md`, `GLOSSARY.md`, `README.md`, every `SKILL.md`, and every `docs/` file at the repo root, under `config/` and under `packages/<name>/`. A link into a `packages/<name>/` folder the repo doesn't track is external and not checked, so a root doc can point at clones that exist only locally.
18
+ - **`--published <dir>`**, repeatable, names each package whose docs (`docs/`, `GLOSSARY.md`, `README.md`, `AGENTS.md` and `CLAUDE.md`) ship on their own, so they link only inside it: `packages/<name>`, `config` (this package, in a repo that holds it as a workspace folder), or `.` for the repo root, either relative to the repo root wherever the bin runs. Anything else, or a folder the repo doesn't track, is an error, and without the flag no package is held to the rule.
19
+ - **Leads and headings**: a `docs/` file's lead before its first `##` heading, and a file with no `##` heading at all, stay within the `limits` in `docLint.js`.
20
+ - **No line-number citations**: a `<name>.md:<n>` anywhere in a markdown file outside a fenced block is reported, since a line number drifts and an anchor is checked. Records that cite lines at a fixed commit on purpose are exempt: `writing/agent-drafts/`, `inbox/changes.md` and `inbox/proposals.md`, each relative to its repo or package root.
21
+ - **No links to a README from anything but a README**: a README is for humans, so a markdown file that isn't one may not link a `README.md`, and should link the fact's own home instead. Records are exempt, as above.
22
+ - **Observation indexes**: in each file `observationIndexes` in `docLint.js` lists, every bullet after the first `##` heading starts with `Observed:` or `Documented:`, carries a `YYYY-MM-DD` date and holds a link.
23
+ - **Skill index**: the file `skillIndex.doc` in `docLint.js` names, when the repo has it, links the `SKILL.md` of every skill under `.claude/skills/` or `runner/skills/`.
24
+ - **Each nested `AGENTS.md`** has a sibling `CLAUDE.md` containing `@AGENTS.md`.
25
+
26
+ ## Releasing
27
+
28
+ Bump `version` in `package.json`, commit, and push a `v<version>` tag. The Publish workflow checks the package and publishes that version to npm with provenance, through npm trusted publishing; nothing is published from a laptop.
package/docLint.js ADDED
@@ -0,0 +1,451 @@
1
+ // @ts-check
2
+ // Checks a repo's agent-facing docs' links, size limits, observation lines and skill index; a doc map in, violations out. lintDocs.js runs it on the repo it is invoked in.
3
+ import { posix } from "node:path";
4
+
5
+ const limits = {
6
+ leadLines: 5,
7
+ leadBytes: 800,
8
+ unheadedDocBytes: 4 * 1024,
9
+ };
10
+ const linkedFileNames = {
11
+ atRoot: new Set(["AGENTS.md", "CLAUDE.md", "GLOSSARY.md", "README.md"]),
12
+ anywhere: new Set(["AGENTS.md", "CLAUDE.md", "SKILL.md"]),
13
+ };
14
+ const workspaceFolders = new Set(["config"]);
15
+ // Records that cite lines at a fixed commit on purpose, relative to their doc root.
16
+ const recordPrefixes = [
17
+ "writing/agent-drafts/",
18
+ "inbox/changes.md",
19
+ "inbox/proposals.md",
20
+ ];
21
+ // Docs whose every line under a `##` heading records one tagged, dated, linked observation, relative to their repo root.
22
+ const observationIndexes = new Set([
23
+ "docs/agents/codebase-priorities/estimates.md",
24
+ "docs/claude-code-behaviour.md",
25
+ "docs/google-docs-behaviour.md",
26
+ "docs/sheets-behaviour.md",
27
+ ]);
28
+ const skillIndex = {
29
+ // The doc that must link every skill's SKILL.md, relative to its repo root.
30
+ doc: "docs/agents/workflows.md",
31
+ // A skill is a folder holding a SKILL.md under one of these roots; a symlinked skill is tracked only at its target.
32
+ skillPattern: /^(?:\.claude|runner)\/skills\/([^/]+)\/SKILL\.md$/,
33
+ };
34
+
35
+ /** @typedef {Record<string, string>} Docs */
36
+ /** @typedef {{ path: string, line: number, message: string }} Violation */
37
+ /** @typedef {(line: number, message: string) => void} Report */
38
+ /** @typedef {{ docs: Docs, known: Set<string>, trackedRoots: Set<string>, published: Set<string>, slugsOf: (path: string) => Set<string>, report: Report }} LinkContext */
39
+ /** @typedef {{ line: number, content: string }} ProseLine */
40
+ /** @typedef {{ line: number, target: string }} Link */
41
+
42
+ /**
43
+ * `docs` maps every markdown path to its contents; `paths` lists the other repo files and folders a link may name.
44
+ * @param {{ docs: Docs, paths?: string[], published?: string[] }} args
45
+ * @returns {Violation[]}
46
+ */
47
+ export function checkDocs({ docs, paths = [], published = [] }) {
48
+ const known = new Set([...Object.keys(docs), ...paths]);
49
+ const trackedRoots = rootsOf(known);
50
+ const publishedRoots = new Set(
51
+ published.map((root) => normalizeRoot(root, trackedRoots)),
52
+ );
53
+ const slugs = new Map();
54
+ /** @param {string} path */
55
+ function slugsOf(path) {
56
+ if (!slugs.has(path)) slugs.set(path, headingSlugs(docs[path] ?? ""));
57
+ return slugs.get(path) ?? new Set();
58
+ }
59
+ /** @type {Violation[]} */
60
+ const violations = [];
61
+ for (const [path, text] of Object.entries(docs)) {
62
+ /** @type {Report} */
63
+ function report(line, message) {
64
+ violations.push({ path, line, message });
65
+ }
66
+ if (isLinkChecked(path)) {
67
+ checkLinks(path, text, {
68
+ docs,
69
+ known,
70
+ trackedRoots,
71
+ published: publishedRoots,
72
+ slugsOf,
73
+ report,
74
+ });
75
+ }
76
+ if (!isRecord(path)) {
77
+ checkLineCitations(text, report);
78
+ if (posix.basename(path) !== "README.md") checkReadmeLinks(text, report);
79
+ }
80
+ if (isDocsFolderFile(path)) checkLead(text, report);
81
+ if (observationIndexes.has(path)) checkObservations(text, report);
82
+ if (posix.basename(path) === "AGENTS.md" && path !== "AGENTS.md") {
83
+ checkClaudePairing(path, docs, report);
84
+ }
85
+ }
86
+ violations.push(...skillIndexViolations(docs));
87
+ return violations;
88
+ }
89
+
90
+ // The repo root, a workspace folder such as `config`, or the `packages/<name>` folder, that holds the doc.
91
+ /** @param {string} path */
92
+ function docRoot(path) {
93
+ const parts = path.split("/");
94
+ const top = parts[0] ?? "";
95
+ if (top === "packages" && parts.length > 2) {
96
+ return parts.slice(0, 2).join("/");
97
+ }
98
+ return workspaceFolders.has(top) && parts.length > 1 ? top : "";
99
+ }
100
+
101
+ // `path` relative to its doc root.
102
+ /** @param {string} path */
103
+ function inRoot(path) {
104
+ const root = docRoot(path);
105
+ return root === "" ? path : path.slice(root.length + 1);
106
+ }
107
+
108
+ /** @param {string} path */
109
+ function isDocsFolderFile(path) {
110
+ return inRoot(path).startsWith("docs/");
111
+ }
112
+
113
+ /** @param {string} path */
114
+ function isRecord(path) {
115
+ const local = inRoot(path);
116
+ return recordPrefixes.some((prefix) => local.startsWith(prefix));
117
+ }
118
+
119
+ /** @param {string} path */
120
+ function isLinkChecked(path) {
121
+ const name = posix.basename(path);
122
+ const local = inRoot(path);
123
+ if (!local.includes("/")) return linkedFileNames.atRoot.has(local);
124
+ return isDocsFolderFile(path) || linkedFileNames.anywhere.has(name);
125
+ }
126
+
127
+ // The repo root is "", a workspace folder is its name and a package is `packages/<name>`, however the caller spells it; an untracked one is a typo, not a no-op.
128
+ /**
129
+ * @param {string} root
130
+ * @param {Set<string>} trackedRoots
131
+ */
132
+ function normalizeRoot(root, trackedRoots) {
133
+ const normal = posix.normalize(root).replace(/\/$/, "");
134
+ if (normal === ".") return "";
135
+ if (packageRootOf(normal) !== normal && !workspaceFolders.has(normal)) {
136
+ const folders = [...workspaceFolders].map((folder) => `"${folder}", `);
137
+ throw new Error(
138
+ `published must be ".", ${folders.join("")}or packages/<name>, not ${root}`,
139
+ );
140
+ }
141
+ if (!trackedRoots.has(normal)) {
142
+ throw new Error(`published package ${root} has no tracked files`);
143
+ }
144
+ return normal;
145
+ }
146
+
147
+ // The `packages/<name>` folder a path is in or is.
148
+ /** @param {string} path */
149
+ function packageRootOf(path) {
150
+ return /^packages\/[^/]+/.exec(path)?.[0];
151
+ }
152
+
153
+ // The workspace and `packages/<name>` folders that hold at least one tracked path.
154
+ /** @param {Set<string>} known */
155
+ function rootsOf(known) {
156
+ const roots = new Set();
157
+ for (const path of known) {
158
+ const root = docRoot(path);
159
+ if (root) roots.add(root);
160
+ }
161
+ return roots;
162
+ }
163
+
164
+ /**
165
+ * @param {string} resolved
166
+ * @param {string} root
167
+ */
168
+ function isInside(resolved, root) {
169
+ if (root === "") return resolved !== ".." && !resolved.startsWith("../");
170
+ return resolved.startsWith(`${root}/`);
171
+ }
172
+
173
+ /**
174
+ * @param {string} path
175
+ * @param {string} text
176
+ * @param {LinkContext} context
177
+ */
178
+ function checkLinks(
179
+ path,
180
+ text,
181
+ { docs, known, trackedRoots, published, slugsOf, report },
182
+ ) {
183
+ // A published package ships without the rest of the repo, so each checked doc in it must stand alone.
184
+ const publishedIn = published.has(docRoot(path)) ? docRoot(path) : undefined;
185
+ const scope = publishedIn === "" ? "the repo" : publishedIn;
186
+ for (const { line, target } of linksIn(text)) {
187
+ const hashAt = target.indexOf("#");
188
+ const file = fileOf(target);
189
+ const anchor =
190
+ hashAt === -1 ? null : decodeURIComponent(target.slice(hashAt + 1));
191
+ const resolved = file === "" ? path : resolveLink(path, file);
192
+ if (publishedIn !== undefined && !isInside(resolved, publishedIn)) {
193
+ report(
194
+ line,
195
+ `link ${target} leaves ${scope}; its published docs link only inside ${scope}`,
196
+ );
197
+ }
198
+ if (isUntrackedPackagePath(resolved, trackedRoots)) continue;
199
+ if (!known.has(resolved)) {
200
+ report(line, `broken link ${target}: no file ${resolved}`);
201
+ continue;
202
+ }
203
+ if (anchor === null || !(resolved in docs)) continue;
204
+ if (!slugsOf(resolved).has(anchor)) {
205
+ report(
206
+ line,
207
+ `broken anchor ${target}: no heading slugs to ${anchor} in ${resolved}`,
208
+ );
209
+ }
210
+ }
211
+ }
212
+
213
+ // A checkout that lacks a package (the private root without its clones) can't say whether a path in it exists, so a link into it is external.
214
+ /**
215
+ * @param {string} resolved
216
+ * @param {Set<string>} trackedRoots
217
+ */
218
+ function isUntrackedPackagePath(resolved, trackedRoots) {
219
+ const root = packageRootOf(resolved);
220
+ return root !== undefined && !trackedRoots.has(root);
221
+ }
222
+
223
+ // A link target's file part, before any `#anchor`, decoded.
224
+ /** @param {string} target */
225
+ function fileOf(target) {
226
+ const hashAt = target.indexOf("#");
227
+ return decodeURIComponent(hashAt === -1 ? target : target.slice(0, hashAt));
228
+ }
229
+
230
+ /**
231
+ * @param {string} from
232
+ * @param {string} file
233
+ */
234
+ function resolveLink(from, file) {
235
+ const joined = file.startsWith("/")
236
+ ? file.slice(1)
237
+ : posix.join(posix.dirname(from), file);
238
+ return posix.normalize(joined).replace(/\/$/, "");
239
+ }
240
+
241
+ /**
242
+ * @param {string} text
243
+ * @returns {Link[]}
244
+ */
245
+ function linksIn(text) {
246
+ /** @type {Link[]} */
247
+ const links = [];
248
+ for (const { line, content } of proseLines(text)) {
249
+ const bare = content.replace(/`[^`]*`/g, "");
250
+ for (const match of bare.matchAll(
251
+ /\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g,
252
+ )) {
253
+ links.push({ line, target: match[1] ?? "" });
254
+ }
255
+ const reference = /^\s*\[[^\]]+\]:\s*(\S+)/.exec(bare);
256
+ if (reference) links.push({ line, target: reference[1] ?? "" });
257
+ }
258
+ return links.filter(({ target }) => !/^[a-z][a-z0-9+.-]*:/i.test(target));
259
+ }
260
+
261
+ // Lines outside fenced code blocks, numbered from 1.
262
+ /**
263
+ * @param {string} text
264
+ * @returns {ProseLine[]}
265
+ */
266
+ function proseLines(text) {
267
+ /** @type {ProseLine[]} */
268
+ const lines = [];
269
+ /** @type {string | null} */
270
+ let fence = null;
271
+ text.split("\n").forEach((content, index) => {
272
+ const opener = /^\s*(```|~~~)/.exec(content);
273
+ if (opener) {
274
+ if (fence === null) fence = opener[1] ?? null;
275
+ else if (opener[1] === fence) fence = null;
276
+ return;
277
+ }
278
+ if (fence === null) lines.push({ line: index + 1, content });
279
+ });
280
+ return lines;
281
+ }
282
+
283
+ // GitHub's slugger: lowercase, drop everything but letters, marks, numbers, spaces, `-` and `_`, then spaces to `-`.
284
+ /** @param {string} text */
285
+ function headingSlugs(text) {
286
+ const slugs = new Set();
287
+ const seen = new Map();
288
+ for (const { content } of proseLines(text)) {
289
+ const heading = /^#{1,6}\s+(.*?)\s*#*\s*$/.exec(content);
290
+ if (!heading) continue;
291
+ const rendered = (heading[1] ?? "")
292
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
293
+ .replace(/[`*]/g, "");
294
+ const base = rendered
295
+ .toLowerCase()
296
+ .replace(/[^\p{L}\p{M}\p{N} _-]/gu, "")
297
+ .replace(/ /g, "-");
298
+ const count = seen.get(base) ?? 0;
299
+ seen.set(base, count + 1);
300
+ slugs.add(count === 0 ? base : `${base}-${count}`);
301
+ }
302
+ return slugs;
303
+ }
304
+
305
+ // A line number drifts with every edit above it; a heading anchor is checked by checkLinks.
306
+ /**
307
+ * @param {string} text
308
+ * @param {Report} report
309
+ */
310
+ function checkLineCitations(text, report) {
311
+ proseLines(text).forEach(({ line, content }) => {
312
+ Array.from(content.matchAll(/[\w./-]+\.md:\d+/g)).forEach(([citation]) => {
313
+ report(
314
+ line,
315
+ `line-number citation ${citation}; cite a heading anchor, since a line number drifts`,
316
+ );
317
+ });
318
+ });
319
+ }
320
+
321
+ // The wording alone didn't keep agent facts out of READMEs, so a non-README doc can't send an agent to one.
322
+ /**
323
+ * @param {string} text
324
+ * @param {Report} report
325
+ */
326
+ function checkReadmeLinks(text, report) {
327
+ linksIn(text).forEach(({ line, target }) => {
328
+ if (posix.basename(fileOf(target)) === "README.md") {
329
+ report(line, "A README is for humans; link the fact's home instead.");
330
+ }
331
+ });
332
+ }
333
+
334
+ // A read-by-heading doc's lead: the non-blank lines after its title and before its first `##` heading.
335
+ /**
336
+ * @param {string} text
337
+ * @param {Report} report
338
+ */
339
+ function checkLead(text, report) {
340
+ const lines = proseLines(text);
341
+ const firstSection = firstSectionIndex(lines);
342
+ if (firstSection === -1) {
343
+ const bytes = byteLength(text);
344
+ if (bytes > limits.unheadedDocBytes) {
345
+ report(
346
+ 1,
347
+ `doc is ${bytes} bytes with no ## heading; over ${limits.unheadedDocBytes} bytes, give it a short lead and ## headings so it can be read by section`,
348
+ );
349
+ }
350
+ return;
351
+ }
352
+ const lead = lines
353
+ .slice(0, firstSection)
354
+ .filter(({ content }) => content.trim() !== "" && !/^#\s/.test(content));
355
+ const leadLine = lead[0]?.line ?? 1;
356
+ if (lead.length > limits.leadLines) {
357
+ report(
358
+ leadLine,
359
+ `lead is ${lead.length} lines before the first ## heading; keep it to ${limits.leadLines} and move the rest under a heading`,
360
+ );
361
+ return;
362
+ }
363
+ const bytes = byteLength(lead.map(({ content }) => content).join("\n"));
364
+ if (bytes > limits.leadBytes) {
365
+ report(
366
+ leadLine,
367
+ `lead is ${bytes} bytes before the first ## heading; keep it to ${limits.leadBytes} and move the rest under a heading`,
368
+ );
369
+ }
370
+ }
371
+
372
+ // Each bullet after the first `##` heading; the lead's bullets describe the index rather than record an observation.
373
+ /**
374
+ * @param {string} text
375
+ * @param {Report} report
376
+ */
377
+ function checkObservations(text, report) {
378
+ const lines = proseLines(text);
379
+ const firstSection = firstSectionIndex(lines);
380
+ if (firstSection === -1) return;
381
+ for (const { line, content } of lines.slice(firstSection)) {
382
+ const bullet = /^\s*[-*]\s+(.*)$/.exec(content)?.[1];
383
+ if (bullet === undefined) continue;
384
+ if (!/^(Observed|Documented):/.test(bullet)) {
385
+ report(
386
+ line,
387
+ 'observation line starts with neither "Observed:" nor "Documented:"',
388
+ );
389
+ }
390
+ if (!/\b\d{4}-\d{2}-\d{2}\b/.test(bullet)) {
391
+ report(line, "observation line has no YYYY-MM-DD date");
392
+ }
393
+ if (!/\]\([^)\s]+\)/.test(bullet.replace(/`[^`]*`/g, ""))) {
394
+ report(line, "observation line links no evidence");
395
+ }
396
+ }
397
+ }
398
+
399
+ /**
400
+ * @param {Docs} docs
401
+ * @returns {Violation[]}
402
+ */
403
+ function skillIndexViolations(docs) {
404
+ const index = docs[skillIndex.doc];
405
+ if (index === undefined) return [];
406
+ const linked = new Set(
407
+ linksIn(index).map(({ target }) =>
408
+ resolveLink(skillIndex.doc, fileOf(target)),
409
+ ),
410
+ );
411
+ return Object.keys(docs).flatMap((doc) => {
412
+ const skill = skillIndex.skillPattern.exec(doc)?.[1];
413
+ if (skill === undefined || linked.has(doc)) return [];
414
+ return [
415
+ {
416
+ path: skillIndex.doc,
417
+ line: 1,
418
+ message: `skill ${skill} is not linked; place ${doc} in a Workflow stage or the out-of-scope list`,
419
+ },
420
+ ];
421
+ });
422
+ }
423
+
424
+ // The index of the first `##` heading among a doc's prose lines, or -1.
425
+ /** @param {ProseLine[]} lines */
426
+ function firstSectionIndex(lines) {
427
+ return lines.findIndex(({ content }) => /^##\s/.test(content));
428
+ }
429
+
430
+ /** @param {string} text */
431
+ function byteLength(text) {
432
+ return new TextEncoder().encode(text).length;
433
+ }
434
+
435
+ /**
436
+ * @param {string} path
437
+ * @param {Docs} docs
438
+ * @param {Report} report
439
+ */
440
+ function checkClaudePairing(path, docs, report) {
441
+ const claude = posix.join(posix.dirname(path), "CLAUDE.md");
442
+ const importsIt = (docs[claude] ?? "")
443
+ .split("\n")
444
+ .some((line) => line.trim() === "@AGENTS.md");
445
+ if (!importsIt) {
446
+ report(
447
+ 1,
448
+ `no sibling CLAUDE.md importing it; add ${claude} containing @AGENTS.md`,
449
+ );
450
+ }
451
+ }
@@ -0,0 +1,63 @@
1
+ # Class shape
2
+
3
+ Style fragment. The one-line rules live in [`docs/code-style.md`](../code-style.md); this file holds the reasoning and the worked examples.
4
+
5
+ One heading per class-shape rule, most of them with the refactor that produced it; a sub-rule either has a heading of its own or shares the heading before it, and the collaborator-naming rule's reasoning is in [`naming.md`](./naming.md#a-collaborator-is-subjectrole). Grep `^## ` for the rule you're applying and read that section.
6
+
7
+ ## Extract the shared piece once its second caller is in the code or an open ticket
8
+
9
+ Keeping a helper private until a second call site actually exists is the wrong default here. When the sibling caller is already visible — another table of the same shape, another handler of the same family — build the shared class now and put it beside its siblings. A name-to-ID resolver that two handlers obviously want is written as a general class for its first caller. The same judgment governs behaviour a caller asks for: build the general form rather than the one fitted to the caller that asked, so per-row reporting serves any handler instead of only the batch one that motivated it. This is not licence to build for imagined callers; a feature nobody has asked for still waits. The test is a fact to check, not a judgement: the second caller is in the code or in an open ticket. A caller someone could only argue for doesn't count, since an agent can always name one.
10
+
11
+ ## Inherit identity and state, compose behaviour
12
+
13
+ A class extends a Base for where it is (its address and the handle to shared state) and gets what it does from collaborators it builds or reaches through a getter. In the framework, every Table, row, column and cell class extends its level's Base for its `tableId`, `rowIndex` or `columnName`, while a coordinator builds its collaborators in lazy getters, a column reaches its Table through `table`, and an Operator reaches its subject through a getter rather than extending the concrete class. This is the usual "inherit for is-a, compose for has-a" split, and it has no exception: a split class's Base shares behaviour among its collaborators by building helper classes, not by holding the helpers itself ([below](#a-split-class-shares-a-base-and-layers-its-collaborators)).
14
+
15
+ ## Class member order
16
+
17
+ 1. `static init()`
18
+ 2. Plain getters for derived collaborators/state (`schema`, `client`, ...)
19
+ 3. Public behavior methods
20
+ 4. Private helpers, `_`-prefixed — ordered so a helper used by only one caller sits immediately after that caller (detail follows the step that needs it); a helper reused by several later methods comes first, in the order of its first use. (`_loadAccess`/`_hasAccess`, each used by multiple methods, sit first; `_pruneRows`, called only by `_syncRows`, sits directly after it.)
21
+
22
+ ## A helper that never reads `this` is a module function
23
+
24
+ A private helper with zero references to `this` depends on nothing the instance holds, so it leaves the class: an unexported function below the class, with the moved functions ordered by their first use in the class. Every private helper left in the class body then depends on instance state, and a reader can tell the two kinds of helper apart without reading each body. Keeping it unexported means the move doesn't widen the module's interface. A random-suffix generator that never touched the instance began as a private method on a schema class and became such a function.
25
+
26
+ - A helper on one collaborator's state moves onto the collaborator, not below the class: `Report._finalizeRows(table, state)` became `Table.finalizeRows()`.
27
+ - A helper that reaches `this` only for a collaborator stays because moving it out would mean passing the collaborator in, which is the threading this file warns against.
28
+ - A public method stays put because it is part of the class's interface, not a helper.
29
+ - A helper that only renames a function goes, and its callers call that function: `Schema.config` wrapped the imported `configGet` with the same signature.
30
+ - An object bundle is named for the subject and written with method shorthand, so the names shorten and the group reads as one unit (`color.fromRgb`, `rows.index`).
31
+ - A helper class holds the value its helpers kept passing, so their signatures stop threading it. A project that builds collaborators a particular way says so in its own style doc.
32
+
33
+ ## Delete dead scaffolding you touch — with one exception
34
+
35
+ Editing a file is the moment to remove, not preserve, a stub nothing calls, a placeholder function (`function triggerAuth(): void { return; }`), or a variable instantiated and discarded (`const parser = Parser.init();` with no use of `parser`). An empty function body is better than a dead unused variable or an unreferenced helper kept "in case."
36
+
37
+ **Exception: commented-out code.** Flag it and ask before deleting — don't remove it as part of a cleanup pass. It might be an intentional breadcrumb rather than leftover cruft.
38
+
39
+ **Zero callers is not proof of dead.** Some members are parked for planned work and carry no marker distinguishing them from cruft: a `Table.clearIndexStale` or a `requestSort` that nothing calls yet may be intentional. A grep-derived list of uncalled members is a set of candidates, not a verdict: name what you found and ask, rather than deleting on the count. A member whose only caller is a test is a third case again — deleting it deletes coverage.
40
+
41
+ ## One class per file
42
+
43
+ A file named for a class holds only that class, so the file name tells a reader everything in it. There are no exceptions, custom `Error` subclasses included; `max-classes-per-file` enforces it. A helper type or free function that serves one class lives in that class's file.
44
+
45
+ Splitting a class family can close an import cycle through an `extends` clause, which fails at load time because the base class isn't defined yet when the subclass file runs.
46
+
47
+ ## Keep "why" comments across a refactor
48
+
49
+ A comment explaining a non-obvious invariant (e.g. why two tables must be written in one transaction) carries over verbatim across a restructure — it documents the invariant, not the code shape around it.
50
+
51
+ ## Split a class when its helpers fall into groups that share nothing
52
+
53
+ A method or line count says how big a class is, not whether it holds separate concerns; private helpers that fall into groups calling nothing in each other's group do. A line count may trigger a look but is never a lint, since byro-repo's [ADR-0012](https://github.com/byronbroughten/byro-repo/blob/master/docs/adr/0012-replace-agents-md-size-caps-with-a-stated-cost-of-adding.md) found that size caps act as targets. `SpecRun` grew into one class whose methods an agent had to grep by phase rather than read, and its split gave each phase's helpers a collaborator of their own (#344). The class keeps its public methods as one-line delegations, so its callers don't change, and the subfolder named after it keeps the collaborators together.
54
+
55
+ ## A split class shares a Base and layers its collaborators
56
+
57
+ Without a Base, a helper two collaborators share lives in one of them, and the other reaches sideways for it or copies it. `SpecRun`'s split (#344) put its config, the progress log and notices, the run-state file and the git snapshots on `SpecRunBase`, as helper methods. That made the Base the next large class: each helper that picked up a second caller moved up and nothing moved it back, so it reached about 30 `protected` helpers in groups that share nothing, which the split rule above would itself split. Every collaborator also inherited all of them, so an agent couldn't tell from a collaborator's imports which it relied on.
58
+
59
+ So the Base keeps only the props and builds the shared behaviour as helper classes in lazy getters, as `SpecRunBase` already built `workspaces` and `factsFile`: a run-state file, a progress log, a snapshot taker, each its own file. An agent reads the small Base and the one helper class its concern uses. The helper classes don't extend the Base, so the Base can import them without the load-time cycle below. A shared helper that reads no state is a module function by the rule above, and a helper with one collaborator calling it stays in that collaborator.
60
+
61
+ With each collaborator building the ones below it and the Base importing none, a call only goes down, so a reader follows it into a file below and never traces a loop back up. The Base rule is also a load-time one: each collaborator's file runs `class X extends Base`, so a Base that imported a collaborator would reach that `extends` clause before the Base was defined, and fail. A method that sits in one group but calls into a group above moves down, to the lower group or to a helper class the Base builds; `SpecRun`'s split placed each method from a call graph built with the TypeScript compiler API, so that no call goes up (#344).
62
+
63
+ A getter back to the coordinator is the one upward reference allowed, for a coordinator that holds shared state of its own, since a circular import is safe while the coordinator only appears inside method bodies and never in an `extends` clause; a project's own style doc names its getters. `SpecRun` holds only delegations, so its collaborators have nothing to reach back for and build the ones below them instead.
@@ -0,0 +1,15 @@
1
+ # Comments: reasoning and examples
2
+
3
+ Disclosed from [`docs/code-style.md`](../code-style.md), "Comments". The rules are there, one line each; this file holds the examples and the why.
4
+
5
+ ## Pull a "what" comment into a named method
6
+
7
+ A block that would need a comment saying _what_ it does becomes a small private method whose name says it. `Importer._updateAll` split into `_deleteStaleRows`, `_appendMissingRows` and `_updateComputedValues`, and the call site now reads as the list of steps.
8
+
9
+ ## A comment explains a "why not the obvious thing"
10
+
11
+ A comment sits trailing or immediately above its line and never restates the line. `action: "boolean", // Should perhaps be "boolean" | "string"` is the shape: it tells the reader why the obvious value isn't there. A why that doesn't fit on one short line goes in a doc the comment links to: an ADR, or the reasoning file of the rule it follows. Otherwise it isn't written. An agent editing the code reads the file and the docs it links, but rarely the history, so a why kept only in a commit message never reaches it. The one line holds back the paragraph comments agents tend to write.
12
+
13
+ ## File-level navigation blocks
14
+
15
+ A navigation block is 5–10 lines immediately above the exported class, stating the file's job and where neighbouring work lives, so an agent opens the right sibling instead of the whole tier.
@@ -0,0 +1,11 @@
1
+ # Error handling: reasoning and examples
2
+
3
+ Disclosed from [`docs/code-style.md`](../code-style.md), "Error handling & validation". The rules are there, one line each; this file holds the why.
4
+
5
+ ## One function for a shared phrase
6
+
7
+ A phrase that names the same thing in several messages or labels comes from one function, so the wording can't drift between them. A `columnLabel(table, column)` used by every error and log line that names a column is the example.
8
+
9
+ ## Throw instead of skip-and-log
10
+
11
+ A defensive skip earns its place only when the condition can genuinely occur in valid, expected state. If upstream code already rules it out (a prior step corrects or prunes exactly this case), skip-and-log just buries a real failure in a log line. Throw instead. Example: `Table.columnEntries()` skipped rows missing `header`/`valueName`/a resolvable `tableId`. But `_correctHeaders` fixes `header` for every active row, the emit step samples `valueName` from the live column, and `_pruneRows` guarantees every surviving row's `tableId` resolves. So a row still failing one of those checks means the sync didn't actually complete, and now it throws.
@@ -0,0 +1,20 @@
1
+ # Imports and file organization: examples
2
+
3
+ Disclosed from [`docs/code-style.md`](../code-style.md), "Imports & file organization". The rules are there, one line each; this file holds the examples.
4
+
5
+ ## No barrel files
6
+
7
+ A package's declared public entries are its only barrels. Every other file is imported directly by its path, except a subfolder's pieces, which reach their importers through the same-named parent file that re-assembles them.
8
+
9
+ ## Re-assembling a subfolder isn't a barrel
10
+
11
+ A barrel costs in three ways: every importer loads everything behind it, it makes import cycles easy to create, and a bundler can't drop what it forwards. The first two reach test code as much as shipped code, so "tests never ship" doesn't exempt a test file. A parent re-assembling its own subfolder avoids the costs another way: its importers want the whole subject anyway, so routing the pieces through it loads nothing extra. `Obj.ts` users want `Obj`, and every SpecRun test already loads `runner/src/specRunHarness.ts` for its setup. A file that forwards unrelated files has no such subject, and is a barrel in any folder.
12
+
13
+ Each piece goes through whole: `Obj.ts` takes `merge` from `Obj/merge.ts` as it is, and a harness exports its `stepResults` bundle, not members picked out of it. A hand-picked list is a second copy of the piece's members that has to be kept in step, and the harness's had already drifted: a test imported the harness and `stepResults.commitFile` beside it, because the list left `commitFile` out. (R667.1 on byronbroughten/byro-repo#667)
14
+
15
+ ## File naming
16
+
17
+ - A class file mirrors its exported class: `RowImporter.ts`, `ConfigLoader.ts`.
18
+ - A static-bundle file takes a short abbreviation: `Str.ts` exports `Str`. A fat bundle's pieces split into a same-named subfolder, as `Obj/merge.ts` in `@byronbroughten/utils` does.
19
+ - Plain data, config and entry-point files are camelCase: `columnConfigs.ts`, `routes.ts`, `index.ts`.
20
+ - A module whose helpers fall into groups that share nothing splits by subject into a same-named subfolder: `HttpClient/headers.ts` exports `requestHeaders`.
@@ -0,0 +1,30 @@
1
+ # Functional vs. imperative idioms: examples
2
+
3
+ Disclosed from [`docs/code-style.md`](../code-style.md), "Functional vs. imperative idioms". The rules are there, one line each; this file holds the examples and the why.
4
+
5
+ ## `for…of` over `forEach`
6
+
7
+ `forEach` was the default once, for its look. `for…of` replaced it for three reasons:
8
+ - **It waits.** `forEach(async …)` starts every callback and returns before any finishes, without an error. `for…of` with `await` runs them in order.
9
+ - **It keeps narrowing.** TypeScript keeps a narrowed variable narrowed in a loop body, but can lose the narrowing inside a callback.
10
+ - **One form covers every loop.** An early exit (`break`, `continue`, `return`) and destructured `Map` entries no longer need their own exceptions.
11
+
12
+ ## `reduce` builds a new object
13
+
14
+ `reduce` builds a new object or record in place of a manual loop with a declared accumulator. The seed is a fresh `{}`, `new Map()` or `[]`, and each step mutates it and returns it: `(acc, item) => { acc[key] = ...; return acc; }`. Spreading it, `({ ...acc, ... })`, copies the whole accumulator on every item, which makes the build O(n²).
15
+
16
+ ## Mutators return `this`
17
+
18
+ A mutator method returns `this` so calls chain: `fetchAndUpdateAll(): this { ...; return this; }`.
19
+
20
+ ## A combined option is built from its parts
21
+
22
+ `prepFetch`'s `"all"` case calls itself for `"headers"`, `"actions"` and `"data"` rather than repeating their bodies.
23
+
24
+ ## `if`/`else` over a ternary
25
+
26
+ A ternary stays only for a single trivial value pick with no side effects. One inside `${}` must also fit on one line; otherwise it becomes a named local, so the template reads as text with names in it.
27
+
28
+ ## State is a named flag, not a trick
29
+
30
+ A wrapper object or a compact operator makes the reader reconstruct what state it encodes; a named variable and an explicit `if` state it. `lazy` tracks "already computed" with `let ready = false` and `if (!ready) { value = make(); ready = true; }`. It doesn't use `made ??= { value: make() }`, which needs a box to tell "computed as `undefined`" from "not computed" and hides that reason. The flag version is a few lines longer, but a reader doesn't have to derive why it's shaped that way.