architecture-harness 0.4.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 (109) hide show
  1. package/package.json +80 -0
  2. package/src/cli/check.mjs +535 -0
  3. package/src/cli/cli.test.mjs +120 -0
  4. package/src/cli/commit-attribution.mjs +68 -0
  5. package/src/cli/commit-attribution.test.mjs +47 -0
  6. package/src/cli/decisions.mjs +223 -0
  7. package/src/cli/doctor.mjs +135 -0
  8. package/src/cli/doctor.test.mjs +57 -0
  9. package/src/cli/init.mjs +98 -0
  10. package/src/cli/install-hooks.mjs +26 -0
  11. package/src/cli/qc.mjs +89 -0
  12. package/src/cli/scaffold.mjs +194 -0
  13. package/src/cli/sync-enforcement-map.mjs +28 -0
  14. package/src/cli/work-order-guard.mjs +0 -0
  15. package/src/cli/work-order-guard.test.mjs +79 -0
  16. package/src/cli/worktree-isolation.mjs +94 -0
  17. package/src/cli/worktree-isolation.test.mjs +82 -0
  18. package/src/config.mjs +338 -0
  19. package/src/config.test.mjs +59 -0
  20. package/src/decisions.mjs +198 -0
  21. package/src/decisions.test.mjs +183 -0
  22. package/src/descriptions.mjs +28 -0
  23. package/src/descriptions.test.mjs +27 -0
  24. package/src/enforcement-map.mjs +46 -0
  25. package/src/enforcement-map.test.mjs +60 -0
  26. package/src/eslint/index.mjs +37 -0
  27. package/src/eslint/options.mjs +53 -0
  28. package/src/eslint/preset.mjs +192 -0
  29. package/src/eslint/preset.test.mjs +96 -0
  30. package/src/eslint/rules/durable-idempotency-key.mjs +120 -0
  31. package/src/eslint/rules/external-service-only-in-adapter.mjs +52 -0
  32. package/src/eslint/rules/module-boundary.mjs +12 -0
  33. package/src/eslint/rules/name-the-pattern.mjs +111 -0
  34. package/src/eslint/rules/no-comment-paragraph.mjs +101 -0
  35. package/src/eslint/rules/no-cross-feature-internals.mjs +57 -0
  36. package/src/eslint/rules/no-number-in-comment.mjs +89 -0
  37. package/src/eslint/rules/no-offset-pagination.mjs +29 -0
  38. package/src/eslint/rules/no-orchestration-in-trigger.mjs +56 -0
  39. package/src/eslint/rules/no-promise-then.mjs +43 -0
  40. package/src/eslint/rules/no-promise-then.test.mjs +63 -0
  41. package/src/eslint/rules/no-raw-fetch.mjs +27 -0
  42. package/src/eslint/rules/no-status-literal.mjs +34 -0
  43. package/src/eslint/rules/no-supersession-trail.mjs +51 -0
  44. package/src/eslint/rules/scoped-repository.mjs +43 -0
  45. package/src/eslint/rules/signal-last-param.mjs +43 -0
  46. package/src/eslint/rules/storage-only-in-resource.mjs +52 -0
  47. package/src/eslint/rules/tenant-scoped-table.mjs +71 -0
  48. package/src/eslint/rules.test.mjs +627 -0
  49. package/src/gates/adr-format.mjs +87 -0
  50. package/src/gates/adr-format.test.mjs +54 -0
  51. package/src/gates/audit-append-only.mjs +34 -0
  52. package/src/gates/audit-append-only.test.mjs +36 -0
  53. package/src/gates/citations.mjs +93 -0
  54. package/src/gates/citations.test.mjs +115 -0
  55. package/src/gates/claimed-requirements.mjs +53 -0
  56. package/src/gates/claimed-requirements.test.mjs +60 -0
  57. package/src/gates/comment-style.mjs +76 -0
  58. package/src/gates/comment-style.test.mjs +46 -0
  59. package/src/gates/config-floor.mjs +68 -0
  60. package/src/gates/config-floor.test.mjs +52 -0
  61. package/src/gates/contract-compose.mjs +38 -0
  62. package/src/gates/contract-compose.test.mjs +40 -0
  63. package/src/gates/eight-blocks.mjs +223 -0
  64. package/src/gates/eight-blocks.test.mjs +359 -0
  65. package/src/gates/enforcement-map.mjs +62 -0
  66. package/src/gates/enforcement-map.test.mjs +41 -0
  67. package/src/gates/english-source.mjs +176 -0
  68. package/src/gates/english-source.test.mjs +122 -0
  69. package/src/gates/frontend-boundaries.mjs +154 -0
  70. package/src/gates/frontend-boundaries.test.mjs +72 -0
  71. package/src/gates/gate-tests.mjs +44 -0
  72. package/src/gates/gate-tests.test.mjs +41 -0
  73. package/src/gates/headless-sagas.mjs +54 -0
  74. package/src/gates/headless-sagas.test.mjs +71 -0
  75. package/src/gates/internal-routes.mjs +76 -0
  76. package/src/gates/internal-routes.test.mjs +53 -0
  77. package/src/gates/public-routes.mjs +67 -0
  78. package/src/gates/public-routes.test.mjs +38 -0
  79. package/src/gates/registry-agreement.mjs +37 -0
  80. package/src/gates/registry-agreement.test.mjs +36 -0
  81. package/src/gates/saga-tests.mjs +94 -0
  82. package/src/gates/saga-tests.test.mjs +92 -0
  83. package/src/gates/sql-identifiers.mjs +244 -0
  84. package/src/gates/sql-identifiers.test.mjs +197 -0
  85. package/src/gates/tenant-predicate.mjs +175 -0
  86. package/src/gates/tenant-predicate.test.mjs +161 -0
  87. package/src/gates/tenant-tables.mjs +65 -0
  88. package/src/gates/tenant-tables.test.mjs +56 -0
  89. package/src/gates/test-mirror.mjs +47 -0
  90. package/src/gates/test-mirror.test.mjs +31 -0
  91. package/src/index.mjs +9 -0
  92. package/templates/.jscpd.json +15 -0
  93. package/templates/CLAUDE.md +54 -0
  94. package/templates/decisions.examples.md +25 -0
  95. package/templates/docs/adr-template.md +58 -0
  96. package/templates/docs/architecture.md +179 -0
  97. package/templates/docs/decisions.md +72 -0
  98. package/templates/docs/enforcement.md +94 -0
  99. package/templates/docs/glossary.md +16 -0
  100. package/templates/docs/guards.md +23 -0
  101. package/templates/docs/pagination.md +113 -0
  102. package/templates/docs/performance.md +35 -0
  103. package/templates/docs/ui.md +32 -0
  104. package/templates/githooks/commit-msg +4 -0
  105. package/templates/githooks/pre-commit +18 -0
  106. package/templates/githooks/pre-push +6 -0
  107. package/templates/github/workflows/ci.yml +21 -0
  108. package/templates/qc.config.json +6 -0
  109. package/templates/quality-thresholds.json +114 -0
@@ -0,0 +1,96 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { defaults, merge } from "../config.mjs";
4
+ import { rules as allRules } from "./index.mjs";
5
+ import { preset } from "./preset.mjs";
6
+
7
+ const config = (override = {}) => ({ ...merge(defaults, override), root: process.cwd() });
8
+
9
+ /**
10
+ * Every `qc/*` entry the preset turns on. The tooling block relaxes all of them and
11
+ * comes last, so a plain last-write-wins read would see only `off`.
12
+ */
13
+ function emitted(blocks) {
14
+ const out = new Map();
15
+ for (const block of blocks) {
16
+ for (const [name, setting] of Object.entries(block.rules ?? {})) {
17
+ if (!name.startsWith("qc/")) continue;
18
+ if (setting === "off") continue;
19
+ out.set(name, setting);
20
+ }
21
+ }
22
+ return out;
23
+ }
24
+
25
+ test("every rule the config enables reaches the preset", () => {
26
+ // Against an all-on config: a policy rule ships off, and this asks whether a rule *can* reach
27
+ // the preset, not which ones are in force by default.
28
+ const blocks = preset({ config: config({ rules: Object.fromEntries(Object.keys(allRules).map((n) => [n, true])) }) });
29
+ const on = emitted(blocks);
30
+ for (const name of Object.keys(allRules)) {
31
+ assert.ok(on.has(`qc/${name}`), `qc/${name} never reaches the lint config`);
32
+ }
33
+ });
34
+
35
+ // The failure this guards: a switch flipped off that quietly stays on, or a rule
36
+ // renamed so its switch no longer reaches it.
37
+ test("a rule switched off in config is not emitted as an error", () => {
38
+ const blocks = preset({ config: config({ rules: { "no-raw-fetch": false } }) });
39
+ const settings = [];
40
+ for (const block of blocks) {
41
+ const setting = (block.rules ?? {})["qc/no-raw-fetch"];
42
+ if (setting !== undefined) settings.push(setting);
43
+ }
44
+ assert.ok(!settings.includes("error"), "a disabled rule is still set to error");
45
+ assert.ok(settings.every((s) => s === "off" || (Array.isArray(s) && s[0] !== "error")));
46
+ });
47
+
48
+ test("a rule's options come from the config, not from its own defaults", () => {
49
+ const blocks = preset({ config: config({ apiClient: "net/http.ts" }) });
50
+ const setting = emitted(blocks).get("qc/no-raw-fetch");
51
+ assert.ok(Array.isArray(setting), "no-raw-fetch should carry options");
52
+ assert.equal(setting[1].client, "net/http.ts");
53
+ });
54
+
55
+ test("the tooling block turns every qc rule off, so a gate can name what it bans", () => {
56
+ const blocks = preset({ config: config() });
57
+ const tooling = blocks.find((b) => JSON.stringify(b.files) === JSON.stringify(defaults.toolingFiles));
58
+ assert.ok(tooling, "no tooling block emitted");
59
+ for (const name of Object.keys(allRules)) {
60
+ assert.equal(tooling.rules[`qc/${name}`], "off", `qc/${name} is not relaxed for tooling`);
61
+ }
62
+ });
63
+
64
+ test("ignores come from the config", () => {
65
+ const blocks = preset({ config: config({ ignores: ["**/generated/**"] }) });
66
+ assert.deepEqual(blocks[0].ignores, ["**/generated/**"]);
67
+ });
68
+
69
+ test("the layer block is emitted only when a boundaries plugin is supplied", () => {
70
+ const withoutPlugin = preset({ config: config() });
71
+ assert.ok(!withoutPlugin.some((b) => b.rules?.["boundaries/element-types"]));
72
+ const withPlugin = preset({ config: config(), plugins: { boundaries: {} } });
73
+ assert.ok(withPlugin.some((b) => b.rules?.["boundaries/element-types"]));
74
+ });
75
+
76
+ test("a repository with no layers still gets the browser rules", () => {
77
+ const blocks = preset({ config: config({ clientFiles: ["app/**/*.tsx"] }) });
78
+ const client = blocks.find((b) => JSON.stringify(b.files) === JSON.stringify(["app/**/*.tsx"]));
79
+ assert.ok(client, "no client block emitted");
80
+ assert.ok(client.rules["qc/no-raw-fetch"]);
81
+ });
82
+
83
+ test("the frontendLayers block is emitted when configured and boundaries plugin is supplied", () => {
84
+ const feConfig = config({
85
+ frontendLayers: {
86
+ include: ["frontend/src/**/*.{ts,tsx}"],
87
+ elements: [{ type: "ui", pattern: "frontend/src/ui/**" }],
88
+ allow: { ui: [] },
89
+ },
90
+ });
91
+ const withoutPlugin = preset({ config: feConfig });
92
+ assert.equal(withoutPlugin.filter((b) => b.rules?.["boundaries/element-types"]).length, 0);
93
+ const withPlugin = preset({ config: feConfig, plugins: { boundaries: {} } });
94
+ assert.ok(withPlugin.some((b) => b.rules?.["boundaries/element-types"]));
95
+ });
96
+
@@ -0,0 +1,120 @@
1
+ // An idempotency key is what makes a retry a resume. The client mints one per user
2
+ // operation and persists it, so a reload cannot lose it — docs/guards.md.
3
+ //
4
+ // Minting is therefore not the fault, and a rule that banned it would fire on every
5
+ // correct queue. What is checkable is a key minted *inline in a call argument*: a value
6
+ // built there is consumed by that call and cannot be re-sent, so the retry carries a
7
+ // different key and writes again. Bind it to a name, persist it, then send it.
8
+
9
+ import { optionsOf, schemaOf } from "../options.mjs";
10
+
11
+ const DEFAULT_KEYS = ["mutationId", "clientMutationId", "idempotencyKey"];
12
+ // A fresh value every call. Durable means: derived from the row, the request, or a
13
+ // value the client persisted before the first attempt.
14
+ const DEFAULT_VOLATILE = ["Date.now", "Math.random", "crypto.randomUUID", "uuid", "uuidv4", "nanoid", "randomUUID"];
15
+ // The key names the store a repeat would be recognised in, and the constructors that
16
+ // make one that outlives nothing.
17
+ const DEFAULT_LEDGER_KEY = "ledger";
18
+ const DEFAULT_THROWAWAY = ["InMemoryPipelineLedger"];
19
+
20
+ /** `crypto.randomUUID()` and `randomUUID()` are the same source, written two ways. */
21
+ function calleeName(node) {
22
+ if (node.type === "Identifier") return node.name;
23
+ if (node.type === "MemberExpression" && node.property.type === "Identifier") {
24
+ const object = node.object.type === "Identifier" ? `${node.object.name}.` : "";
25
+ return `${object}${node.property.name}`;
26
+ }
27
+ return null;
28
+ }
29
+
30
+ export default {
31
+ meta: {
32
+ type: "problem",
33
+ docs: { description: "an idempotency key comes from a durable id, never the clock or fresh randomness" },
34
+ schema: schemaOf({
35
+ keys: { type: "array", items: { type: "string" } },
36
+ volatile: { type: "array", items: { type: "string" } },
37
+ ledgerKey: { type: "string" },
38
+ throwawayLedgers: { type: "array", items: { type: "string" } },
39
+ }),
40
+ messages: {
41
+ volatile:
42
+ "'{{key}}' is minted from {{source}} inside a call argument, so a retry cannot reuse it and writes again. Bind it to a name and persist it before sending.",
43
+ },
44
+ },
45
+ create(context) {
46
+ const options = optionsOf(context);
47
+ const keys = new Set(options.keys ?? DEFAULT_KEYS);
48
+ const volatile = new Set(options.volatile ?? DEFAULT_VOLATILE);
49
+ const ledgerKey = options.ledgerKey ?? DEFAULT_LEDGER_KEY;
50
+ const throwaway = new Set(options.throwawayLedgers ?? DEFAULT_THROWAWAY);
51
+
52
+ /** The value assigned to a key, unwrapped through the shapes a default takes. */
53
+ function sourceOf(node) {
54
+ if (node === null || node === undefined) return null;
55
+ if (node.type === "CallExpression" || node.type === "NewExpression") {
56
+ const name = calleeName(node.callee);
57
+ if (name === "Date") return "the clock";
58
+ if (name !== null && volatile.has(name)) return name;
59
+ // A volatile value formatted on the way out is still volatile:
60
+ // `new Date().toISOString()` reads as a call to toISOString.
61
+ if (node.callee.type === "MemberExpression") return sourceOf(node.callee.object);
62
+ return null;
63
+ }
64
+ // `a ?? b`, `a || b`, `cond ? a : b` — a volatile fallback is still volatile.
65
+ if (node.type === "LogicalExpression") return sourceOf(node.left) ?? sourceOf(node.right);
66
+ if (node.type === "ConditionalExpression") return sourceOf(node.consequent) ?? sourceOf(node.alternate);
67
+ return null;
68
+ }
69
+
70
+ /** True when this property is inside an object literal passed straight to a call. */
71
+ function isCallArgument(node) {
72
+ let child = node;
73
+ let parent = node.parent;
74
+ while (parent) {
75
+ if (parent.type === "CallExpression" || parent.type === "NewExpression") {
76
+ return parent.arguments.includes(child);
77
+ }
78
+ // A bound name, a return, or a stored property can all be persisted.
79
+ if (
80
+ parent.type === "VariableDeclarator" ||
81
+ parent.type === "AssignmentExpression" ||
82
+ parent.type === "ReturnStatement" ||
83
+ parent.type === "ArrowFunctionExpression" ||
84
+ parent.type === "FunctionDeclaration" ||
85
+ parent.type === "FunctionExpression"
86
+ ) {
87
+ return false;
88
+ }
89
+ child = parent;
90
+ parent = parent.parent;
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /** A sibling naming a store that outlives nothing means nothing can be deduped. */
96
+ function dedupeIsThrownAway(property) {
97
+ const object = property.parent;
98
+ if (!object || object.type !== "ObjectExpression") return false;
99
+ return object.properties.some((sibling) => {
100
+ if (sibling.type !== "Property") return false;
101
+ if (sibling.key.type !== "Identifier" || sibling.key.name !== ledgerKey) return false;
102
+ const built = sibling.value;
103
+ if (built.type !== "NewExpression" && built.type !== "CallExpression") return false;
104
+ const name = calleeName(built.callee);
105
+ return name !== null && throwaway.has(name);
106
+ });
107
+ }
108
+
109
+ return {
110
+ Property(node) {
111
+ if (node.key.type !== "Identifier" || !keys.has(node.key.name)) return;
112
+ const source = sourceOf(node.value);
113
+ if (source === null) return;
114
+ if (!isCallArgument(node)) return;
115
+ if (dedupeIsThrownAway(node)) return;
116
+ context.report({ node, messageId: "volatile", data: { key: node.key.name, source } });
117
+ },
118
+ };
119
+ },
120
+ };
@@ -0,0 +1,52 @@
1
+ // A third-party service is a concrete choice; only the adapter that implements the port, or
2
+ // the composition root that selects a provider, may import its SDK. The decision to scope a
3
+ // provider behind a port belongs to the repository that adopts this rule — cite its own ADR.
4
+ //
5
+ // Business logic that calls a cloud store, a payment gateway, or a message provider directly
6
+ // has no seam left for a second provider, and no seam for a test double either — the two
7
+ // reasons the port exists in the first place. The list below is a starting point, not a
8
+ // ceiling: a repository replaces `externalServices` with its own vendor list.
9
+
10
+ import { filenameOf, moduleGroup, optionsOf, schemaOf, scopeGroup } from "../options.mjs";
11
+ import { isExemptFile } from "./module-boundary.mjs";
12
+
13
+ const DEFAULT_SCOPES = ["@aws-sdk", "@azure", "@google-cloud", "@sendgrid", "@elastic", "@algolia", "@stripe", "@twilio"];
14
+ const DEFAULT_MODULES = ["aws-sdk", "stripe", "braintree", "twilio", "nodemailer", "algoliasearch", "amqplib", "kafkajs"];
15
+ const DEFAULT_ALLOWED_FILES = ["main.ts", "entry.ts"];
16
+ // Each entry names a category subfolder, not a bare "adapters/": a feature-local folder that
17
+ // happens to be named adapters/ must not become exempt by accident.
18
+ const DEFAULT_ALLOWED_PATHS = ["adapters/cloud/", "adapters/payments/", "adapters/messaging/", "adapters/search/"];
19
+
20
+ export default {
21
+ meta: {
22
+ type: "problem",
23
+ docs: { description: "an external service's SDK belongs behind an adapter, or the composition root that selects a provider" },
24
+ schema: schemaOf({
25
+ scopes: { type: "array", items: { type: "string" } },
26
+ modules: { type: "array", items: { type: "string" } },
27
+ allowedFiles: { type: "array", items: { type: "string" } },
28
+ allowedPaths: { type: "array", items: { type: "string" } },
29
+ }),
30
+ messages: {
31
+ misplaced: "'{{source}}' belongs behind an adapter, or the composition root that selects a provider.",
32
+ },
33
+ },
34
+ create(context) {
35
+ const options = optionsOf(context);
36
+ const scopes = scopeGroup(options.scopes ?? DEFAULT_SCOPES);
37
+ const modules = moduleGroup(options.modules ?? DEFAULT_MODULES);
38
+ const allowedFiles = options.allowedFiles ?? DEFAULT_ALLOWED_FILES;
39
+ const allowedPaths = options.allowedPaths ?? DEFAULT_ALLOWED_PATHS;
40
+ const exempt = isExemptFile(filenameOf(context), { allowedBasenames: allowedFiles, allowedPathPrefixes: allowedPaths });
41
+
42
+ return {
43
+ ImportDeclaration(node) {
44
+ if (exempt) return;
45
+ const source = node.source.value;
46
+ if (typeof source === "string" && (scopes.test(source) || modules.test(source))) {
47
+ context.report({ node, messageId: "misplaced", data: { source } });
48
+ }
49
+ },
50
+ };
51
+ },
52
+ };
@@ -0,0 +1,12 @@
1
+ // Shared by every rule that restricts a module to specific files or paths — one mechanism,
2
+ // each rule its own semantic boundary (storage, an external service's SDK, ...).
3
+
4
+ import { pathPrefix } from "../options.mjs";
5
+
6
+ /** @param filename forward-slash — pass `filenameOf(context)`, never `context.filename` directly.
7
+ * @returns true when this file is allowed to import the restricted module regardless. */
8
+ export function isExemptFile(filename, { allowedBasenames = [], allowedPathPrefixes = [] } = {}) {
9
+ const base = filename.split("/").pop() ?? "";
10
+ if (allowedBasenames.includes(base)) return true;
11
+ return allowedPathPrefixes.some((prefix) => pathPrefix(prefix).test(filename));
12
+ }
@@ -0,0 +1,111 @@
1
+ // A named pattern is a pointer, not a lesson. Naming it costs an agent a few tokens and a human a
2
+ // web search; re-teaching it costs every reader of this file, every time it is loaded.
3
+
4
+ import { optionsOf, schemaOf } from "../options.mjs";
5
+
6
+ const DEFAULT_MAX_WORDS = 20;
7
+
8
+ // Canonical names a reader can look up. A repository adds its own through `patterns`.
9
+ const DEFAULT_PATTERNS = [
10
+ "outbox",
11
+ "saga",
12
+ "circuit breaker",
13
+ "bulkhead",
14
+ "backpressure",
15
+ "keyset pagination",
16
+ "cursor pagination",
17
+ "cqrs",
18
+ "event sourcing",
19
+ "unit of work",
20
+ "repository pattern",
21
+ "anti-corruption layer",
22
+ "hexagonal",
23
+ "adapter pattern",
24
+ "strategy pattern",
25
+ "observer pattern",
26
+ "builder pattern",
27
+ "factory pattern",
28
+ "singleton",
29
+ "memoization",
30
+ "debounce",
31
+ "throttle",
32
+ "exponential backoff",
33
+ "token bucket",
34
+ "leaky bucket",
35
+ "idempotency key",
36
+ "optimistic locking",
37
+ "pessimistic locking",
38
+ "last-write-wins",
39
+ "crdt",
40
+ "two-phase commit",
41
+ "write-ahead log",
42
+ "copy-on-write",
43
+ "dependency injection",
44
+ "inversion of control",
45
+ "fan-out",
46
+ "dead-letter queue",
47
+ "content-addressed",
48
+ "bloom filter",
49
+ "trie",
50
+ "lru",
51
+ ];
52
+
53
+ function proseOf(comment) {
54
+ return comment.value
55
+ .split("\n")
56
+ .map((line) => line.replace(/^\s*\*+\s?/, "").trim())
57
+ .filter((line) => line !== "" && !line.startsWith("@"))
58
+ .join(" ");
59
+ }
60
+
61
+ // Mentioning a pattern while saying what a file does is not teaching it. The finding needs a
62
+ // definitional turn after the name -- the shape an explanation takes and a description does not.
63
+ const EXPLAINS = /\b(?:is|are|works? by|means|refers to|consists of|guarantees?|ensures?|in other words|that is|lets you|allows)\b/i;
64
+
65
+ export function namedPattern(prose, patterns) {
66
+ const haystack = prose.toLowerCase();
67
+ for (const name of patterns) {
68
+ const at = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`).exec(haystack);
69
+ if (at && EXPLAINS.test(haystack.slice(at.index + name.length))) return name;
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ export function wordsOf(prose) {
75
+ return prose.split(/\s+/).filter(Boolean).length;
76
+ }
77
+
78
+ export default {
79
+ meta: {
80
+ type: "suggestion",
81
+ docs: { description: "a comment names a standard pattern and stops, it never re-teaches one" },
82
+ schema: schemaOf({
83
+ maxWords: { type: "integer", minimum: 3 },
84
+ patterns: { type: "array", items: { type: "string" } },
85
+ extra: { type: "array", items: { type: "string" } },
86
+ }),
87
+ messages: {
88
+ explained:
89
+ "Comment explains the {{pattern}} pattern in {{words}} words. Name it and stop — " +
90
+ "a reader looks it up, and every agent that loads this file pays for the lesson.",
91
+ },
92
+ },
93
+ create(context) {
94
+ const options = optionsOf(context);
95
+ const maxWords = options.maxWords ?? DEFAULT_MAX_WORDS;
96
+ // `patterns` replaces the vocabulary; `extra` adds a repository's own names to it.
97
+ const patterns = [...(options.patterns ?? DEFAULT_PATTERNS), ...(options.extra ?? [])];
98
+
99
+ return {
100
+ Program() {
101
+ for (const comment of context.sourceCode.getAllComments()) {
102
+ const prose = proseOf(comment);
103
+ const words = wordsOf(prose);
104
+ if (words <= maxWords) continue;
105
+ const pattern = namedPattern(prose, patterns);
106
+ if (pattern) context.report({ node: comment, messageId: "explained", data: { pattern, words } });
107
+ }
108
+ },
109
+ };
110
+ },
111
+ };
@@ -0,0 +1,101 @@
1
+ // A comment is one line of why. Reasoning that needs a paragraph is a decision, not a comment.
2
+
3
+ import { optionsOf, schemaOf } from "../options.mjs";
4
+
5
+ const DEFAULT_MAX_LINES = 2;
6
+
7
+ // A rule of repeated punctuation used as a divider.
8
+ const BANNER = /^\s*[*/]*\s*(?:[-=*_~#]{4,})\s*[*/]*\s*$/;
9
+
10
+ // Code is a statement shape that also ends like one; prose merely starting "import" is not.
11
+ const CODE_SHAPE = [
12
+ /^(?:const|let|var|function|class|import|export|return|await)\s+\S+/,
13
+ /^(?:if|for|while|switch)\s*\(/,
14
+ /^[\w.$[\]]+\([^)]*\)\s*$/,
15
+ ];
16
+ const STATEMENT_END = /[;{})]$/;
17
+ const BRACE_ONLY = /^\}\s*(?:else\b.*)?[;{)]?$/;
18
+
19
+ function looksLikeCode(line) {
20
+ if (BRACE_ONLY.test(line)) return true;
21
+ return CODE_SHAPE.some((shape) => shape.test(line)) && STATEMENT_END.test(line);
22
+ }
23
+
24
+ // A `@param` line is a type annotation, not a sentence, and capping it would delete the types.
25
+ function proseLinesOf(comment) {
26
+ return comment.value
27
+ .split("\n")
28
+ .map((line) => line.replace(/^\s*\*+\s?/, "").trim())
29
+ .filter((line) => line !== "" && !line.startsWith("@"));
30
+ }
31
+
32
+ function ownLine(comment, lines) {
33
+ return lines[comment.loc.start.line - 1].slice(0, comment.loc.start.column).trim() === "";
34
+ }
35
+
36
+ /**
37
+ * Consecutive own-line comments are one thought, so they are measured as one block. A comment
38
+ * trailing a statement belongs to that statement: two in a row are two notes, not a paragraph.
39
+ */
40
+ function runsOf(comments, lines) {
41
+ const runs = [];
42
+ let current = null;
43
+ for (const comment of comments) {
44
+ if (comment.type === "Block" || !ownLine(comment, lines)) {
45
+ runs.push([comment]);
46
+ current = null;
47
+ continue;
48
+ }
49
+ const previous = current?.[current.length - 1];
50
+ if (previous && comment.loc.start.line === previous.loc.end.line + 1) {
51
+ current.push(comment);
52
+ continue;
53
+ }
54
+ current = [comment];
55
+ runs.push(current);
56
+ }
57
+ return runs;
58
+ }
59
+
60
+ export default {
61
+ meta: {
62
+ type: "suggestion",
63
+ docs: { description: "a comment is one line of why, never a paragraph, a banner or code" },
64
+ schema: schemaOf({
65
+ maxLines: { type: "integer", minimum: 1 },
66
+ doc: { type: "string" },
67
+ decisions: { type: "string" },
68
+ }),
69
+ messages: {
70
+ paragraph: "Comment paragraph. One line of why, or make it a decision and cite that — {{decisions}}.",
71
+ banner: "Banner comment. {{doc}}.",
72
+ code: "Commented-out code. {{doc}}.",
73
+ },
74
+ },
75
+ create(context) {
76
+ const options = optionsOf(context);
77
+ const maxLines = options.maxLines ?? DEFAULT_MAX_LINES;
78
+ const doc = options.doc ?? "docs/enforcement.md";
79
+ const decisions = options.decisions ?? "docs/decisions.md";
80
+
81
+ return {
82
+ Program() {
83
+ for (const run of runsOf(context.sourceCode.getAllComments(), context.sourceCode.lines)) {
84
+ const prose = run.flatMap(proseLinesOf);
85
+ const node = run[0];
86
+ if (prose.some((line) => BANNER.test(line))) {
87
+ context.report({ node, messageId: "banner", data: { doc } });
88
+ continue;
89
+ }
90
+ if (prose.some(looksLikeCode)) {
91
+ context.report({ node, messageId: "code", data: { doc } });
92
+ continue;
93
+ }
94
+ if (prose.length > maxLines) {
95
+ context.report({ node, messageId: "paragraph", data: { decisions } });
96
+ }
97
+ }
98
+ },
99
+ };
100
+ },
101
+ };
@@ -0,0 +1,57 @@
1
+ // Only the public file may be imported across features. docs/architecture.md.
2
+
3
+ import path from "node:path";
4
+ import { escape, filenameOf, optionsOf, schemaOf } from "../options.mjs";
5
+
6
+ const DEFAULT_FEATURE_DIR = "features";
7
+ const DEFAULT_PUBLIC_FILE = "index";
8
+
9
+ function parser(featureDir) {
10
+ const pattern = new RegExp(`(?:^|/)${escape(featureDir)}/([^/]+)(?:/(.+))?$`);
11
+ return (candidate) => {
12
+ const match = pattern.exec(candidate.replace(/\.[cm]?[jt]sx?$/, ""));
13
+ return match ? { feature: match[1], rest: match[2] ?? "" } : null;
14
+ };
15
+ }
16
+
17
+ /** A relative specifier only names a feature once resolved against the importer. */
18
+ function resolve(filename, source) {
19
+ if (source.startsWith(".")) {
20
+ return path.posix.normalize(path.posix.join(path.posix.dirname(filename), source));
21
+ }
22
+ return source;
23
+ }
24
+
25
+ export default {
26
+ meta: {
27
+ type: "problem",
28
+ docs: { description: "a feature exposes only its public file to other features" },
29
+ schema: schemaOf({ featureDir: { type: "string" }, publicFile: { type: "string" } }),
30
+ messages: {
31
+ internal:
32
+ "Importing '{{target}}' reaches inside feature '{{feature}}'. Import its {{publicFile}}, or ask for a kernel fragment.",
33
+ },
34
+ },
35
+ create(context) {
36
+ const options = optionsOf(context);
37
+ const publicFile = options.publicFile ?? DEFAULT_PUBLIC_FILE;
38
+ const parse = parser(options.featureDir ?? DEFAULT_FEATURE_DIR);
39
+ const filename = filenameOf(context);
40
+ const here = parse(filename);
41
+ return {
42
+ ImportDeclaration(node) {
43
+ const source = node.source.value;
44
+ if (typeof source !== "string") return;
45
+ const there = parse(resolve(filename, source));
46
+ if (!there) return;
47
+ if (here && here.feature === there.feature) return;
48
+ if (there.rest === "" || there.rest === publicFile) return;
49
+ context.report({
50
+ node,
51
+ messageId: "internal",
52
+ data: { target: source, feature: there.feature, publicFile },
53
+ });
54
+ },
55
+ };
56
+ },
57
+ };
@@ -0,0 +1,89 @@
1
+ // A number in a comment is maintenance work that buys nothing. docs/enforcement.md.
2
+ // Citation identifiers are the exception — citing instead of restating is the point.
3
+
4
+ import { escape, optionsOf, schemaOf } from "../options.mjs";
5
+
6
+ // Decision ids this repository defines. A prefix, then a number.
7
+ const DEFAULT_PREFIXES = ["ADR", "QC"];
8
+ // Ids a repository cites but does not own.
9
+ const DEFAULT_EXTERNAL = ["REQ-[A-Z]{3}-\\d+", "T\\d+-\\d+", "D\\d+"];
10
+ // Standards and encodings are identifiers everywhere, not thresholds.
11
+ const STANDARDS = [
12
+ "WCAG(?: \\d(?:\\.\\d)*)?",
13
+ "ES\\d{4}",
14
+ "UTF-8",
15
+ "SHA-256",
16
+ "HTTP\\/\\d",
17
+ "RFC \\d+",
18
+ "base64",
19
+ "utf8",
20
+ "\\d+_[a-z0-9_]+",
21
+ ];
22
+
23
+ const DIGIT = /\d/;
24
+
25
+ const NUMBER_WORDS =
26
+ "zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand";
27
+ const QUANTITY_UNITS =
28
+ "times|seconds?|mins?|minutes?|hours?|days?|ms|milliseconds?|bytes?|kb|mb|gb|retries|attempts?";
29
+ const THRESHOLD_PREFIXES =
30
+ "wait|sleep|delay|budget|quota|timeout|at most|up to|batch of|limit of|maximum of";
31
+
32
+ const QUANTITY_WORD = new RegExp(
33
+ `\\b(?:${NUMBER_WORDS})\\s+(?:${QUANTITY_UNITS})\\b|\\b(?:${THRESHOLD_PREFIXES})\\s+(?:${NUMBER_WORDS})\\b`,
34
+ "i",
35
+ );
36
+
37
+ function citationPattern({ prefixes, external, standards }) {
38
+ const alternatives = [
39
+ ...prefixes.map((prefix) => `${escape(prefix)}-\\d+`),
40
+ ...external,
41
+ ...standards,
42
+ ];
43
+ return new RegExp(`\\b(?:${alternatives.join("|")})\\b`);
44
+ }
45
+
46
+ export default {
47
+ meta: {
48
+ type: "problem",
49
+ docs: { description: "no numeric literal or quantity threshold in a comment; cite the registry instead" },
50
+ schema: schemaOf({
51
+ prefixes: { type: "array", items: { type: "string" } },
52
+ external: { type: "array", items: { type: "string" } },
53
+ standards: { type: "array", items: { type: "string" } },
54
+ registry: { type: "string" },
55
+ }),
56
+ messages: {
57
+ number: "Number or quantity threshold in a comment. Cite {{registry}} or the doc that owns it.",
58
+ },
59
+ },
60
+ create(context) {
61
+ const options = optionsOf(context);
62
+ const citation = citationPattern({
63
+ prefixes: options.prefixes ?? DEFAULT_PREFIXES,
64
+ external: options.external ?? DEFAULT_EXTERNAL,
65
+ standards: options.standards ?? STANDARDS,
66
+ });
67
+ const registry = options.registry ?? "the decision registry";
68
+
69
+ return {
70
+ Program() {
71
+ for (const comment of context.sourceCode.getAllComments()) {
72
+ // Strip citations, then anything left with a digit is a literal.
73
+ let stripped = comment.value;
74
+ let match;
75
+ while ((match = citation.exec(stripped)) !== null) {
76
+ stripped = stripped.replace(match[0], "");
77
+ }
78
+ // Backtick-quoted code is a reference, never a prose quantity claim.
79
+ stripped = stripped.replace(/`[^`]*`/g, "");
80
+ // A lone list marker or an identifier-embedded digit is not a threshold.
81
+ stripped = stripped.replace(/\b[a-zA-Z_$][\w$]*\d[\w$]*\b/g, "");
82
+ if (DIGIT.test(stripped) || QUANTITY_WORD.test(stripped)) {
83
+ context.report({ node: comment, messageId: "number", data: { registry } });
84
+ }
85
+ }
86
+ },
87
+ };
88
+ },
89
+ };
@@ -0,0 +1,29 @@
1
+ // Keyset only; offset is never offered. docs/architecture.md.
2
+
3
+ import { optionsOf, schemaOf } from "../options.mjs";
4
+
5
+ const DEFAULT_BANNED = ["offset", "skip"];
6
+
7
+ export default {
8
+ meta: {
9
+ type: "problem",
10
+ docs: { description: "keyset pagination only" },
11
+ schema: schemaOf({ banned: { type: "array", items: { type: "string" } } }),
12
+ messages: { offset: "'{{name}}' is offset pagination. Use a keyset cursor." },
13
+ },
14
+ create(context) {
15
+ const banned = new Set(optionsOf(context).banned ?? DEFAULT_BANNED);
16
+ return {
17
+ MemberExpression(node) {
18
+ if (node.property.type === "Identifier" && banned.has(node.property.name) && node.object.type !== "ThisExpression") {
19
+ context.report({ node, messageId: "offset", data: { name: node.property.name } });
20
+ }
21
+ },
22
+ Property(node) {
23
+ if (node.key.type === "Identifier" && banned.has(node.key.name)) {
24
+ context.report({ node, messageId: "offset", data: { name: node.key.name } });
25
+ }
26
+ },
27
+ };
28
+ },
29
+ };