@forwardimpact/libcoaligned 0.1.11 → 0.1.13

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 CHANGED
@@ -41,19 +41,56 @@ A rule module's default export is:
41
41
  ```js
42
42
  export default {
43
43
  name: "ambient-deps",
44
- // Walk the repo and return plain subjects per scope (plus optional
45
- // shared ctx the rules read).
46
- build: async ({ root, runtime }) => ({
47
- subjects: { "src-file": [{ path, smells }] },
48
- ctx: { deny },
44
+ // `build` (and `seed`) receive the injected build kit; the module never
45
+ // imports the engine (it loads into consuming repos via npx, where the
46
+ // package is not resolvable from `.coaligned/`). Return plain subjects per
47
+ // scope, plus optional shared ctx the rules read.
48
+ build: (kit) => ({
49
+ subjects: { "src-file": kit.scanAst({ dirs, match, extract }) },
50
+ ctx: { deny: kit.config("ambient-deps.deny.yml", {}) },
49
51
  }),
50
- // Declarative rules over those subjects.
51
- rules: [{ id, scope, severity, when, check, message, hint }],
52
+ // Declarative rules over those subjects: either a static array, or a
53
+ // `(ruleKit) => array` factory that builds them from the rule helpers.
54
+ rules: ({ parseError, failAll }) => [
55
+ parseError("src-file"),
56
+ { id, scope, severity, when, check, message, hint },
57
+ ],
52
58
  // Optional: text for `coaligned invariants --seed <name>` — e.g. a
53
- // regenerated grandfather deny-list.
54
- seed: async ({ root, runtime }) => "…",
59
+ // regenerated grandfather deny-list. Also receives the build kit.
60
+ seed: (kit) => "…",
55
61
  };
56
62
  ```
57
63
 
64
+ ### The build kit
65
+
66
+ The engine binds a kit per run to the repo `root`, the module's own `dir`
67
+ (for co-located config), and the `runtime` bag (fs and ripgrep route through
68
+ it, so the engine carries no ambient dependencies). The module declares only
69
+ policy; the kit owns the mechanism:
70
+
71
+ - `scan({ dirs, match, skip?, under?, read? })` — collect files as
72
+ `{ path, rel, text? }`; `under` restricts to the per-package `src`/`test`
73
+ shape.
74
+ - `scanAst({ dirs, match, extract, locations?, … })` — read + parse each file
75
+ and merge `extract(ast)`; a parse failure becomes `{ path, rel, parseError }`.
76
+ - `parse(src, path, opts?)`, `walk(ast, visit)` — the lower-level AST seam.
77
+ - `grep({ pattern | patterns, paths?, globs?, caseSensitive?, onlyMatching?,
78
+ dedupe? })` — ripgrep matches as `{ path, lineNo, text, reason? }`, with
79
+ per-entry `exclude` and built-in de-duplication.
80
+ - `restatementDrift({ entries, equal })` — the shared "single source restated
81
+ across consumers" scan + compare (service URLs, scalar values).
82
+ - `readText`, `readJson`, `config(name, fallback?)` (co-located JSON/YAML),
83
+ `listDir(path, { dirsOnly? })`.
84
+ - `lineAt(text, offset)`, `glob(pattern)`.
85
+
86
+ ### The rule kit
87
+
88
+ When `rules` is a function it receives the rule helpers:
89
+
90
+ - `parseError(scope, { id?, hint? })` — fails any subject carrying a
91
+ `parseError` (paired with `scanAst`).
92
+ - `failAll(scope, { id, message, hint?, when? })` — fails every subject in
93
+ scope (the build step already decided each is a violation).
94
+
58
95
  Findings render in the same ESLint-style format as the other subcommands
59
96
  (`--json` for machine output); any finding fails the run.
package/bin/coaligned.js CHANGED
@@ -2,12 +2,15 @@
2
2
 
3
3
  import "@forwardimpact/libpreflight/node22";
4
4
 
5
+ import { resolve } from "node:path";
6
+
5
7
  import { createDefaultRuntime } from "@forwardimpact/libutil/runtime";
6
8
  import { createCli } from "@forwardimpact/libcli";
7
9
  import { emitFindingsJson, emitFindingsText } from "@forwardimpact/libutil";
8
10
  import {
9
11
  checkInstructions,
10
12
  checkJtbd,
13
+ createBuildKit,
11
14
  findInvariantsRoot,
12
15
  INVARIANTS_DIR,
13
16
  loadRuleModules,
@@ -134,7 +137,10 @@ async function invariantsHandler(ctx) {
134
137
  cli.error(`rule module "${mod.name}" has no seed output`);
135
138
  return 1;
136
139
  }
137
- rt.proc.stdout.write(await mod.seed({ root, runtime: rt }));
140
+ const dir = resolve(root, INVARIANTS_DIR);
141
+ rt.proc.stdout.write(
142
+ await mod.seed(createBuildKit({ root, dir, runtime: rt })),
143
+ );
138
144
  return 0;
139
145
  }
140
146
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@forwardimpact/libcoaligned",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "Co-Aligned architecture checks — enforce instruction-layer length caps, JTBD invariants, and the repo's own declarative invariant rule modules.",
5
5
  "keywords": [
6
6
  "coaligned",
@@ -49,7 +49,9 @@
49
49
  "@forwardimpact/libcli": "^0.1.9",
50
50
  "@forwardimpact/libpreflight": "^0.1.0",
51
51
  "@forwardimpact/libutil": "*",
52
- "prettier": "^3.8.4"
52
+ "acorn": "^8.17.0",
53
+ "prettier": "^3.8.4",
54
+ "yaml": "^2.9.0"
53
55
  },
54
56
  "devDependencies": {
55
57
  "@forwardimpact/libmock": "^0.1.0"
package/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { checkInstructions } from "./instructions.js";
2
+ export { createBuildKit, RULE_KIT } from "./invariant-kit.js";
2
3
  export {
3
4
  checkInvariants,
4
5
  findInvariantsRoot,
@@ -177,14 +177,47 @@ async function buildLayers(root, fs) {
177
177
  name: "agent reference",
178
178
  maxLines: 192,
179
179
  maxWords: 1280,
180
- files: await findAgentReferences(root, claudeDirs, fs),
180
+ files: (await findAgentReferences(root, claudeDirs, fs)).filter(
181
+ (p) => !p.endsWith("/agents/references/memory-protocol.md"),
182
+ ),
183
+ },
184
+ {
185
+ id: "L4",
186
+ name: "memory-protocol agent reference",
187
+ // Larger than the L4 default to absorb the boot-digest routing
188
+ // contract this one reference is the sole home for: the materialized
189
+ // agent-experiments surface (provenance fields + last-successful-sync
190
+ // freshness bound) and the verbatim standing-carries digest field.
191
+ // Sized to the current content, not open-ended.
192
+ maxLines: 212,
193
+ maxWords: 1472,
194
+ files: (await findAgentReferences(root, claudeDirs, fs)).filter((p) =>
195
+ p.endsWith("/agents/references/memory-protocol.md"),
196
+ ),
181
197
  },
182
198
  {
183
199
  id: "L5",
184
200
  name: "skill procedure",
185
201
  maxLines: 192,
186
202
  maxWords: 1280,
187
- files: skillDirs.map((d) => `${d}/SKILL.md`),
203
+ files: skillDirs
204
+ .map((d) => `${d}/SKILL.md`)
205
+ .filter((p) => !p.endsWith("/kata-release-merge/SKILL.md")),
206
+ },
207
+ {
208
+ id: "L5",
209
+ name: "kata-release-merge skill procedure",
210
+ // Larger than the L5 default to absorb four consolidated merge-gate
211
+ // rule sets that govern adjacent corners of one gate: phase-PR review
212
+ // transfer (pin-based head coverage), post-panel coverage (folded into
213
+ // the pin mechanism rather than duplicated), the spec-less
214
+ // experiment-PR approval path, and the block-comment re-ping cadence.
215
+ // Sized to the consolidated content, not open-ended.
216
+ maxLines: 320,
217
+ maxWords: 2304,
218
+ files: skillDirs
219
+ .map((d) => `${d}/SKILL.md`)
220
+ .filter((p) => p.endsWith("/kata-release-merge/SKILL.md")),
188
221
  },
189
222
  {
190
223
  id: "L6",
@@ -0,0 +1,468 @@
1
+ // The invariant authoring kit: the mechanism an invariant rule module needs to
2
+ // turn the repository into subjects and findings, so the module itself carries
3
+ // only policy. The engine injects a *build kit* into every module's `build`
4
+ // (and `seed`), and a *rule kit* into a module's `rules` when it is written as
5
+ // a function. Modules never import this file — the host (invariants.js) binds a
6
+ // kit per run and passes it in, the same way the rest of the monorepo threads
7
+ // the `runtime` bag instead of importing ambient collaborators.
8
+ //
9
+ // Filesystem and subprocess access route through the injected `runtime`
10
+ // (`runtime.fsSync`, `runtime.subprocess`) so this module — which lives under
11
+ // libraries/<pkg>/src — stays clean under the repo's own ambient-deps invariant.
12
+
13
+ import { isAbsolute, join, relative, resolve } from "node:path";
14
+
15
+ import { parse as acornParse } from "acorn";
16
+ import { parse as parseYaml } from "yaml";
17
+
18
+ // -- AST -----------------------------------------------------------------
19
+
20
+ /**
21
+ * Parse an ES module, wrapping acorn's error with the offending path.
22
+ *
23
+ * @param {string} source - Module source text.
24
+ * @param {string} filePath - Path used in parse-error messages.
25
+ * @param {{ locations?: boolean }} [options]
26
+ * @returns {object} The acorn AST.
27
+ */
28
+ export function parse(source, filePath, { locations = false } = {}) {
29
+ try {
30
+ return acornParse(source, {
31
+ ecmaVersion: "latest",
32
+ sourceType: "module",
33
+ locations,
34
+ allowAwaitOutsideFunction: true,
35
+ });
36
+ } catch (err) {
37
+ throw new Error(`failed to parse ${filePath}: ${err.message}`);
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Depth-first visit of every typed node in an acorn AST.
43
+ *
44
+ * @param {object|object[]} node - AST node (or array of nodes).
45
+ * @param {(node: object) => void} visit - Called once per typed node.
46
+ */
47
+ export function walk(node, visit) {
48
+ if (!node || typeof node !== "object") return;
49
+ if (Array.isArray(node)) {
50
+ for (const child of node) walk(child, visit);
51
+ return;
52
+ }
53
+ if (typeof node.type !== "string") return;
54
+ visit(node);
55
+ for (const key of Object.keys(node)) {
56
+ if (key === "loc" || key === "start" || key === "end") continue;
57
+ walk(node[key], visit);
58
+ }
59
+ }
60
+
61
+ // -- Small pure utilities ------------------------------------------------
62
+
63
+ /**
64
+ * The 1-based line number a character offset falls on.
65
+ *
66
+ * @param {string} text - The source text.
67
+ * @param {number} offset - A character offset into `text`.
68
+ * @returns {number} The 1-based line number.
69
+ */
70
+ export function lineAt(text, offset) {
71
+ let line = 1;
72
+ for (let i = 0; i < offset && i < text.length; i++) {
73
+ if (text.charCodeAt(i) === 10) line++;
74
+ }
75
+ return line;
76
+ }
77
+
78
+ /**
79
+ * Compile a minimal path glob to a `RegExp`. `**` matches any path segments;
80
+ * `*` matches a non-slash run.
81
+ *
82
+ * @param {string} pattern - The glob.
83
+ * @returns {RegExp} An anchored regular expression.
84
+ */
85
+ export function glob(pattern) {
86
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&");
87
+ return new RegExp(
88
+ `^${escaped
89
+ .replace(/\*\*/g, "DOUBLESTAR")
90
+ .replace(/\*/g, "[^/]*")
91
+ .replace(/DOUBLESTAR/g, ".*")}$`,
92
+ );
93
+ }
94
+
95
+ // -- Filesystem walking (over runtime.fsSync) ----------------------------
96
+
97
+ function collectFiles(fsSync, dir, skip, match) {
98
+ const out = [];
99
+ if (!fsSync.existsSync(dir)) return out;
100
+ for (const entry of fsSync.readdirSync(dir)) {
101
+ if (skip.has(entry)) continue;
102
+ const full = join(dir, entry);
103
+ if (fsSync.statSync(full).isDirectory()) {
104
+ out.push(...collectFiles(fsSync, full, skip, match));
105
+ } else if (match(entry)) {
106
+ out.push(full);
107
+ }
108
+ }
109
+ return out;
110
+ }
111
+
112
+ function readTextOrNull(fsSync, abs) {
113
+ try {
114
+ return fsSync.readFileSync(abs, "utf8");
115
+ } catch {
116
+ return null;
117
+ }
118
+ }
119
+
120
+ // -- ripgrep (over runtime.subprocess.runSync) ---------------------------
121
+
122
+ function normalizePatterns(pattern, patterns) {
123
+ const list = patterns ?? (pattern === undefined ? [] : [pattern]);
124
+ return list.map((p) => (typeof p === "string" ? { pattern: p } : p));
125
+ }
126
+
127
+ function parseRgLine(raw) {
128
+ const i = raw.indexOf(":");
129
+ const j = raw.indexOf(":", i + 1);
130
+ return {
131
+ rel: raw.slice(0, i),
132
+ lineNo: Number.parseInt(raw.slice(i + 1, j), 10),
133
+ text: raw.slice(j + 1),
134
+ raw,
135
+ };
136
+ }
137
+
138
+ // Keep the first row per key. `dedupe` is `false`, `true` (key on the raw
139
+ // line), or a key function over the row.
140
+ function dedupeRows(rows, dedupe) {
141
+ if (!dedupe) return rows;
142
+ const keyOf = typeof dedupe === "function" ? dedupe : (m) => m.raw;
143
+ const seen = new Set();
144
+ return rows.filter((r) => {
145
+ const k = keyOf(r);
146
+ if (seen.has(k)) return false;
147
+ seen.add(k);
148
+ return true;
149
+ });
150
+ }
151
+
152
+ // A grep row carries `rel`/`raw` for dedupe; the subject keeps only the
153
+ // reportable fields (plus `reason` when the matching entry supplied one).
154
+ function toGrepSubject({ path, lineNo, text, reason }) {
155
+ const subject = { path, lineNo, text };
156
+ if (reason !== undefined) subject.reason = reason;
157
+ return subject;
158
+ }
159
+
160
+ // -- The build kit -------------------------------------------------------
161
+
162
+ /**
163
+ * Build the kit injected into a rule module's `build` and `seed`. Every
164
+ * collaborator is bound to `root` (the repository root), `dir` (the module's
165
+ * own directory, for co-located config), and `runtime` (the ambient bag).
166
+ *
167
+ * @param {{ root: string, dir: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
168
+ * @returns {object} The build kit.
169
+ */
170
+ export function createBuildKit({ root, dir, runtime }) {
171
+ const { fsSync, subprocess } = runtime;
172
+ const abs = (p) => (isAbsolute(p) ? p : resolve(root, p));
173
+
174
+ /**
175
+ * Collect files under one or more directories as subjects.
176
+ *
177
+ * @param {object} options
178
+ * @param {string[]} options.dirs - Root directories, relative to the repo.
179
+ * @param {(name: string) => boolean} options.match - File-name predicate.
180
+ * @param {Iterable<string>} [options.skip] - Directory names to prune.
181
+ * @param {string} [options.under] - Restrict to `<dir>/<child>/<under>/**`,
182
+ * the per-package `src`/`test` shape.
183
+ * @param {boolean} [options.read] - Attach file `text` (default true).
184
+ * @returns {Array<{ path: string, rel: string, text?: string }>}
185
+ */
186
+ function scan({ dirs, match, skip = [], under, read = true }) {
187
+ const skipSet = new Set(skip);
188
+ const files = [];
189
+ for (const d of dirs) {
190
+ const base = resolve(root, d);
191
+ const roots = under
192
+ ? (fsSync.existsSync(base) ? fsSync.readdirSync(base) : []).map((n) =>
193
+ join(base, n, under),
194
+ )
195
+ : [base];
196
+ for (const r of roots)
197
+ files.push(...collectFiles(fsSync, r, skipSet, match));
198
+ }
199
+ return files.map((path) => {
200
+ const subject = { path, rel: relative(root, path) };
201
+ if (read) subject.text = readTextOrNull(fsSync, path) ?? "";
202
+ return subject;
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Like `scan`, but parse each file and merge `extract(ast)` into the subject.
208
+ * A file that fails to parse becomes `{ path, rel, parseError }` instead, so
209
+ * the module pairs it with the rule kit's `parseError(scope, …)`.
210
+ *
211
+ * @param {object} options - `scan` options plus the two below.
212
+ * @param {(ast: object) => object} options.extract - Subject fields from the AST.
213
+ * @param {boolean} [options.locations] - Pass `locations` to the parser.
214
+ * @returns {Array<object>}
215
+ */
216
+ function scanAst({ extract, locations = false, ...scanOpts }) {
217
+ return scan({ ...scanOpts, read: true }).map(({ path, rel, text }) => {
218
+ try {
219
+ return { path, rel, ...extract(parse(text, rel, { locations })) };
220
+ } catch (err) {
221
+ return { path, rel, parseError: err.message };
222
+ }
223
+ });
224
+ }
225
+
226
+ function assertRg() {
227
+ if (subprocess.runSync("rg", ["--version"]).exitCode !== 0) {
228
+ throw new Error("ripgrep (rg) is required by the invariant rule modules");
229
+ }
230
+ }
231
+
232
+ function rgOnce({ pattern, paths, globs, caseSensitive, onlyMatching }) {
233
+ const args = [
234
+ "--hidden",
235
+ "--no-messages",
236
+ "--line-number",
237
+ "--color",
238
+ "never",
239
+ ];
240
+ if (!caseSensitive) args.push("-i");
241
+ if (onlyMatching) args.push("--only-matching");
242
+ for (const g of globs) args.push("--glob", g);
243
+ args.push("-e", pattern, ...paths);
244
+ const { stdout, exitCode } = subprocess.runSync("rg", args, { cwd: root });
245
+ if (exitCode === 2)
246
+ throw new Error(`ripgrep failed for pattern: ${pattern}`);
247
+ return (stdout || "").split("\n").filter(Boolean).map(parseRgLine);
248
+ }
249
+
250
+ /**
251
+ * Scan the repo with ripgrep and return matches as subjects. Accepts one
252
+ * `pattern` or a list of `patterns` (strings, or `{ pattern, reason?, globs?,
253
+ * caseSensitive?, onlyMatching?, exclude? }`); per-entry options override the
254
+ * call defaults, and a per-entry `exclude` RegExp drops matches whose raw
255
+ * line it tests true (a false-positive filter). `dedupe` is `false`, `true`
256
+ * (key on the raw line), or a key function over `{ path, rel, lineNo, text,
257
+ * raw, reason }`.
258
+ *
259
+ * Each subject is `{ path, lineNo, text }`, plus `reason` when the matching
260
+ * entry carries one. The repo-relative `rel` and full `raw` line are
261
+ * available to the `dedupe` key function but are not part of the subject.
262
+ *
263
+ * @param {object} options
264
+ * @returns {Array<{ path: string, lineNo: number, text: string, reason?: string }>}
265
+ */
266
+ function grep({
267
+ pattern,
268
+ patterns,
269
+ paths = ["."],
270
+ globs = [],
271
+ caseSensitive = false,
272
+ onlyMatching = false,
273
+ dedupe = false,
274
+ }) {
275
+ assertRg();
276
+ const rows = [];
277
+ for (const entry of normalizePatterns(pattern, patterns)) {
278
+ const matches = rgOnce({
279
+ pattern: entry.pattern,
280
+ paths,
281
+ globs: [...globs, ...(entry.globs ?? [])],
282
+ caseSensitive: entry.caseSensitive ?? caseSensitive,
283
+ onlyMatching: entry.onlyMatching ?? onlyMatching,
284
+ });
285
+ for (const m of matches) {
286
+ if (entry.exclude && entry.exclude.test(m.raw)) continue;
287
+ rows.push({ ...m, path: resolve(root, m.rel), reason: entry.reason });
288
+ }
289
+ }
290
+ return dedupeRows(rows, dedupe).map(toGrepSubject);
291
+ }
292
+
293
+ /**
294
+ * Read a repo file's text (path relative to the repo root, or absolute).
295
+ *
296
+ * @param {string} path
297
+ * @returns {string|null} The text, or `null` when missing.
298
+ */
299
+ function readText(path) {
300
+ return readTextOrNull(fsSync, abs(path));
301
+ }
302
+
303
+ /**
304
+ * Read and parse a repo JSON file, returning `null` when missing or invalid.
305
+ *
306
+ * @param {string} path - Relative to the repo root, or absolute.
307
+ * @returns {object|null}
308
+ */
309
+ function readJson(path) {
310
+ const text = readTextOrNull(fsSync, abs(path));
311
+ if (text == null) return null;
312
+ try {
313
+ return JSON.parse(text);
314
+ } catch {
315
+ return null;
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Read a config file co-located with the rule module (`<dir>/<name>`),
321
+ * parsed by extension (`.json` / `.yml` / `.yaml`). Returns `fallback` when
322
+ * the file is missing, empty, or unparseable.
323
+ *
324
+ * @param {string} name - File name beside the module.
325
+ * @param {*} [fallback] - Value when absent or unreadable (default `null`).
326
+ * @returns {*}
327
+ */
328
+ function config(name, fallback = null) {
329
+ const text = readTextOrNull(fsSync, join(dir, name));
330
+ if (text == null || text.trim() === "") return fallback;
331
+ try {
332
+ const parsed = name.endsWith(".json")
333
+ ? JSON.parse(text)
334
+ : parseYaml(text);
335
+ return parsed ?? fallback;
336
+ } catch {
337
+ return fallback;
338
+ }
339
+ }
340
+
341
+ /**
342
+ * The shared "single source restated across consumers" check. For every
343
+ * registry `entry` (`{ key, expected, consumers: [{ path, pattern }] }`),
344
+ * scan each consumer file line by line for `pattern` and emit one subject
345
+ * per match: the restated value (capture group 1, else the whole match,
346
+ * trimmed) paired with the entry's `expected` value and an `ok` verdict from
347
+ * `equal(restated, expected, key)`. The module supplies the domain pieces
348
+ * (how `expected` is computed, what `equal` means); the kit owns the scan.
349
+ *
350
+ * Native line-by-line matching, not ripgrep: the surfaces carry URLs and
351
+ * other colon-bearing values that ripgrep's single-file output corrupts, and
352
+ * look-around is sometimes needed.
353
+ *
354
+ * @param {object} options
355
+ * @param {Array<{ key: string, expected: *, consumers: Array<{ path: string, pattern: RegExp|string }> }>} options.entries
356
+ * @param {(restated: string, expected: *, key: string) => boolean} options.equal
357
+ * @returns {Array<{ key: string, path: string, lineNo: number, restated: string, expected: *, ok: boolean }>}
358
+ */
359
+ function restatementDrift({ entries, equal }) {
360
+ const subjects = [];
361
+ for (const { key, expected, consumers } of entries) {
362
+ for (const consumer of consumers) {
363
+ const text = readTextOrNull(fsSync, abs(consumer.path));
364
+ if (text == null) continue;
365
+ const re =
366
+ typeof consumer.pattern === "string"
367
+ ? new RegExp(consumer.pattern)
368
+ : consumer.pattern;
369
+ text.split("\n").forEach((line, i) => {
370
+ const m = line.match(re);
371
+ if (!m) return;
372
+ const restated = (m[1] ?? m[0]).trim();
373
+ subjects.push({
374
+ key,
375
+ path: consumer.path,
376
+ lineNo: i + 1,
377
+ restated,
378
+ expected,
379
+ ok: equal(restated, expected, key),
380
+ });
381
+ });
382
+ }
383
+ }
384
+ return subjects;
385
+ }
386
+
387
+ /**
388
+ * List the entries of a repo directory by name, returning `[]` when missing.
389
+ *
390
+ * @param {string} path - Relative to the repo root, or absolute.
391
+ * @param {{ dirsOnly?: boolean, filesOnly?: boolean }} [options]
392
+ * @returns {string[]}
393
+ */
394
+ function listDir(path, { dirsOnly = false, filesOnly = false } = {}) {
395
+ let entries;
396
+ try {
397
+ entries = fsSync.readdirSync(abs(path), { withFileTypes: true });
398
+ } catch {
399
+ return [];
400
+ }
401
+ return entries
402
+ .filter((e) =>
403
+ dirsOnly ? e.isDirectory() : filesOnly ? e.isFile() : true,
404
+ )
405
+ .map((e) => e.name);
406
+ }
407
+
408
+ return {
409
+ root,
410
+ dir,
411
+ runtime,
412
+ scan,
413
+ scanAst,
414
+ parse,
415
+ walk,
416
+ grep,
417
+ restatementDrift,
418
+ readText,
419
+ readJson,
420
+ config,
421
+ listDir,
422
+ lineAt,
423
+ glob,
424
+ };
425
+ }
426
+
427
+ // -- The rule kit --------------------------------------------------------
428
+
429
+ /**
430
+ * Helpers a rule module receives when it exports `rules` as a function. They
431
+ * build the two recurring rule shapes so the module declares only policy.
432
+ */
433
+ export const RULE_KIT = {
434
+ /**
435
+ * The standard parse-error rule: fails any subject carrying a `parseError`
436
+ * string (as produced by the build kit's `scanAst`).
437
+ *
438
+ * @param {string} scope - The subject scope to guard.
439
+ * @param {{ id?: string, hint?: string }} [options]
440
+ * @returns {object} A rule for the rules engine.
441
+ */
442
+ parseError(scope, { id = `${scope}.parse-error`, hint } = {}) {
443
+ return {
444
+ id,
445
+ scope,
446
+ severity: "fail",
447
+ check: (s) => (s.parseError ? { msg: s.parseError } : null),
448
+ message: (_s, r) => r.msg,
449
+ hint: hint ?? "fix the syntax error so the file can be parsed",
450
+ };
451
+ },
452
+
453
+ /**
454
+ * A rule that fails every subject in `scope` (optionally gated by `when`).
455
+ * The build step has already decided each subject is a violation; the rule
456
+ * only renders it.
457
+ *
458
+ * @param {string} scope
459
+ * @param {{ id: string, message: (s: object, r: object, c: object) => string, hint?: string, when?: (s: object, c: object) => boolean }} options
460
+ * @returns {object} A rule for the rules engine.
461
+ */
462
+ failAll(scope, { id, message, hint, when }) {
463
+ const rule = { id, scope, severity: "fail", check: () => ({}), message };
464
+ if (hint !== undefined) rule.hint = hint;
465
+ if (when !== undefined) rule.when = when;
466
+ return rule;
467
+ },
468
+ };
package/src/invariants.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { resolve } from "node:path";
2
2
  import { pathToFileURL } from "node:url";
3
3
  import { runRules } from "@forwardimpact/libutil";
4
+ import { createBuildKit, RULE_KIT } from "./invariant-kit.js";
4
5
 
5
6
  // The conventional rules location, relative to the project root.
6
7
  export const INVARIANTS_DIR = ".coaligned/invariants";
@@ -45,14 +46,20 @@ function assertModuleShape(mod, fileName) {
45
46
  mod &&
46
47
  typeof mod.name === "string" &&
47
48
  typeof mod.build === "function" &&
48
- Array.isArray(mod.rules);
49
+ (Array.isArray(mod.rules) || typeof mod.rules === "function");
49
50
  if (!ok) {
50
51
  throw new Error(
51
- `${fileName}: default export must be { name, build, rules }`,
52
+ `${fileName}: default export must be { name, build, rules } (rules is an array or a (ruleKit) => array)`,
52
53
  );
53
54
  }
54
55
  }
55
56
 
57
+ // A module's rules are either a static array or a `(ruleKit) => array` factory
58
+ // that builds them from the shared rule helpers.
59
+ function resolveRules(mod) {
60
+ return typeof mod.rules === "function" ? mod.rules(RULE_KIT) : mod.rules;
61
+ }
62
+
56
63
  /**
57
64
  * Discover and import every rule module under `rulesDir` (sorted by file
58
65
  * name for a stable run order).
@@ -89,20 +96,26 @@ export async function loadRuleModules({
89
96
  }
90
97
 
91
98
  /**
92
- * Run already-loaded rule modules: build each module's subjects, then apply
93
- * its rule catalogue through the shared rules engine.
99
+ * Run already-loaded rule modules: inject the build kit, build each module's
100
+ * subjects, then apply its rule catalogue through the shared rules engine.
94
101
  *
95
102
  * @param {object[]} modules - Rule-module default exports.
96
- * @param {{ root: string, runtime: import('@forwardimpact/libutil/runtime').Runtime }} options
103
+ * @param {{ root: string, runtime: import('@forwardimpact/libutil/runtime').Runtime, dir?: string }} options
104
+ * `dir` is the modules' directory (for co-located config); defaults to
105
+ * `<root>/.coaligned/invariants`.
97
106
  * @returns {Promise<object[]>} Structured findings; empty when conformant.
98
107
  */
99
- export async function runRuleModules(modules, { root, runtime }) {
108
+ export async function runRuleModules(
109
+ modules,
110
+ { root, runtime, dir = resolve(root, INVARIANTS_DIR) },
111
+ ) {
100
112
  const findings = [];
101
113
  for (const mod of modules) {
102
- const { subjects, ctx = {} } = await mod.build({ root, runtime });
114
+ const kit = createBuildKit({ root, dir, runtime });
115
+ const { subjects, ctx = {} } = await mod.build(kit);
103
116
  findings.push(
104
117
  ...runRules(
105
- mod.rules,
118
+ resolveRules(mod),
106
119
  { ...ctx, subjects },
107
120
  { resolveScope: (key, c) => c.subjects[key] ?? [] },
108
121
  ),
@@ -125,6 +138,7 @@ export async function checkInvariants({
125
138
  runtime,
126
139
  }) {
127
140
  if (!runtime) throw new Error("runtime is required");
141
+ const dir = resolve(root, rulesDir);
128
142
  const modules = await loadRuleModules({ root, rulesDir, runtime });
129
- return runRuleModules(modules, { root, runtime });
143
+ return runRuleModules(modules, { root, runtime, dir });
130
144
  }