@inixiative/atlas 0.0.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/src/cli.ts ADDED
@@ -0,0 +1,281 @@
1
+ import { resolve } from 'node:path';
2
+ import { analyze } from './analyze.ts';
3
+ import { runCheck } from './commands/check.ts';
4
+ import { coverage, evaluateCoverageGate, readBaseline } from './commands/coverage.ts';
5
+ import { generate } from './commands/generate.ts';
6
+ import { graph } from './commands/graph.ts';
7
+ import { flagsToRule, type QueryRule, queryFiles, toQueryRecords } from './commands/query.ts';
8
+ import { buildCoverageReport, buildConceptGraph } from './commands/report.ts';
9
+ import { inScope, runStamp } from './commands/stamp.ts';
10
+ import { renderCoverageHtml } from './render/html.ts';
11
+ import { renderCoverageMarkdown } from './render/markdown.ts';
12
+
13
+ const HELP = `atlas — the map of the codebase
14
+
15
+ Usage: atlas <command> [target] [flags]
16
+
17
+ Commands:
18
+ graph reverse indexes: concept → files, file → concepts, doc → concepts
19
+ check [target] presence + vocab + reference existence (the CI command);
20
+ a target scopes to a path and skips registry-wide reference checks
21
+ coverage unannotated files; @uses curation buckets; unresolved memberships
22
+ gate with --min <pct> and/or --ratchet (vs a committed baseline)
23
+ generate write MAP.md from the annotated tree
24
+ report coverage gaps + concept graph → COVERAGE.md (Mermaid) and atlas.html (Cytoscape)
25
+ query [predicate] find files by axis — flags (--kind/--partOf/--uses/--path) and/or a
26
+ json-rules predicate (the same AST used for authz/filtering)
27
+ stamp [target] write/refresh @atlas blocks from the config rules (the patcher)
28
+
29
+ Flags:
30
+ --root <dir> repo root to operate on (default: cwd)
31
+ --json machine-readable output (graph/check/coverage/stamp)
32
+ --stdout print to stdout instead of writing a file (generate, report)
33
+ --out <dir> output directory for report files (report; default: root)
34
+ --md / --html emit only one report format (report; default: both)
35
+ --warn-only print problems but always exit 0 (check; warn-only rollout)
36
+ --min <pct> fail if annotated coverage is below this percentage (coverage)
37
+ --ratchet fail if unannotated count exceeds the baseline (coverage)
38
+ --update-baseline write the current unannotated count as the baseline (coverage)
39
+ --baseline <path> baseline file (default: .atlas/coverage-baseline.json)
40
+ --write persist changes (stamp; default is a dry-run)
41
+ --overwrite resync derivable @kind/@partOf, preserving curated @uses (stamp)
42
+ --kind/--partOf/--uses/--path <v> axis filters (query; AND together, combine with a predicate)
43
+ --version print version
44
+ --help this help`;
45
+
46
+ type Flags = Record<string, string | boolean>;
47
+
48
+ // Flags that consume the next token as a value; everything else is boolean.
49
+ const VALUE_FLAGS = new Set(['root', 'min', 'baseline', 'out', 'kind', 'partOf', 'uses', 'path']);
50
+
51
+ const parseArgs = (args: string[]): { flags: Flags; positionals: string[] } => {
52
+ const flags: Flags = {};
53
+ const positionals: string[] = [];
54
+ for (let i = 0; i < args.length; i++) {
55
+ const a = args[i]!;
56
+ if (a.startsWith('--')) {
57
+ const key = a.slice(2);
58
+ if (VALUE_FLAGS.has(key)) {
59
+ // Don't swallow the next flag as a value: `--min --json` leaves min empty
60
+ // (caught downstream) rather than silently capturing '--json'.
61
+ const next = args[i + 1];
62
+ flags[key] = next !== undefined && !next.startsWith('--') ? (i++, next) : '';
63
+ } else flags[key] = true;
64
+ } else positionals.push(a);
65
+ }
66
+ return { flags, positionals };
67
+ };
68
+
69
+ const version = async (): Promise<string> => {
70
+ const pkg = (await import('../package.json')) as { version?: string; default?: { version?: string } };
71
+ return pkg.version ?? pkg.default?.version ?? '0.0.0';
72
+ };
73
+
74
+ export const runCli = async (argv: string[], env: { cwd: string }): Promise<{ code: number; out: string }> => {
75
+ const out: string[] = [];
76
+ const log = (s = ''): void => void out.push(s);
77
+ const done = (code: number) => ({ code, out: out.join('\n') });
78
+
79
+ const { flags, positionals } = parseArgs(argv);
80
+ const command = positionals[0];
81
+ const root = (flags.root as string) || env.cwd;
82
+ const json = flags.json === true;
83
+
84
+ if (flags.version === true) return { code: 0, out: await version() };
85
+ if (flags.help === true || command === undefined || command === 'help') return { code: 0, out: HELP };
86
+
87
+ // Error boundary: any thrown error (bad config, IO, corrupt baseline) becomes a
88
+ // clean one-line message + exit 1, never an unhandled rejection / stack trace.
89
+ try {
90
+ return await dispatch(command, positionals, flags, { root, json, log, done });
91
+ } catch (err) {
92
+ return { code: 1, out: `atlas: ${err instanceof Error ? err.message : String(err)}` };
93
+ }
94
+ };
95
+
96
+ type Ctx = {
97
+ root: string;
98
+ json: boolean;
99
+ log: (s?: string) => void;
100
+ done: (code: number) => { code: number; out: string };
101
+ };
102
+
103
+ const dispatch = async (
104
+ command: string,
105
+ positionals: string[],
106
+ flags: Flags,
107
+ { root, json, log, done }: Ctx,
108
+ ): Promise<{ code: number; out: string }> => {
109
+ switch (command) {
110
+ case 'check': {
111
+ const target = positionals[1];
112
+ const warnOnly = flags['warn-only'] === true;
113
+ const full = await analyze(root);
114
+ const scoped = target ? { ...full, files: full.files.filter((f) => inScope(f.path, target)) } : full;
115
+ const result = await runCheck(scoped, { references: target === undefined });
116
+
117
+ if (json) log(JSON.stringify({ ...result, warnOnly }, null, 2));
118
+ else if (result.ok) log('✓ atlas check passed');
119
+ else {
120
+ log(`${warnOnly ? '⚠' : '✗'} atlas check: ${result.problems.length} problem(s)${warnOnly ? ' — warn-only' : ''}`);
121
+ for (const p of result.problems) log(` [${p.kind}] ${p.file ?? p.concept ?? ''} — ${p.message}`);
122
+ }
123
+ return done(result.ok || warnOnly ? 0 : 1);
124
+ }
125
+
126
+ case 'coverage': {
127
+ const c = coverage(await analyze(root));
128
+ const baselinePath = resolve(root, (flags.baseline as string) || '.atlas/coverage-baseline.json');
129
+
130
+ if (flags['update-baseline'] === true) {
131
+ await Bun.write(baselinePath, `${JSON.stringify({ unannotated: c.unannotated.length }, null, 2)}\n`);
132
+ log(`✓ wrote coverage baseline: ${c.unannotated.length} unannotated`);
133
+ return done(0);
134
+ }
135
+
136
+ let ratchet: number | undefined;
137
+ if (flags.ratchet === true) {
138
+ const baseline = await readBaseline(baselinePath);
139
+ if (baseline === null) {
140
+ log(`no baseline at ${baselinePath} — run: atlas coverage --update-baseline`);
141
+ return done(1);
142
+ }
143
+ ratchet = baseline;
144
+ }
145
+ let min: number | undefined;
146
+ if (flags.min !== undefined) {
147
+ min = Number(flags.min);
148
+ if (flags.min === '' || !Number.isFinite(min)) {
149
+ log(`✗ --min expects a number, got '${flags.min}'`);
150
+ return done(1);
151
+ }
152
+ }
153
+ const gate = evaluateCoverageGate(c, { min, ratchet });
154
+ const gating = min !== undefined || ratchet !== undefined;
155
+
156
+ if (json) {
157
+ log(JSON.stringify({ ...c, percent: gate.percent, gate }, null, 2));
158
+ } else {
159
+ log(`Coverage: ${c.annotated}/${c.total} files annotated (${gate.percent.toFixed(1)}%)`);
160
+ if (c.unannotated.length) log(` unannotated (${c.unannotated.length}):\n${c.unannotated.map((f) => ` ${f}`).join('\n')}`);
161
+ log(` @uses — curated ${c.uses.curated.length}, curated-empty ${c.uses.curatedEmpty.length}, proposed ${c.uses.proposed.length}, uncurated ${c.uses.uncurated.length}`);
162
+ if (c.unresolved.length) log(` unresolved memberships (${c.unresolved.length}):\n${c.unresolved.map((u) => ` ${u.file}: ${u.category}:${u.value}`).join('\n')}`);
163
+ if (!gate.ok) for (const r of gate.reasons) log(`✗ ${r}`);
164
+ else if (gating) log('✓ coverage gate passed');
165
+ }
166
+ return done(gate.ok ? 0 : 1);
167
+ }
168
+
169
+ case 'graph': {
170
+ const g = graph(await analyze(root));
171
+ if (json) log(JSON.stringify(g, null, 2));
172
+ else {
173
+ log('concept → files (@partOf):');
174
+ for (const concept of Object.keys(g.conceptToFiles).sort()) log(` ${concept} (${g.conceptToFiles[concept]!.length})`);
175
+ log('concept → consumers (@uses):');
176
+ for (const concept of Object.keys(g.usesConsumers).sort()) log(` ${concept} (${g.usesConsumers[concept]!.length})`);
177
+ }
178
+ return done(0);
179
+ }
180
+
181
+ case 'report': {
182
+ const a = await analyze(root);
183
+ const report = buildCoverageReport(a);
184
+ const conceptGraph = buildConceptGraph(a);
185
+
186
+ if (json) {
187
+ log(JSON.stringify({ report, graph: conceptGraph }, null, 2));
188
+ return done(0);
189
+ }
190
+ if (flags.stdout === true) {
191
+ log(renderCoverageMarkdown(report, conceptGraph));
192
+ return done(0);
193
+ }
194
+
195
+ const outDir = (flags.out as string) || root;
196
+ const wantMd = flags.html !== true || flags.md === true;
197
+ const wantHtml = flags.md !== true || flags.html === true;
198
+ const written: string[] = [];
199
+ if (wantMd) {
200
+ await Bun.write(resolve(outDir, 'COVERAGE.md'), renderCoverageMarkdown(report, conceptGraph));
201
+ written.push('COVERAGE.md');
202
+ }
203
+ if (wantHtml) {
204
+ await Bun.write(resolve(outDir, 'atlas.html'), renderCoverageHtml(report, conceptGraph));
205
+ written.push('atlas.html');
206
+ }
207
+ log(`✓ wrote ${written.join(', ')} (${report.total.files - report.total.missingBlock}/${report.total.files} annotated)`);
208
+ return done(0);
209
+ }
210
+
211
+ case 'generate': {
212
+ const map = generate(await analyze(root));
213
+ if (flags.stdout === true) log(map);
214
+ else {
215
+ await Bun.write(resolve(root, 'MAP.md'), map);
216
+ log(`✓ wrote MAP.md (${map.split('\n').length} lines)`);
217
+ }
218
+ return done(0);
219
+ }
220
+
221
+ case 'query': {
222
+ const records = toQueryRecords(await analyze(root));
223
+ const flagRule = flagsToRule({
224
+ kind: flags.kind as string | undefined,
225
+ partOf: flags.partOf as string | undefined,
226
+ uses: flags.uses as string | undefined,
227
+ path: flags.path as string | undefined,
228
+ });
229
+ let jsonRule: QueryRule | null = null;
230
+ const raw = positionals[1];
231
+ if (raw) {
232
+ try {
233
+ jsonRule = JSON.parse(raw) as QueryRule;
234
+ } catch {
235
+ log(`✗ query: invalid json-rules predicate (not valid JSON): ${raw}`);
236
+ return done(1);
237
+ }
238
+ }
239
+ const rule: QueryRule | null =
240
+ flagRule && jsonRule ? ({ all: [flagRule, jsonRule] } as QueryRule) : (jsonRule ?? flagRule);
241
+ if (!rule) {
242
+ log('query needs a json-rules predicate and/or at least one of --kind/--partOf/--uses/--path');
243
+ return done(1);
244
+ }
245
+ const hits = queryFiles(records, rule);
246
+ if (json) log(JSON.stringify(hits, null, 2));
247
+ else {
248
+ log(`${hits.length} file(s):`);
249
+ for (const h of hits) log(` ${h.path}`);
250
+ }
251
+ return done(0);
252
+ }
253
+
254
+ case 'stamp': {
255
+ const mode = flags.overwrite === true ? 'overwrite' : 'additive';
256
+ const write = flags.write === true;
257
+ const { changes, unresolved } = await runStamp(root, { mode, target: positionals[1], write });
258
+ if (json) {
259
+ log(JSON.stringify({ changes: changes.map((c) => ({ path: c.path })), unresolved }, null, 2));
260
+ } else {
261
+ if (!changes.length) log('✓ nothing to stamp — already up to date');
262
+ else {
263
+ log(`${write ? 'Wrote' : 'Would change'} ${changes.length} file(s)${write ? '' : ' (dry-run — pass --write to apply)'}:`);
264
+ for (const c of changes) log(` ${c.path}`);
265
+ }
266
+ // A capture that resolves to no concept leaves the file without @partOf —
267
+ // surface it here so the registry gap isn't invisible at write time.
268
+ if (unresolved.length) {
269
+ log(`⚠ ${unresolved.length} unresolved membership(s) — left unstamped (add the concept to .atlas/concepts.ts):`);
270
+ for (const u of unresolved) log(` ${u.file}: ${u.category}:${u.value}`);
271
+ }
272
+ }
273
+ return done(0);
274
+ }
275
+
276
+ default:
277
+ log(`unknown command: ${command}\n`);
278
+ log(HELP);
279
+ return done(1);
280
+ }
281
+ };
@@ -0,0 +1,71 @@
1
+ import { resolve } from 'node:path';
2
+ import type { Analysis } from '../analyze.ts';
3
+
4
+ // Enforcement is EXISTENCE, not correctness: presence of a block, validity of
5
+ // the vocabulary used, and existence of referenced docs. atlas never
6
+ // checks "is this @partOf actually true" or any derived status — fool's errands.
7
+ export type Problem = {
8
+ kind: 'presence' | 'vocab' | 'reference';
9
+ file?: string;
10
+ concept?: string;
11
+ message: string;
12
+ };
13
+
14
+ export type CheckResult = { ok: boolean; problems: Problem[] };
15
+
16
+ // presence — every considered (non-ignored) file carries an @atlas block.
17
+ export const checkPresence = (a: Analysis): Problem[] =>
18
+ a.files
19
+ .filter((f) => f.annotation === null)
20
+ .map((f) => ({ kind: 'presence' as const, file: f.path, message: 'missing @atlas block' }));
21
+
22
+ // vocab existence — @kind is in the vocab; @partOf/@uses name a concept that
23
+ // EXISTS in the registry (not: is the file really part of it).
24
+ export const checkVocab = (a: Analysis): Problem[] => {
25
+ const kinds = new Set(a.config.kinds);
26
+ const concepts = new Set(Object.keys(a.config.concepts));
27
+ const problems: Problem[] = [];
28
+ for (const { path, annotation } of a.files) {
29
+ if (!annotation) continue;
30
+ for (const k of annotation.kind) if (!kinds.has(k)) problems.push({ kind: 'vocab', file: path, message: `unknown @kind '${k}'` });
31
+ for (const p of annotation.partOf)
32
+ if (!concepts.has(p)) problems.push({ kind: 'vocab', file: path, message: `@partOf '${p}' is not a registered concept` });
33
+ for (const u of annotation.uses)
34
+ if (!concepts.has(u)) problems.push({ kind: 'vocab', file: path, message: `@uses '${u}' is not a registered concept` });
35
+ }
36
+ return problems;
37
+ };
38
+
39
+ // reference existence — a concept's doc paths resolve to real files.
40
+ export const checkReferences = async (a: Analysis): Promise<Problem[]> => {
41
+ const problems: Problem[] = [];
42
+ for (const [concept, entry] of Object.entries(a.config.concepts)) {
43
+ for (const [field, resolver] of Object.entries(a.config.references)) {
44
+ for (const value of entry[field] ?? []) {
45
+ // The resolver is consumer code — a throw becomes a structured problem,
46
+ // never an unhandled crash of the whole check.
47
+ let rel: string;
48
+ try {
49
+ rel = resolver(value);
50
+ } catch (err) {
51
+ const msg = err instanceof Error ? err.message : String(err);
52
+ problems.push({ kind: 'reference', concept, message: `${concept}: ${field} resolver threw on '${value}': ${msg}` });
53
+ continue;
54
+ }
55
+ if (!(await Bun.file(resolve(a.root, rel)).exists())) {
56
+ problems.push({ kind: 'reference', concept, message: `${concept}: ${field} reference '${value}' → ${rel} does not exist` });
57
+ }
58
+ }
59
+ }
60
+ }
61
+ return problems;
62
+ };
63
+
64
+ // Reference existence is a registry-wide concern, so it is skipped when a run is
65
+ // scoped to a subset of files (incremental PR checks) — only the file-level
66
+ // presence/vocab checks make sense there.
67
+ export const runCheck = async (a: Analysis, opts: { references?: boolean } = {}): Promise<CheckResult> => {
68
+ const problems = [...checkPresence(a), ...checkVocab(a)];
69
+ if (opts.references !== false) problems.push(...(await checkReferences(a)));
70
+ return { ok: problems.length === 0, problems };
71
+ };
@@ -0,0 +1,86 @@
1
+ import type { Analysis } from '../analyze.ts';
2
+ import { stampFor } from '../config/stamp.ts';
3
+
4
+ // The signal you lose the moment you auto-stamp `@uses none` everywhere: absence
5
+ // (uncurated) is distinct from explicit-empty (curated), and a patcher proposal
6
+ // is distinct from both.
7
+ export type Coverage = {
8
+ total: number;
9
+ annotated: number;
10
+ unannotated: string[];
11
+ uses: {
12
+ uncurated: string[]; // no @uses line — nobody filled it in
13
+ curatedEmpty: string[]; // explicit @uses none — a human looked, it uses nothing
14
+ proposed: string[]; // tentative @uses? — patcher proposed, awaiting acceptance
15
+ curated: string[]; // real @uses values
16
+ };
17
+ // membership captures (partOfFor) that matched no concept — fillable signal, not an error.
18
+ unresolved: { file: string; category: string; value: string }[];
19
+ };
20
+
21
+ // A CI gate over a coverage snapshot. `min` is a percentage floor; `ratchet` is
22
+ // a backslide guard — the unannotated count may not exceed a committed baseline,
23
+ // which is how a repo starting near 0% enforces "every new file is annotated"
24
+ // without demanding an unreachable percentage on day one.
25
+ export type CoverageGate = { min?: number; ratchet?: number };
26
+ export type GateResult = { ok: boolean; reasons: string[]; percent: number };
27
+
28
+ export const evaluateCoverageGate = (c: Coverage, gate: CoverageGate): GateResult => {
29
+ const percent = c.total === 0 ? 100 : (c.annotated / c.total) * 100;
30
+ const reasons: string[] = [];
31
+ const gating = gate.min !== undefined || gate.ratchet !== undefined;
32
+ // Zero files under an active gate is almost always a misconfig (wrong --root,
33
+ // an include that matched nothing), not a real 100% — fail rather than pass.
34
+ if (gating && c.total === 0) {
35
+ reasons.push('0 files matched — check --root / include / ignore');
36
+ }
37
+ if (gate.min !== undefined && percent < gate.min) {
38
+ reasons.push(`coverage ${percent.toFixed(1)}% is below the --min ${gate.min}% floor`);
39
+ }
40
+ if (gate.ratchet !== undefined && c.unannotated.length > gate.ratchet) {
41
+ reasons.push(
42
+ `unannotated files rose to ${c.unannotated.length} (baseline ${gate.ratchet}) — annotate the new files or run --update-baseline`,
43
+ );
44
+ }
45
+ return { ok: reasons.length === 0, reasons, percent };
46
+ };
47
+
48
+ // Baseline file holds just the unannotated count: { "unannotated": <n> }.
49
+ export const readBaseline = async (path: string): Promise<number | null> => {
50
+ const file = Bun.file(path);
51
+ if (!(await file.exists())) return null;
52
+ let data: { unannotated?: number };
53
+ try {
54
+ data = (await file.json()) as { unannotated?: number };
55
+ } catch {
56
+ throw new Error(`baseline at ${path} is not valid JSON — re-run: atlas coverage --update-baseline`);
57
+ }
58
+ return typeof data.unannotated === 'number' ? data.unannotated : null;
59
+ };
60
+
61
+ export const coverage = (a: Analysis): Coverage => {
62
+ const unannotated: string[] = [];
63
+ const uses = { uncurated: [] as string[], curatedEmpty: [] as string[], proposed: [] as string[], curated: [] as string[] };
64
+ const unresolved: Coverage['unresolved'] = [];
65
+
66
+ for (const { path, annotation } of a.files) {
67
+ if (!annotation) {
68
+ unannotated.push(path);
69
+ } else {
70
+ const bucket =
71
+ annotation.usesState === 'absent'
72
+ ? uses.uncurated
73
+ : annotation.usesState === 'none'
74
+ ? uses.curatedEmpty
75
+ : annotation.usesState === 'proposed'
76
+ ? uses.proposed
77
+ : uses.curated;
78
+ bucket.push(path);
79
+ }
80
+ for (const u of stampFor(path, a.config.stamp, a.config.concepts).unresolved) {
81
+ unresolved.push({ file: path, category: u.category, value: u.value });
82
+ }
83
+ }
84
+
85
+ return { total: a.files.length, annotated: a.files.length - unannotated.length, unannotated, uses, unresolved };
86
+ };
@@ -0,0 +1,54 @@
1
+ import type { Analysis } from '../analyze.ts';
2
+ import { conceptClass } from '../registry/types.ts';
3
+ import { graph } from './graph.ts';
4
+
5
+ // MAP.md — the high-altitude entry point that defeats grab-bag: every concept,
6
+ // grouped by class, with its constituent files (by @partOf), a kind breakdown,
7
+ // and its @uses consumers. Fully sorted, so it is byte-stable in CI and a diff
8
+ // means a real structural change.
9
+ export const generate = (a: Analysis): string => {
10
+ const g = graph(a);
11
+
12
+ const fileKinds: Record<string, string[]> = {};
13
+ for (const { path, annotation } of a.files) if (annotation) fileKinds[path] = annotation.kind;
14
+
15
+ const byClass: Record<string, string[]> = {};
16
+ for (const concept of Object.keys(a.config.concepts)) {
17
+ const cls = conceptClass(concept) ?? 'other';
18
+ (byClass[cls] ??= []).push(concept);
19
+ }
20
+
21
+ const lines: string[] = ['# MAP', '', '_Generated by `atlas generate`. Do not edit by hand._', ''];
22
+
23
+ for (const cls of Object.keys(byClass).sort()) {
24
+ lines.push(`## ${cls}`, '');
25
+ for (const concept of byClass[cls]!.sort()) {
26
+ lines.push(`### ${concept}`);
27
+
28
+ const entry = a.config.concepts[concept]!;
29
+ for (const field of Object.keys(entry).sort()) {
30
+ const values = entry[field];
31
+ if (values?.length) lines.push(`- ${field}: ${values.join(', ')}`);
32
+ }
33
+
34
+ const members = g.conceptToFiles[concept] ?? [];
35
+ const counts: Record<string, number> = {};
36
+ for (const file of members) for (const k of fileKinds[file] ?? []) counts[k] = (counts[k] ?? 0) + 1;
37
+ const breakdown = Object.keys(counts)
38
+ .sort()
39
+ .map((k) => `${k}(${counts[k]})`)
40
+ .join(', ');
41
+ lines.push(`- files (${members.length})${breakdown ? `: ${breakdown}` : ''}`);
42
+ for (const file of members) lines.push(` - ${file} — ${(fileKinds[file] ?? []).join(', ')}`);
43
+
44
+ const consumers = g.usesConsumers[concept] ?? [];
45
+ if (consumers.length) {
46
+ lines.push(`- consumers (${consumers.length}):`);
47
+ for (const file of consumers) lines.push(` - ${file}`);
48
+ }
49
+ lines.push('');
50
+ }
51
+ }
52
+
53
+ return `${lines.join('\n').trimEnd()}\n`;
54
+ };
@@ -0,0 +1,38 @@
1
+ import type { Analysis } from '../analyze.ts';
2
+ import { invert } from '../registry/invert.ts';
3
+
4
+ // The bidirectional indexes — "show me everything that touches caching" in one
5
+ // traversal. concept→files and concept→consumers come from the annotated tree;
6
+ // doc→concepts comes from inverting the registry's `docs` reference field.
7
+ export type Graph = {
8
+ conceptToFiles: Record<string, string[]>; // via @partOf (membership)
9
+ usesConsumers: Record<string, string[]>; // via @uses (dependency)
10
+ fileToConcepts: Record<string, { partOf: string[]; uses: string[] }>;
11
+ docToConcepts: Record<string, string[]>;
12
+ };
13
+
14
+ const push = (rec: Record<string, string[]>, key: string, val: string): void => {
15
+ (rec[key] ??= []).push(val);
16
+ };
17
+
18
+ export const graph = (a: Analysis): Graph => {
19
+ const conceptToFiles: Record<string, string[]> = {};
20
+ const usesConsumers: Record<string, string[]> = {};
21
+ const fileToConcepts: Graph['fileToConcepts'] = {};
22
+
23
+ for (const { path, annotation } of a.files) {
24
+ if (!annotation) continue;
25
+ fileToConcepts[path] = { partOf: annotation.partOf, uses: annotation.uses };
26
+ for (const concept of annotation.partOf) push(conceptToFiles, concept, path);
27
+ for (const concept of annotation.uses) push(usesConsumers, concept, path);
28
+ }
29
+ for (const key of Object.keys(conceptToFiles)) conceptToFiles[key]!.sort();
30
+ for (const key of Object.keys(usesConsumers)) usesConsumers[key]!.sort();
31
+
32
+ return {
33
+ conceptToFiles,
34
+ usesConsumers,
35
+ fileToConcepts,
36
+ docToConcepts: invert(a.config.concepts, 'docs'),
37
+ };
38
+ };
@@ -0,0 +1,33 @@
1
+ import { check } from '@inixiative/json-rules';
2
+ import type { Analysis } from '../analyze.ts';
3
+
4
+ // A file flattened to its queryable axes. Unannotated files get empty arrays so
5
+ // "files with no @kind" style queries work too.
6
+ export type QueryRecord = { path: string; kind: string[]; partOf: string[]; uses: string[] };
7
+
8
+ // A json-rules predicate (the same AST the repo already uses for authz/filtering).
9
+ export type QueryRule = Parameters<typeof check>[0];
10
+
11
+ export const toQueryRecords = (a: Analysis): QueryRecord[] =>
12
+ a.files.map((f) => ({
13
+ path: f.path,
14
+ kind: f.annotation?.kind ?? [],
15
+ partOf: f.annotation?.partOf ?? [],
16
+ uses: f.annotation?.uses ?? [],
17
+ }));
18
+
19
+ export type QueryFlags = { kind?: string; partOf?: string; uses?: string; path?: string };
20
+
21
+ // Desugar the common flags into a json-rules predicate (AND of `contains`).
22
+ // Returns null when no flag is set (nothing to filter on).
23
+ export const flagsToRule = (flags: QueryFlags): QueryRule | null => {
24
+ const clauses = (['kind', 'partOf', 'uses', 'path'] as const)
25
+ .filter((f) => flags[f] !== undefined)
26
+ .map((f) => ({ field: f, operator: 'contains', value: flags[f] }));
27
+ if (clauses.length === 0) return null;
28
+ return (clauses.length === 1 ? clauses[0] : { all: clauses }) as QueryRule;
29
+ };
30
+
31
+ // A record matches when json-rules `check` passes (it returns the error string otherwise).
32
+ export const queryFiles = (records: QueryRecord[], rule: QueryRule): QueryRecord[] =>
33
+ records.filter((r) => check(rule, r) === true);
Binary file
@@ -0,0 +1,74 @@
1
+ import { resolve } from 'node:path';
2
+ import type { LoadedConfig } from '../config/defineConfig.ts';
3
+ import { loadConfig } from '../config/load.ts';
4
+ import { stampFor } from '../config/stamp.ts';
5
+ import { mapLimit } from '../fs/concurrent.ts';
6
+ import { walkFiles } from '../fs/walk.ts';
7
+ import { applyStamp, type StampMode } from '../stamp/patcher.ts';
8
+
9
+ export type StampChange = { path: string; before: string; after: string };
10
+ export type Unresolved = { file: string; category: string; value: string };
11
+ export type StampResult = { changes: StampChange[]; unresolved: Unresolved[] };
12
+
13
+ const IO_CONCURRENCY = 64;
14
+
15
+ // A file is in scope when no target is given, when the target IS the file, or
16
+ // when the target is a folder the file lives under. (all / folder / individual)
17
+ export const inScope = (path: string, target?: string): boolean => {
18
+ if (!target) return true;
19
+ if (path === target) return true;
20
+ const folder = target.endsWith('/') ? target : `${target}/`;
21
+ return path.startsWith(folder);
22
+ };
23
+
24
+ // Pure: what stamping a file WOULD do, or null if it's already up to date.
25
+ export const computeStamp = (
26
+ path: string,
27
+ source: string,
28
+ config: LoadedConfig,
29
+ mode: StampMode,
30
+ ): StampChange | null => {
31
+ const resolved = stampFor(path, config.stamp, config.concepts);
32
+ const { content, changed } = applyStamp(source, resolved, mode);
33
+ return changed ? { path, before: source, after: content } : null;
34
+ };
35
+
36
+ // Pure: the full change plan over an in-memory file set, scoped by target.
37
+ export const planStamp = (
38
+ files: { path: string; source: string }[],
39
+ config: LoadedConfig,
40
+ mode: StampMode,
41
+ target?: string,
42
+ ): StampChange[] =>
43
+ files
44
+ .filter((f) => inScope(f.path, target))
45
+ .map((f) => computeStamp(f.path, f.source, config, mode))
46
+ .filter((c): c is StampChange => c !== null);
47
+
48
+ // IO: read the scoped files, plan, and (only with write) persist. Dry-run is
49
+ // the default everywhere — writing requires the explicit flag. Reads/writes are
50
+ // concurrency-bounded so a large repo can't exhaust file descriptors. Unresolved
51
+ // memberships are surfaced here (not just in `coverage`) so a capture that maps
52
+ // to no concept — leaving a file under-stamped — is visible at write time.
53
+ export const runStamp = async (
54
+ root: string,
55
+ opts: { mode: StampMode; target?: string; write: boolean },
56
+ ): Promise<StampResult> => {
57
+ const config = await loadConfig(root);
58
+ const paths = (await walkFiles(root, config.include, config.ignore)).filter((p) => inScope(p, opts.target));
59
+ const files = await mapLimit(paths, IO_CONCURRENCY, async (path) => ({
60
+ path,
61
+ source: await Bun.file(resolve(root, path)).text(),
62
+ }));
63
+
64
+ const changes = planStamp(files, config, opts.mode, opts.target);
65
+ const unresolved: Unresolved[] = [];
66
+ for (const { path } of files) {
67
+ for (const u of stampFor(path, config.stamp, config.concepts).unresolved) {
68
+ unresolved.push({ file: path, category: u.category, value: u.value });
69
+ }
70
+ }
71
+
72
+ if (opts.write) await mapLimit(changes, IO_CONCURRENCY, (c) => Bun.write(resolve(root, c.path), c.after));
73
+ return { changes, unresolved };
74
+ };