@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.
@@ -0,0 +1,86 @@
1
+ import type { CoverageReport, Gaps, ConceptGraph } from '../commands/report.ts';
2
+
3
+ // Injective sanitizer for Mermaid node ids: distinct concept ids never collide
4
+ // (encoding the char code keeps `feature:billing` and `feature.billing` apart).
5
+ export const safeId = (id: string): string => id.replace(/[^a-zA-Z0-9]/g, (c) => `_${c.charCodeAt(0)}_`);
6
+
7
+ // Escape a Mermaid quoted-label so a `"` in a concept id can't break the diagram
8
+ // or inject directives.
9
+ const safeLabel = (s: string): string => s.replace(/"/g, '"');
10
+
11
+ const totalsTable = (t: Gaps): string =>
12
+ [
13
+ '| metric | count |',
14
+ '|--------|------:|',
15
+ `| files | ${t.files} |`,
16
+ `| missing block | ${t.missingBlock} |`,
17
+ `| missing @kind (required) | ${t.missingKind} |`,
18
+ `| missing @partOf (required) | ${t.missingPartOf} |`,
19
+ `| @uses uncurated | ${t.usesUncurated} |`,
20
+ `| @uses curated-empty | ${t.usesCuratedEmpty} |`,
21
+ `| @uses curated | ${t.usesCurated} |`,
22
+ `| @uses proposed | ${t.usesProposed} |`,
23
+ ].join('\n');
24
+
25
+ const pie = (t: Gaps): string =>
26
+ ['```mermaid', 'pie title Annotation coverage', ` "annotated" : ${t.files - t.missingBlock}`, ` "missing block" : ${t.missingBlock}`, '```'].join(
27
+ '\n',
28
+ );
29
+
30
+ const categoryTable = (report: CoverageReport): string => {
31
+ const head = [
32
+ '| category | files | no block | no @kind | no @partOf | uncurated | curated-empty | curated |',
33
+ '|----------|------:|---------:|---------:|-----------:|----------:|--------------:|--------:|',
34
+ ];
35
+ const rows = report.categories.map(
36
+ (c) =>
37
+ `| ${c.category} | ${c.files} | ${c.missingBlock} | ${c.missingKind} | ${c.missingPartOf} | ${c.usesUncurated} | ${c.usesCuratedEmpty} | ${c.usesCurated} |`,
38
+ );
39
+ return [...head, ...rows].join('\n');
40
+ };
41
+
42
+ const conceptGraph = (graph: ConceptGraph): string => {
43
+ const lines = ['```mermaid', 'graph LR'];
44
+ const byClass: Record<string, typeof graph.nodes> = {};
45
+ for (const n of graph.nodes) (byClass[n.cls] ??= []).push(n);
46
+ for (const cls of Object.keys(byClass).sort()) {
47
+ lines.push(` subgraph ${cls}`);
48
+ for (const n of byClass[cls]!) lines.push(` ${safeId(n.id)}["${safeLabel(n.id)}"]`);
49
+ lines.push(' end');
50
+ }
51
+ for (const e of graph.edges) lines.push(` ${safeId(e.source)} --> ${safeId(e.target)}`);
52
+ lines.push('```');
53
+ return lines.join('\n');
54
+ };
55
+
56
+ // COVERAGE.md — diffable, GitHub-native (Mermaid renders inline). Totals + a
57
+ // coverage pie + a per-category gap table + the concept dependency graph.
58
+ export const renderCoverageMarkdown = (report: CoverageReport, graph: ConceptGraph): string =>
59
+ [
60
+ '# Coverage',
61
+ '',
62
+ '_Generated by `atlas report`. Do not edit by hand._',
63
+ '',
64
+ '## Totals',
65
+ '',
66
+ totalsTable(report.total),
67
+ '',
68
+ pie(report.total),
69
+ '',
70
+ '## By category',
71
+ '',
72
+ 'Grouped by effective concept (declared `@partOf`, else the rules’ predicted concept). `@uses` columns',
73
+ 'are curation signals, not failures.',
74
+ ...(report.filesInMultipleConcepts > 0
75
+ ? ['', `> ${report.filesInMultipleConcepts} file(s) belong to multiple concepts, so the per-category file counts sum to more than the total.`]
76
+ : []),
77
+ '',
78
+ categoryTable(report),
79
+ '',
80
+ '## Concept graph',
81
+ '',
82
+ 'Edges are `@partOf` → `@uses`: a concept depends on what its files use.',
83
+ '',
84
+ conceptGraph(graph),
85
+ '',
86
+ ].join('\n');
@@ -0,0 +1,111 @@
1
+ import { type AtlasAnnotation, locateAtlasBlock, parseAtlasBlock, type UsesState } from '../parse/parseAtlasBlock.ts';
2
+
3
+ export type BlockSpec = {
4
+ kind?: string[];
5
+ partOf?: string[];
6
+ uses?: string[];
7
+ usesState?: UsesState;
8
+ constructs?: string[];
9
+ pinned?: boolean;
10
+ };
11
+
12
+ // What the rules produce for a file — the derivable axes only (@uses is never
13
+ // auto-stamped). `constructs` is optional because not every rule set touches it.
14
+ export type StampInput = {
15
+ kind?: string[];
16
+ partOf?: string[];
17
+ constructs?: string[];
18
+ };
19
+
20
+ export type StampMode = 'additive' | 'overwrite';
21
+
22
+ const line = (axis: string, values: string[]): string => ` * @${axis} ${values.join(', ')}`;
23
+
24
+ // Render a canonical `@atlas` block. Axis order is fixed for diff-stability.
25
+ export const renderBlock = (spec: BlockSpec): string => {
26
+ const lines = ['/**', spec.pinned ? ' * @atlas pin' : ' * @atlas'];
27
+ if (spec.kind?.length) lines.push(line('kind', spec.kind));
28
+ if (spec.partOf?.length) lines.push(line('partOf', spec.partOf));
29
+ if (spec.usesState === 'none') lines.push(' * @uses none');
30
+ else if (spec.usesState === 'proposed' && spec.uses?.length) lines.push(line('uses?', spec.uses));
31
+ else if (spec.usesState === 'values' && spec.uses?.length) lines.push(line('uses', spec.uses));
32
+ if (spec.constructs?.length) lines.push(line('constructs', spec.constructs));
33
+ lines.push(' */');
34
+ return lines.join('\n');
35
+ };
36
+
37
+ const union = (a: string[] = [], b: string[] = []): string[] => [...new Set([...a, ...b])];
38
+
39
+ const detectEol = (source: string): string => (source.includes('\r\n') ? '\r\n' : '\n');
40
+
41
+ // Renders the canonical (LF) block, then matches the file's existing EOL so a
42
+ // CRLF file round-trips without churn or mixed endings.
43
+ const renderWithEol = (spec: BlockSpec, eol: string): string =>
44
+ eol === '\n' ? renderBlock(spec) : renderBlock(spec).replaceAll('\n', eol);
45
+
46
+ // A fresh block belongs at the top, but below a shebang (moving it above would
47
+ // break an executable script).
48
+ const SHEBANG = /^#![^\n]*\n/;
49
+
50
+ const carryUses = (existing: AtlasAnnotation | null): Pick<BlockSpec, 'uses' | 'usesState'> =>
51
+ existing ? { uses: existing.uses, usesState: existing.usesState } : {};
52
+
53
+ // Merge a stamp into a file's source per mode. Returns the new content and
54
+ // whether anything changed (idempotent: a no-op re-stamp reports changed=false).
55
+ export const applyStamp = (
56
+ source: string,
57
+ resolved: StampInput,
58
+ mode: StampMode = 'additive',
59
+ ): { content: string; changed: boolean } => {
60
+ const existing = parseAtlasBlock(source);
61
+ const located = locateAtlasBlock(source);
62
+ const eol = detectEol(source);
63
+
64
+ // No block yet — insert a fresh one at the top (uses omitted = uncurated),
65
+ // but below a shebang so an executable file keeps working.
66
+ if (!existing || !located) {
67
+ const spec: BlockSpec = {
68
+ kind: resolved.kind ?? [],
69
+ partOf: [...(resolved.partOf ?? [])].sort(),
70
+ constructs: resolved.constructs ?? [],
71
+ };
72
+ const hasAny = [spec.kind, spec.partOf, spec.constructs].some((v) => v && v.length);
73
+ if (!hasAny) return { content: source, changed: false };
74
+ const block = renderWithEol(spec, eol);
75
+ const shebang = SHEBANG.exec(source)?.[0];
76
+ const content = shebang
77
+ ? shebang + block + eol + source.slice(shebang.length)
78
+ : block + eol + source;
79
+ return { content, changed: true };
80
+ }
81
+
82
+ // Overwrite is exempt on a pinned block — the hand-curated overload wins.
83
+ if (mode === 'overwrite' && existing.pinned) return { content: source, changed: false };
84
+
85
+ const pick = (next: string[] | undefined, prev: string[]): string[] => (next && next.length ? next : prev);
86
+
87
+ const merged: BlockSpec =
88
+ mode === 'overwrite'
89
+ ? {
90
+ // resync the derivable axes to the rules; keep curated @uses
91
+ kind: pick(resolved.kind, existing.kind),
92
+ partOf: pick(resolved.partOf, existing.partOf),
93
+ constructs: pick(resolved.constructs, existing.constructs),
94
+ ...carryUses(existing),
95
+ pinned: existing.pinned,
96
+ }
97
+ : {
98
+ // additive: add what's absent, never remove, never touch @uses
99
+ kind: union(existing.kind, resolved.kind),
100
+ partOf: union(existing.partOf, resolved.partOf),
101
+ constructs: union(existing.constructs, resolved.constructs),
102
+ ...carryUses(existing),
103
+ pinned: existing.pinned,
104
+ };
105
+ // @partOf is sorted so a merged block matches a freshly-stamped one (stampFor sorts).
106
+ merged.partOf = [...(merged.partOf ?? [])].sort();
107
+
108
+ const block = renderWithEol(merged, eol);
109
+ if (block === located.text) return { content: source, changed: false };
110
+ return { content: source.slice(0, located.start) + block + source.slice(located.end), changed: true };
111
+ };
@@ -0,0 +1,52 @@
1
+ // atlas default `@kind` vocabulary — the ROLE a file plays ("what is this?").
2
+ //
3
+ // Closed set, but the consumer EXTENDS it:
4
+ // export const KINDS = [...DEFAULT_KINDS, 'job', 'migration'] as const
5
+ // atlas validates `@kind` against the merged set the repo provides; it does not
6
+ // force this list on anyone. These are near-universal file roles.
7
+ //
8
+ // IMPORTANT — kind is a ROLE, not a LAYER. The architectural layer is the concept
9
+ // CLASS (the `class:` prefix: feature / primitive / infrastructure), expressed via
10
+ // @partOf, never via @kind. So a file is NOT `@kind infrastructure`; it's e.g.
11
+ // `@kind client @partOf infrastructure:redis`, and a building block is
12
+ // `@kind <role> @partOf primitive:caching`. That's why `primitive`/`infrastructure`
13
+ // are NOT kinds here. (`registry` IS a kind — it's the role "a config table", not a
14
+ // layer; a feature-flags table is `@kind registry @partOf feature:featureFlags`.)
15
+
16
+ export const DEFAULT_KINDS = [
17
+ // ── backend / shared ──────────────────────────────────────────────────────
18
+ 'controller', // request handler in modules/*/controllers
19
+ 'route', // route definition in modules/*/routes
20
+ 'middleware', // middleware/*
21
+ 'handler', // handler — pair with @partOf (jobs, app-events, db mutation hooks)
22
+ 'helper', // small focused helper bound to a concept (vs generic `utils`)
23
+ 'service', // domain logic in modules/*/services and internal module parts
24
+ 'query', // a db query builder / include / select shape (modules/*/queries)
25
+ 'schema', // request/response schemas in modules/*/schemas
26
+ 'validator', // modules/*/validations
27
+ 'transformer', // value/shape transformers (serialize, normalize, project)
28
+ 'bridge', // connects two systems (e.g. an app-event → email/websocket bridge)
29
+ 'client', // a connection/client to an external dependency (redis, prisma, s3…)
30
+ 'adapter', // an implementation of an interface behind a port (the adapter pattern)
31
+ 'integration', // glue to an external service (webhooks, oauth handshakes, SDK wrappers)
32
+ 'factory', // test factory (packages/db/src/test/factories)
33
+ 'constructor', // make*() factory producing a category of thing; pair with @constructs
34
+ 'entrypoint', // the way into a concept (ws/index, app bootstrap) — a concept may have several
35
+ 'config', // configuration / env wiring
36
+ 'constant', // a closed set of literal values / lookup table, no behavioral hook
37
+ 'definition', // a static definition entry consumed by a registry (vs the behavioral `registry`)
38
+ 'registry', // a declarative config table that drives runtime behavior (the registry pattern)
39
+ 'type', // a pure type-only module (no runtime), distinct from a Zod schema
40
+ 'error', // an error class / error type definition
41
+ 'seed', // db seed
42
+ 'generator', // a code-generation script (produces source / types)
43
+ 'utils', // generic helper; also the catch-all when path can't classify
44
+
45
+ // ── frontend ────────────────────────────────────────────────────────────────
46
+ 'component', // reusable React component
47
+ 'page', // page/view component
48
+ 'hook', // React hook (use*)
49
+ 'store', // zustand store/slice
50
+ ] as const;
51
+
52
+ export type DefaultKind = (typeof DEFAULT_KINDS)[number];