@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,59 @@
1
+ import type { ConceptRegistry } from '../registry/types.ts';
2
+
3
+ // `partOfFor` is a LAZY descriptor, not a value. The consumer's config.ts can
4
+ // reference it before the concept registry is loaded; the stamp engine resolves it
5
+ // later against the loaded registry. This is what lets `.atlas/config.ts` and
6
+ // `.atlas/concepts.ts` be separate files with no evaluation-order coupling.
7
+ export type PartOfForDescriptor = { __atlasPartOfFor: true; category: string; capture: string };
8
+
9
+ // Fill @partOf by resolving a captured path segment through the inverse of a
10
+ // consumer-defined constituent category: partOfFor('module', '$1').
11
+ // `category` and `'module'` are NOT atlas concepts — the repo defines them.
12
+ export const partOfFor = (category: string, capture: string): PartOfForDescriptor => ({
13
+ __atlasPartOfFor: true,
14
+ category,
15
+ capture,
16
+ });
17
+
18
+ export const isPartOfFor = (v: unknown): v is PartOfForDescriptor => {
19
+ if (typeof v !== 'object' || v === null) return false;
20
+ const d = v as Partial<PartOfForDescriptor>;
21
+ return d.__atlasPartOfFor === true && typeof d.category === 'string' && typeof d.capture === 'string';
22
+ };
23
+
24
+ // A tag value is a literal string (with optional `$n` interpolation), a list of
25
+ // those, or a lazy partOfFor descriptor.
26
+ export type TagValue = string | string[] | PartOfForDescriptor;
27
+
28
+ export type StampRule = {
29
+ include: string | string[];
30
+ kind?: TagValue;
31
+ partOf?: TagValue;
32
+ constructs?: TagValue;
33
+ // @uses is NEVER auto-stamped — absence is a signal (uncurated), so atlas
34
+ // leaves it out entirely. There is intentionally no `uses` field here.
35
+ };
36
+
37
+ // field name (e.g. 'docs') → a value's repo-relative path, so
38
+ // `atlas check` can verify the reference exists on disk.
39
+ export type ReferenceResolver = (value: string) => string;
40
+
41
+ // The defaultable fields, defined once so input (all optional) and loaded (all
42
+ // present) stay in lockstep — adding a field can't drift between the two.
43
+ type ConfigDefaults = {
44
+ stamp: StampRule[]; // path → tag rules
45
+ ignore: string[]; // files exempt from presence + stamping (tests, barrels)
46
+ include: string[]; // file globs atlas considers (default: common source files)
47
+ references: Record<string, ReferenceResolver>;
48
+ };
49
+
50
+ export type AtlasConfigInput = Partial<ConfigDefaults>;
51
+
52
+ export const defineConfig = (config: AtlasConfigInput): AtlasConfigInput => config;
53
+
54
+ // What the loader hands the engine once defaults are applied and vocab/registry
55
+ // are loaded from the sibling .atlas/ files.
56
+ export type LoadedConfig = ConfigDefaults & {
57
+ kinds: readonly string[];
58
+ concepts: ConceptRegistry;
59
+ };
@@ -0,0 +1,83 @@
1
+ // Glob matcher for stamp `include` patterns and `ignore` lists, with the
2
+ // capture syntax atlas adds on top of ordinary globbing:
3
+ // * — match one segment, DISCARD
4
+ // ** — match many segments, DISCARD (trailing `/` makes it optional)
5
+ // $1.. — match one segment, CAPTURE, referenced by tag values / partOfFor
6
+ // You number only what you capture, in order of appearance, so `**` is never a
7
+ // capture and the multi-segment ambiguity disappears.
8
+
9
+ export type Captures = Record<number, string>;
10
+
11
+ const escapeChar = (c: string): string => (/[.+^${}()|[\]\\/]/.test(c) ? `\\${c}` : c);
12
+
13
+ // Translate one brace-alternation option, honouring `*`/`?` within it (so
14
+ // `{j*,ts}` matches `js`) rather than escaping them to literals.
15
+ const translateOption = (opt: string): string =>
16
+ [...opt].map((c) => (c === '*' ? '[^/]*' : c === '?' ? '[^/]' : escapeChar(c))).join('');
17
+
18
+ const globToRegex = (pattern: string): { re: RegExp; captureNums: number[] } => {
19
+ const captureNums: number[] = [];
20
+ let re = '^';
21
+ let i = 0;
22
+ while (i < pattern.length) {
23
+ const c = pattern[i]!;
24
+ if (c === '*') {
25
+ if (pattern[i + 1] === '*') {
26
+ if (pattern[i + 2] === '/') {
27
+ re += '(?:.*/)?'; // **/ — optional, so it matches at the root too
28
+ i += 3;
29
+ } else {
30
+ re += '.*'; // ** — across segments
31
+ i += 2;
32
+ }
33
+ } else {
34
+ re += '[^/]*'; // * — within a segment
35
+ i += 1;
36
+ }
37
+ } else if (c === '$' && /\d/.test(pattern[i + 1] ?? '')) {
38
+ let j = i + 1;
39
+ let num = '';
40
+ while (j < pattern.length && /\d/.test(pattern[j]!)) num += pattern[j++];
41
+ re += '([^/]+)';
42
+ captureNums.push(Number.parseInt(num, 10));
43
+ i = j;
44
+ } else if (c === '{') {
45
+ const end = pattern.indexOf('}', i);
46
+ if (end > i) {
47
+ const opts = pattern
48
+ .slice(i + 1, end)
49
+ .split(',')
50
+ .map(translateOption)
51
+ .join('|');
52
+ re += `(?:${opts})`;
53
+ i = end + 1;
54
+ } else {
55
+ re += '\\{';
56
+ i += 1;
57
+ }
58
+ } else if (c === '?') {
59
+ re += '[^/]';
60
+ i += 1;
61
+ } else {
62
+ re += escapeChar(c);
63
+ i += 1;
64
+ }
65
+ }
66
+ return { re: new RegExp(`${re}$`), captureNums };
67
+ };
68
+
69
+ // Returns the captures keyed by their `$n` number (`{}` when matched with no
70
+ // captures), or null when the path does not match the pattern.
71
+ export const matchGlob = (pattern: string, path: string): Captures | null => {
72
+ const { re, captureNums } = globToRegex(pattern);
73
+ const m = re.exec(path);
74
+ if (!m) return null;
75
+ const caps: Captures = {};
76
+ captureNums.forEach((n, idx) => {
77
+ caps[n] = m[idx + 1]!;
78
+ });
79
+ return caps;
80
+ };
81
+
82
+ export const matchesAny = (patterns: string[], path: string): boolean =>
83
+ patterns.some((p) => matchGlob(p, path) !== null);
@@ -0,0 +1,56 @@
1
+ import { resolve } from 'node:path';
2
+ import { DEFAULT_KINDS } from '../vocab/kinds.ts';
3
+ import { DEFAULT_INCLUDE } from '../fs/walk.ts';
4
+ import type { ConceptRegistry } from '../registry/types.ts';
5
+ import type { AtlasConfigInput, LoadedConfig } from './defineConfig.ts';
6
+
7
+ // Import a `.atlas/` file if it exists; missing files are optional (atlas ships
8
+ // defaults for vocab), but a present file with a real error propagates.
9
+ const loadModule = async (path: string): Promise<Record<string, unknown> | null> => {
10
+ if (!(await Bun.file(path).exists())) return null;
11
+ return (await import(path)) as Record<string, unknown>;
12
+ };
13
+
14
+ // Pull a named export. A file that is PRESENT but exports none of `names` is a
15
+ // misconfiguration, not an "absent → use default" — throw loudly rather than
16
+ // silently degrading (e.g. an empty concept registry that passes CI against nothing).
17
+ const named = <T>(mod: Record<string, unknown> | null, file: string, ...names: string[]): T | undefined => {
18
+ if (!mod) return undefined;
19
+ for (const n of names) if (mod[n] !== undefined) return mod[n] as T;
20
+ throw new Error(`.atlas/${file} exists but exports none of: ${names.join(', ')}`);
21
+ };
22
+
23
+ // Load the consumer's `.atlas/` config: kinds → concepts → config (no
24
+ // evaluation-order coupling, since partOfFor is a lazy descriptor). atlas ships
25
+ // the kinds defaults; the repo OWNS concepts.ts.
26
+ export const loadConfig = async (root: string): Promise<LoadedConfig> => {
27
+ const dir = resolve(root, '.atlas');
28
+ const [kindsMod, conceptsMod, configMod] = await Promise.all([
29
+ loadModule(resolve(dir, 'kinds.ts')),
30
+ loadModule(resolve(dir, 'concepts.ts')),
31
+ loadModule(resolve(dir, 'config.ts')),
32
+ ]);
33
+
34
+ const kinds = named<readonly string[]>(kindsMod, 'kinds.ts', 'KINDS', 'default') ?? DEFAULT_KINDS;
35
+ const concepts = named<ConceptRegistry>(conceptsMod, 'concepts.ts', 'CONCEPTS', 'default') ?? {};
36
+ const cfg = named<AtlasConfigInput>(configMod, 'config.ts', 'default', 'config') ?? {};
37
+
38
+ // Concept keys are either `class:name` (a layer member) or a bare classless
39
+ // tag (a derived cross-cutting marker like `superadmin`). Reject only a key
40
+ // with an empty class or name side — that's a typo, not a deliberate shape.
41
+ for (const key of Object.keys(concepts)) {
42
+ const colon = key.indexOf(':');
43
+ if (key.length === 0 || colon === 0 || colon === key.length - 1) {
44
+ throw new Error(`.atlas/concepts.ts: malformed concept key '${key}' — use 'class:name' or a bare tag`);
45
+ }
46
+ }
47
+
48
+ return {
49
+ kinds,
50
+ concepts,
51
+ stamp: cfg.stamp ?? [],
52
+ ignore: cfg.ignore ?? [],
53
+ include: cfg.include ?? DEFAULT_INCLUDE,
54
+ references: cfg.references ?? {},
55
+ };
56
+ };
@@ -0,0 +1,84 @@
1
+ import { invert } from '../registry/invert.ts';
2
+ import type { ConceptRegistry } from '../registry/types.ts';
3
+ import { isPartOfFor, type StampRule, type TagValue } from './defineConfig.ts';
4
+ import { type Captures, matchGlob } from './glob.ts';
5
+
6
+ // The materialized @atlas axes a set of stamp rules produce for one file.
7
+ // @uses is deliberately absent — it is never auto-stamped.
8
+ export type ResolvedStamp = {
9
+ kind: string[];
10
+ partOf: string[];
11
+ constructs: string[];
12
+ // partOfFor captures that matched no concept — surfaced by `coverage`, never an error.
13
+ unresolved: { category: string; value: string }[];
14
+ };
15
+
16
+ const interpolate = (template: string, caps: Captures): string | null => {
17
+ let missing = false;
18
+ const out = template.replace(/\$(\d+)/g, (_, n: string) => {
19
+ const v = caps[Number.parseInt(n, 10)];
20
+ if (v === undefined) missing = true;
21
+ return v ?? '';
22
+ });
23
+ return missing ? null : out;
24
+ };
25
+
26
+ const dedupe = (values: string[]): string[] => [...new Set(values)];
27
+
28
+ const toArray = (v: TagValue): (string | TagValue)[] => (Array.isArray(v) ? v : [v]);
29
+
30
+ // Resolve one tag value (literal, list, or partOfFor descriptor) into concrete
31
+ // strings, recording any membership capture that resolves to nothing.
32
+ const resolveTag = (
33
+ value: TagValue,
34
+ caps: Captures,
35
+ registry: ConceptRegistry,
36
+ unresolved: { category: string; value: string }[],
37
+ ): string[] => {
38
+ const out: string[] = [];
39
+ for (const item of toArray(value)) {
40
+ if (isPartOfFor(item)) {
41
+ const segment = interpolate(item.capture, caps);
42
+ if (segment === null) continue;
43
+ const concepts = invert(registry, item.category)[segment];
44
+ if (!concepts || concepts.length === 0) {
45
+ unresolved.push({ category: item.category, value: segment });
46
+ continue;
47
+ }
48
+ out.push(...concepts);
49
+ } else if (typeof item === 'string') {
50
+ const resolved = interpolate(item, caps);
51
+ if (resolved !== null) out.push(resolved);
52
+ }
53
+ }
54
+ return out;
55
+ };
56
+
57
+ // Compose EVERY matching rule's contributions for a file (not first-match-wins).
58
+ export const stampFor = (path: string, rules: StampRule[], registry: ConceptRegistry): ResolvedStamp => {
59
+ const kind: string[] = [];
60
+ const partOf: string[] = [];
61
+ const constructs: string[] = [];
62
+ const unresolved: { category: string; value: string }[] = [];
63
+
64
+ for (const rule of rules) {
65
+ const patterns = Array.isArray(rule.include) ? rule.include : [rule.include];
66
+ let caps: Captures | null = null;
67
+ for (const pattern of patterns) {
68
+ caps = matchGlob(pattern, path);
69
+ if (caps) break;
70
+ }
71
+ if (!caps) continue;
72
+
73
+ if (rule.kind) kind.push(...resolveTag(rule.kind, caps, registry, unresolved));
74
+ if (rule.partOf) partOf.push(...resolveTag(rule.partOf, caps, registry, unresolved));
75
+ if (rule.constructs) constructs.push(...resolveTag(rule.constructs, caps, registry, unresolved));
76
+ }
77
+
78
+ return {
79
+ kind: dedupe(kind),
80
+ partOf: dedupe(partOf).sort(),
81
+ constructs: dedupe(constructs),
82
+ unresolved,
83
+ };
84
+ };
@@ -0,0 +1,19 @@
1
+ // Map over items with a bounded number of in-flight async tasks, preserving
2
+ // input order. atlas uses this for file reads/writes so a repo with thousands
3
+ // of source files can't exhaust the OS file-descriptor limit (EMFILE).
4
+ export const mapLimit = async <T, R>(
5
+ items: T[],
6
+ limit: number,
7
+ fn: (item: T, index: number) => Promise<R>,
8
+ ): Promise<R[]> => {
9
+ const results: R[] = new Array(items.length);
10
+ let next = 0;
11
+ const worker = async (): Promise<void> => {
12
+ for (let i = next++; i < items.length; i = next++) {
13
+ results[i] = await fn(items[i]!, i);
14
+ }
15
+ };
16
+ const workers = Math.max(1, Math.min(limit, items.length));
17
+ await Promise.all(Array.from({ length: workers }, worker));
18
+ return results;
19
+ };
package/src/fs/walk.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { Glob } from 'bun';
2
+ import { matchesAny } from '../config/glob.ts';
3
+
4
+ export const DEFAULT_INCLUDE = ['**/*.ts', '**/*.tsx'];
5
+
6
+ // Never walk into these regardless of consumer config.
7
+ const ALWAYS_IGNORE = ['**/node_modules/**', '**/.git/**', '**/dist/**'];
8
+
9
+ // Repo-relative source files matching `include` and not `ignore`, sorted for
10
+ // deterministic output. Dotfiles/dotdirs (including `.atlas/`) are skipped.
11
+ export const walkFiles = async (
12
+ root: string,
13
+ include: string[] = DEFAULT_INCLUDE,
14
+ ignore: string[] = [],
15
+ ): Promise<string[]> => {
16
+ const glob = new Glob('**/*');
17
+ const files: string[] = [];
18
+ for await (const entry of glob.scan({ cwd: root, onlyFiles: true, dot: false })) {
19
+ const path = entry.replaceAll('\\', '/');
20
+ if (matchesAny(ALWAYS_IGNORE, path)) continue;
21
+ if (!matchesAny(include, path)) continue;
22
+ if (matchesAny(ignore, path)) continue;
23
+ files.push(path);
24
+ }
25
+ return files.sort();
26
+ };
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ // Public API — what a consuming repo's `.atlas/` config imports.
2
+ export { DEFAULT_KINDS, type DefaultKind } from './vocab/kinds.ts';
3
+ export { type ConceptEntry, type ConceptRegistry, conceptClass, conceptClasses } from './registry/types.ts';
4
+ export { invert } from './registry/invert.ts';
5
+ export {
6
+ type AtlasConfigInput,
7
+ defineConfig,
8
+ isPartOfFor,
9
+ type LoadedConfig,
10
+ type PartOfForDescriptor,
11
+ partOfFor,
12
+ type ReferenceResolver,
13
+ type StampRule,
14
+ type TagValue,
15
+ } from './config/defineConfig.ts';
16
+ export { type AtlasAnnotation, parseAtlasBlock, type UsesState } from './parse/parseAtlasBlock.ts';
@@ -0,0 +1,104 @@
1
+ // @uses carries curation state — its absence is meaningful (uncurated) and
2
+ // distinct from an explicit empty (curated-empty), which is distinct from a
3
+ // patcher proposal awaiting human acceptance.
4
+ export type UsesState = 'absent' | 'none' | 'values' | 'proposed';
5
+
6
+ export type AtlasAnnotation = {
7
+ kind: string[];
8
+ partOf: string[];
9
+ uses: string[];
10
+ usesState: UsesState;
11
+ constructs: string[];
12
+ // `@atlas pin` on the opener — exempts the file's derivable axes from
13
+ // `atlas stamp --overwrite` (a hand-curated overload the rules must not clobber).
14
+ pinned: boolean;
15
+ // every parsed axis (name without @, the `@atlas` opener excluded) → values.
16
+ axes: Record<string, string[]>;
17
+ };
18
+
19
+ // Each axis line: optional leading `*`, the @tag, an optional `?` tentative
20
+ // marker, then the comma-separated values.
21
+ const AXIS_LINE = /^\s*\*?\s*@([a-zA-Z][\w]*)(\??)[ \t]*(.*)$/;
22
+ const BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
23
+
24
+ const dedupe = (values: string[]): string[] => [...new Set(values)];
25
+
26
+ const splitValues = (raw: string): string[] =>
27
+ dedupe(
28
+ raw
29
+ .split(',')
30
+ .map((v) => v.trim())
31
+ .filter((v) => v.length > 0),
32
+ );
33
+
34
+ const OPENS_ATLAS = /(^|\n)\s*\*?\s*@atlas\b/;
35
+
36
+ // Locate the first block comment that opens with `@atlas`, returning its text
37
+ // and character span so the patcher can splice a regenerated block in place.
38
+ export const locateAtlasBlock = (source: string): { start: number; end: number; text: string } | null => {
39
+ BLOCK_COMMENT.lastIndex = 0;
40
+ for (let m = BLOCK_COMMENT.exec(source); m !== null; m = BLOCK_COMMENT.exec(source)) {
41
+ if (OPENS_ATLAS.test(m[0])) {
42
+ return { start: m.index, end: m.index + m[0].length, text: m[0] };
43
+ }
44
+ }
45
+ return null;
46
+ };
47
+
48
+ // Parse the first block comment that opens with `@atlas`. Returns null if the
49
+ // file carries no atlas block. Parsing is scoped to that block, so a stray
50
+ // `@uses` in code or prose elsewhere never false-matches.
51
+ export const parseAtlasBlock = (source: string): AtlasAnnotation | null => {
52
+ const located = locateAtlasBlock(source);
53
+ if (!located) return null;
54
+ const atlasBlock = located.text;
55
+
56
+ const axes: Record<string, string[]> = {};
57
+ let pinned = false;
58
+ // @uses is resolved from the whole block, not last-line-wins, so multi-line or
59
+ // mixed `@uses none, x` can't produce a state that disagrees with the values.
60
+ let usesSeen = false;
61
+ let usesNone = false;
62
+ let usesProposed = false;
63
+ const usesValues: string[] = [];
64
+
65
+ // split on \r?\n so CRLF files don't leave a trailing \r polluting values.
66
+ for (const line of atlasBlock.split(/\r?\n/)) {
67
+ const m = AXIS_LINE.exec(line);
68
+ if (!m) continue;
69
+ const [, name, tentative, rest] = m;
70
+ if (name === 'atlas') {
71
+ if (splitValues(rest ?? '').includes('pin')) pinned = true;
72
+ continue;
73
+ }
74
+
75
+ const values = splitValues(rest ?? '');
76
+
77
+ if (name === 'uses') {
78
+ usesSeen = true;
79
+ if (tentative === '?') usesProposed = true;
80
+ if (values.includes('none')) usesNone = true;
81
+ usesValues.push(...values.filter((v) => v !== 'none'));
82
+ continue;
83
+ }
84
+
85
+ axes[name!] = dedupe([...(axes[name!] ?? []), ...values]);
86
+ }
87
+
88
+ // Real values always win over a stray `none`; absent (no line) is distinct
89
+ // from curated-empty (`@uses none` / a bare `@uses`).
90
+ const uses = dedupe(usesValues);
91
+ const usesState: UsesState =
92
+ uses.length > 0 ? (usesProposed ? 'proposed' : 'values') : usesNone || usesSeen ? 'none' : 'absent';
93
+ if (usesSeen) axes.uses = uses;
94
+
95
+ return {
96
+ kind: axes.kind ?? [],
97
+ partOf: axes.partOf ?? [],
98
+ uses,
99
+ usesState,
100
+ constructs: axes.constructs ?? [],
101
+ pinned,
102
+ axes,
103
+ };
104
+ };
@@ -0,0 +1,21 @@
1
+ import type { ConceptRegistry } from './types.ts';
2
+
3
+ // The bidirectionality the whole thing is for: from a forward declaration
4
+ // (concept → values of a field) derive the inverse (value → concept keys).
5
+ //
6
+ // invert(concepts, 'module') → module → concept[] (drives @partOf stamping)
7
+ // invert(concepts, 'docs') → doc → concept[] ("which concepts does AUTH.md cover")
8
+ //
9
+ // Concept-key lists are sorted for deterministic, diff-stable output.
10
+ export const invert = (registry: ConceptRegistry, field: string): Record<string, string[]> => {
11
+ const out: Record<string, string[]> = {};
12
+ for (const [conceptKey, entry] of Object.entries(registry)) {
13
+ const values = entry[field];
14
+ if (!values) continue;
15
+ for (const value of values) {
16
+ (out[value] ??= []).push(conceptKey);
17
+ }
18
+ }
19
+ for (const value of Object.keys(out)) out[value]!.sort();
20
+ return out;
21
+ };
@@ -0,0 +1,21 @@
1
+ // A concept entry is a generic bag of named string lists. atlas hardcodes NO
2
+ // field names — the CONSUMER defines its categories (docs, module, integration,
3
+ // package, …). Reference categories (e.g. docs) drive the doc→concept inversion;
4
+ // constituent categories (e.g. module) fill @partOf during stamping. That
5
+ // distinction lives in the consuming repo's config, never in atlas.
6
+ export type ConceptEntry = Record<string, string[]>;
7
+
8
+ // Keyed `class:name` (e.g. 'feature:tenancy'). The single source of valid concepts.
9
+ // The concept CLASS is just the prefix before ':' — also consumer-defined, derived
10
+ // from these keys, never an enum atlas ships.
11
+ export type ConceptRegistry = Record<string, ConceptEntry>;
12
+
13
+ // `class:name` → its class (the prefix). Returns null for a malformed key.
14
+ export const conceptClass = (key: string): string | null => {
15
+ const idx = key.indexOf(':');
16
+ return idx > 0 ? key.slice(0, idx) : null;
17
+ };
18
+
19
+ // The set of concept classes present in a registry (sorted, unique).
20
+ export const conceptClasses = (registry: ConceptRegistry): string[] =>
21
+ [...new Set(Object.keys(registry).map(conceptClass).filter((c): c is string => c !== null))].sort();
@@ -0,0 +1,109 @@
1
+ import type { CoverageReport, ConceptGraph } from '../commands/report.ts';
2
+
3
+ // JSON embedded in a <script> tag must not contain a literal </script> or a
4
+ // raw '<'; escaping '<' is sufficient and keeps it valid JSON.
5
+ const embed = (data: unknown): string => JSON.stringify(data).replace(/</g, '\\u003c');
6
+
7
+ // A self-contained interactive report: Cytoscape (via CDN) renders the concept
8
+ // graph with compound nodes grouping concepts by class (the grouping view), node
9
+ // colour = block coverage, tap a node to drill into its files, tap to highlight
10
+ // neighbours (traverse). No build step — open the file in a browser.
11
+ export const renderCoverageHtml = (report: CoverageReport, graph: ConceptGraph): string => {
12
+ const data = embed({ report, graph });
13
+ return `<!doctype html>
14
+ <html lang="en">
15
+ <head>
16
+ <meta charset="utf-8" />
17
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
18
+ <title>atlas — coverage & concept graph</title>
19
+ <script src="https://unpkg.com/cytoscape@3.30.2/dist/cytoscape.min.js"></script>
20
+ <style>
21
+ :root { color-scheme: light dark; }
22
+ * { box-sizing: border-box; }
23
+ body { margin: 0; font: 14px/1.4 system-ui, sans-serif; display: flex; height: 100vh; }
24
+ #cy { flex: 1; height: 100%; }
25
+ #panel { width: 340px; border-left: 1px solid rgba(136,136,136,.27); padding: 16px; overflow: auto; }
26
+ #panel h1 { font-size: 15px; margin: 0 0 4px; }
27
+ #panel .sub { opacity: .6; margin: 0 0 16px; font-size: 12px; }
28
+ .bar { height: 8px; border-radius: 4px; background: rgba(136,136,136,.2); overflow: hidden; margin: 6px 0 14px; }
29
+ .bar > i { display: block; height: 100%; background: #2e9e54; }
30
+ table { border-collapse: collapse; width: 100%; font-size: 12px; }
31
+ td { padding: 2px 0; } td.n { text-align: right; font-variant-numeric: tabular-nums; }
32
+ ul.files { list-style: none; padding: 0; margin: 8px 0 0; font-size: 12px; }
33
+ ul.files li { padding: 2px 0; border-bottom: 1px solid rgba(136,136,136,.13); word-break: break-all; }
34
+ .hint { opacity: .55; font-size: 12px; }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <div id="cy"></div>
39
+ <div id="panel"><h1>atlas</h1><p class="sub">click a concept to drill in · click again to traverse</p><p class="hint">Loading…</p></div>
40
+ <script id="atlas-data" type="application/json">${data}</script>
41
+ <script>
42
+ const { report, graph } = JSON.parse(document.getElementById('atlas-data').textContent);
43
+ const byCat = Object.fromEntries(report.categories.map((c) => [c.category, c]));
44
+ const cov = (id) => { const c = byCat[id]; return c && c.files ? (c.files - c.missingBlock) / c.files : 0; };
45
+ // Comma-form hsl() — Cytoscape's colour parser rejects the space-separated
46
+ // CSS Color-4 form and silently falls back to grey. Guard non-finite too.
47
+ const color = (r) => 'hsl(' + (Number.isFinite(r) ? Math.round(r * 120) : 0) + ', 65%, 45%)'; // red→green
48
+
49
+ const classes = [...new Set(graph.nodes.map((n) => n.cls))];
50
+ const elements = [
51
+ ...classes.map((cls) => ({ data: { id: 'cls:' + cls, label: cls }, classes: 'group' })),
52
+ ...graph.nodes.map((n) => ({ data: { id: n.id, parent: 'cls:' + n.cls, label: n.label, cov: cov(n.id) } })),
53
+ ...graph.edges.map((e) => ({ data: { id: e.source + '->' + e.target, source: e.source, target: e.target } })),
54
+ ];
55
+
56
+ const cy = cytoscape({
57
+ container: document.getElementById('cy'),
58
+ elements,
59
+ style: [
60
+ { selector: 'node', style: { 'label': 'data(label)', 'font-size': 11, 'text-valign': 'center', 'color': '#fff',
61
+ 'background-color': (n) => color(n.data('cov')), 'width': 46, 'height': 46 } },
62
+ // group (compound) nodes carry no cov — give them a neutral fill, not the NaN mapper result.
63
+ { selector: 'node.group', style: { 'background-color': '#888888', 'background-opacity': 0.06, 'border-width': 1,
64
+ 'border-color': 'rgba(136,136,136,.4)', 'text-valign': 'top', 'color': '#888888', 'font-size': 12,
65
+ 'shape': 'round-rectangle', 'padding': 18 } },
66
+ { selector: 'edge', style: { 'width': 1.5, 'line-color': 'rgba(136,136,136,.53)', 'target-arrow-color': 'rgba(136,136,136,.53)',
67
+ 'target-arrow-shape': 'triangle', 'curve-style': 'bezier' } },
68
+ { selector: '.faded', style: { 'opacity': 0.12 } },
69
+ { selector: '.hl', style: { 'line-color': '#e8a33d', 'target-arrow-color': '#e8a33d', 'width': 2.5, 'opacity': 1 } },
70
+ ],
71
+ layout: { name: 'cose', animate: false, padding: 40, nodeRepulsion: 24000, idealEdgeLength: 120,
72
+ nodeDimensionsIncludeLabels: true, componentSpacing: 140, gravity: 0.25, fit: true },
73
+ });
74
+ window.cy = cy; // exposed for inspection / testing
75
+
76
+ const panel = document.getElementById('panel');
77
+ const esc = (s) => s.replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
78
+ const row = (k, v) => '<tr><td>' + k + '</td><td class="n">' + v + '</td></tr>';
79
+
80
+ const showTotals = () => {
81
+ const t = report.total;
82
+ panel.innerHTML = '<h1>All files</h1><p class="sub">' + (t.files - t.missingBlock) + '/' + t.files + ' annotated</p>'
83
+ + '<div class="bar"><i style="width:' + Math.round((t.files ? (t.files - t.missingBlock) / t.files : 0) * 100) + '%"></i></div>'
84
+ + '<table>' + row('files', t.files) + row('missing block', t.missingBlock) + row('missing @kind', t.missingKind)
85
+ + row('missing @partOf', t.missingPartOf) + row('@uses uncurated', t.usesUncurated)
86
+ + row('@uses curated-empty', t.usesCuratedEmpty) + row('@uses curated', t.usesCurated) + '</table>'
87
+ + '<p class="hint">Node colour = block coverage (red→green). Boxes group concepts by class.</p>';
88
+ };
89
+ showTotals();
90
+
91
+ cy.on('tap', (e) => { if (e.target === cy) { cy.elements().removeClass('faded hl'); showTotals(); } });
92
+ cy.on('tap', 'node', (e) => {
93
+ const n = e.target;
94
+ if (n.hasClass('group')) return;
95
+ const id = n.id(), c = byCat[id] || { files: 0, missingBlock: 0, missingKind: 0, missingPartOf: 0, usesUncurated: 0, usesCuratedEmpty: 0, usesCurated: 0, filePaths: [] };
96
+ const hood = n.closedNeighborhood();
97
+ cy.elements().addClass('faded'); hood.removeClass('faded'); hood.edgesWith(n).addClass('hl'); n.connectedEdges().addClass('hl');
98
+ panel.innerHTML = '<h1>' + esc(id) + '</h1><p class="sub">' + (c.files - c.missingBlock) + '/' + c.files + ' annotated</p>'
99
+ + '<div class="bar"><i style="width:' + Math.round((c.files ? (c.files - c.missingBlock) / c.files : 0) * 100) + '%"></i></div>'
100
+ + '<table>' + row('files', c.files) + row('missing block', c.missingBlock) + row('missing @kind', c.missingKind)
101
+ + row('missing @partOf', c.missingPartOf) + row('@uses uncurated', c.usesUncurated)
102
+ + row('@uses curated-empty', c.usesCuratedEmpty) + row('@uses curated', c.usesCurated) + '</table>'
103
+ + '<ul class="files">' + (c.filePaths || []).map((f) => '<li>' + esc(f) + '</li>').join('') + '</ul>';
104
+ });
105
+ </script>
106
+ </body>
107
+ </html>
108
+ `;
109
+ };