@inixiative/atlas 0.4.1 → 0.5.1
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 +141 -46
- package/examples/atlas-config/README.md +4 -3
- package/examples/atlas-config/config.ts +10 -2
- package/examples/ci/README.md +3 -3
- package/examples/ci/github-actions-incremental.yml +14 -12
- package/examples/ci/github-actions.yml +9 -8
- package/examples/ci/pre-commit +14 -12
- package/package.json +6 -6
- package/src/analyze.ts +120 -7
- package/src/cli.ts +72 -17
- package/src/commands/check.ts +10 -2
- package/src/commands/coverage.ts +8 -1
- package/src/commands/init.ts +78 -0
- package/src/commands/report.ts +0 -0
- package/src/commands/setup.ts +66 -22
- package/src/commands/stamp.ts +99 -31
- package/src/config/defineConfig.ts +10 -2
- package/src/config/load.ts +58 -2
- package/src/fs/walk.ts +90 -17
- package/src/hook/cachedGraph.ts +4 -1
- package/src/hook/claudeCode.ts +1 -1
- package/src/hook/neighbourhood.ts +3 -3
- package/src/index.ts +21 -1
- package/src/parse/parseAtlasBlock.ts +102 -20
- package/src/stamp/patcher.ts +46 -31
- package/src/syntax/comments.ts +260 -0
package/src/analyze.ts
CHANGED
|
@@ -1,24 +1,137 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
2
|
import type { LoadedConfig } from './config/defineConfig.ts';
|
|
3
|
+
import { matchesAny } from './config/glob.ts';
|
|
3
4
|
import { loadConfig } from './config/load.ts';
|
|
5
|
+
import { type ResolvedStamp, stampFor } from './config/stamp.ts';
|
|
4
6
|
import { mapLimit } from './fs/concurrent.ts';
|
|
5
7
|
import { walkFiles } from './fs/walk.ts';
|
|
6
8
|
import { type AtlasAnnotation, parseAtlasBlock } from './parse/parseAtlasBlock.ts';
|
|
9
|
+
import { type CommentStyle, styleFor } from './syntax/comments.ts';
|
|
7
10
|
|
|
8
|
-
|
|
11
|
+
// `inline`: the file carries its own @atlas block. `path`: the file can't hold a comment (.json,
|
|
12
|
+
// .txt, an image), so its tags are the ones the stamp rules give its path; it has no @uses.
|
|
13
|
+
export type Tagging = 'inline' | 'path';
|
|
14
|
+
export type FileRecord = { path: string; tagging: Tagging; annotation: AtlasAnnotation | null };
|
|
9
15
|
export type Analysis = { root: string; config: LoadedConfig; files: FileRecord[] };
|
|
10
16
|
|
|
17
|
+
// A file atlas considers, and the comment style it is written in (null: tagged by path, with
|
|
18
|
+
// what its rules give it).
|
|
19
|
+
export type ConsideredFile =
|
|
20
|
+
| { path: string; style: CommentStyle }
|
|
21
|
+
| { path: string; style: null; stamp: ResolvedStamp };
|
|
22
|
+
|
|
11
23
|
// Bound open file descriptors so a repo with thousands of files can't hit EMFILE.
|
|
12
24
|
const READ_CONCURRENCY = 64;
|
|
13
25
|
|
|
26
|
+
const hasTags = (s: ResolvedStamp): boolean =>
|
|
27
|
+
s.kind.length > 0 || s.partOf.length > 0 || s.constructs.length > 0;
|
|
28
|
+
|
|
29
|
+
// The files atlas considers: those `include` names, or by default every file in a comment
|
|
30
|
+
// style atlas knows plus every file a stamp rule tags by its path. A path-tagged file carries
|
|
31
|
+
// the rules' result, so it is resolved once.
|
|
32
|
+
export const consideredFiles = async (
|
|
33
|
+
root: string,
|
|
34
|
+
config: LoadedConfig,
|
|
35
|
+
): Promise<ConsideredFile[]> => {
|
|
36
|
+
const { include } = config;
|
|
37
|
+
const resolved = new Map<string, ResolvedStamp>();
|
|
38
|
+
const tagsOf = (path: string): ResolvedStamp => {
|
|
39
|
+
let stamp = resolved.get(path);
|
|
40
|
+
if (!stamp) {
|
|
41
|
+
stamp = stampFor(path, config.stamp, config.concepts);
|
|
42
|
+
resolved.set(path, stamp);
|
|
43
|
+
}
|
|
44
|
+
return stamp;
|
|
45
|
+
};
|
|
46
|
+
const keep = include
|
|
47
|
+
? (path: string) => matchesAny(include, path)
|
|
48
|
+
: (path: string) => styleFor(path, config.comments) !== null || hasTags(tagsOf(path));
|
|
49
|
+
const paths = await walkFiles(root, config.ignore, keep);
|
|
50
|
+
return paths.map((path) => {
|
|
51
|
+
const style = styleFor(path, config.comments);
|
|
52
|
+
return style ? { path, style } : { path, style, stamp: tagsOf(path) };
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// How a file's text is stored, so the stamper writes it back the same way. Bun's decoder drops
|
|
57
|
+
// a byte-order mark, and Windows tools depend on it: PowerShell 5.1 reads a .ps1 without one as
|
|
58
|
+
// ANSI, and writes UTF-16 by default.
|
|
59
|
+
export type TextEncoding = 'utf-8' | 'utf-8-bom' | 'utf-16le' | 'utf-16be';
|
|
60
|
+
|
|
61
|
+
const BOMS: Record<Exclude<TextEncoding, 'utf-8'>, number[]> = {
|
|
62
|
+
'utf-8-bom': [0xef, 0xbb, 0xbf],
|
|
63
|
+
'utf-16le': [0xff, 0xfe],
|
|
64
|
+
'utf-16be': [0xfe, 0xff],
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const nulCount = (bytes: Uint8Array): number => bytes.reduce((n, b) => (b === 0 ? n + 1 : n), 0);
|
|
68
|
+
|
|
69
|
+
const startsWith = (bytes: Uint8Array, prefix: number[]): boolean =>
|
|
70
|
+
prefix.every((byte, i) => bytes[i] === byte);
|
|
71
|
+
|
|
72
|
+
// A file's text and encoding, or null for a file named like source but holding binary (a `.ts`
|
|
73
|
+
// video stream: NUL bytes and not valid UTF-8) or stored as UTF-32 or as UTF-16 without a BOM. A NUL alone isn't binary:
|
|
74
|
+
// valid UTF-8 source may hold one. `exact` is false when the bytes aren't valid in their
|
|
75
|
+
// encoding (a Windows-1252 `.ps1`): the text is still read, with U+FFFD for the bad bytes, so
|
|
76
|
+
// check and graph work, but the stamper must not write it back.
|
|
77
|
+
export const readText = async (
|
|
78
|
+
root: string,
|
|
79
|
+
path: string,
|
|
80
|
+
): Promise<{ text: string; encoding: TextEncoding; exact: boolean } | null> => {
|
|
81
|
+
const bytes = await Bun.file(resolve(root, path)).bytes();
|
|
82
|
+
if (startsWith(bytes, [0xff, 0xfe, 0, 0]) || startsWith(bytes, [0, 0, 0xfe, 0xff])) return null;
|
|
83
|
+
let encoding: TextEncoding = startsWith(bytes, BOMS['utf-8-bom']) ? 'utf-8-bom' : 'utf-8';
|
|
84
|
+
for (const utf16 of ['utf-16le', 'utf-16be'] as const)
|
|
85
|
+
if (startsWith(bytes, BOMS[utf16])) encoding = utf16;
|
|
86
|
+
// UTF-16 without a byte-order mark: every other byte of ASCII-range text is NUL, which is
|
|
87
|
+
// valid UTF-8, so it would be stamped as UTF-8 and mixed. Text holds at most a stray NUL.
|
|
88
|
+
if (encoding === 'utf-8' && nulCount(bytes) * 10 > bytes.length) return null;
|
|
89
|
+
const label = encoding === 'utf-8-bom' ? 'utf-8' : encoding;
|
|
90
|
+
try {
|
|
91
|
+
return { text: new TextDecoder(label, { fatal: true }).decode(bytes), encoding, exact: true };
|
|
92
|
+
} catch {
|
|
93
|
+
if (label === 'utf-8' && bytes.includes(0)) return null;
|
|
94
|
+
return { text: new TextDecoder(label).decode(bytes), encoding, exact: false };
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
// The bytes to write for `text` in `encoding`, byte-order mark included.
|
|
99
|
+
export const encodeText = (text: string, encoding: TextEncoding): Uint8Array => {
|
|
100
|
+
if (encoding === 'utf-8') return new TextEncoder().encode(text);
|
|
101
|
+
if (encoding === 'utf-8-bom')
|
|
102
|
+
return new Uint8Array([...BOMS[encoding], ...new TextEncoder().encode(text)]);
|
|
103
|
+
const out = new Uint8Array(2 + text.length * 2);
|
|
104
|
+
out.set(BOMS[encoding]);
|
|
105
|
+
for (let i = 0; i < text.length; i++) {
|
|
106
|
+
const unit = text.charCodeAt(i);
|
|
107
|
+
const [first, second] =
|
|
108
|
+
encoding === 'utf-16le' ? [unit & 0xff, unit >> 8] : [unit >> 8, unit & 0xff];
|
|
109
|
+
out[2 + i * 2] = first;
|
|
110
|
+
out[3 + i * 2] = second;
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// A path-tagged file's annotation: what the rules say, or null when they say nothing.
|
|
116
|
+
const pathAnnotation = ({ kind, partOf, constructs }: ResolvedStamp): AtlasAnnotation | null => {
|
|
117
|
+
if (kind.length + partOf.length + constructs.length === 0) return null;
|
|
118
|
+
const axes: Record<string, string[]> = { kind, partOf };
|
|
119
|
+
if (constructs.length) axes.constructs = constructs;
|
|
120
|
+
return { kind, partOf, constructs, uses: [], usesState: 'absent', pinned: false, axes };
|
|
121
|
+
};
|
|
122
|
+
|
|
14
123
|
// One pass: load the consumer's .atlas/ config, walk the considered files, and
|
|
15
124
|
// parse each into its @atlas annotation (or null). Every command consumes this.
|
|
16
125
|
export const analyze = async (root: string): Promise<Analysis> => {
|
|
17
126
|
const config = await loadConfig(root);
|
|
18
|
-
const
|
|
19
|
-
const files
|
|
20
|
-
path
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
127
|
+
const considered = await consideredFiles(root, config);
|
|
128
|
+
const files = await mapLimit(considered, READ_CONCURRENCY, async (file) => {
|
|
129
|
+
const { path } = file;
|
|
130
|
+
if (file.style === null)
|
|
131
|
+
return { path, tagging: 'path' as const, annotation: pathAnnotation(file.stamp) };
|
|
132
|
+
const read = await readText(root, path);
|
|
133
|
+
if (read === null) return null;
|
|
134
|
+
return { path, tagging: 'inline' as const, annotation: parseAtlasBlock(read.text, file.style) };
|
|
135
|
+
});
|
|
136
|
+
return { root, config, files: files.filter((f): f is FileRecord => f !== null) };
|
|
24
137
|
};
|
package/src/cli.ts
CHANGED
|
@@ -4,29 +4,34 @@ import { runCheck } from './commands/check.ts';
|
|
|
4
4
|
import { coverage, evaluateCoverageGate, readBaseline } from './commands/coverage.ts';
|
|
5
5
|
import { generate } from './commands/generate.ts';
|
|
6
6
|
import { graph } from './commands/graph.ts';
|
|
7
|
+
import { init } from './commands/init.ts';
|
|
7
8
|
import { flagsToRule, type QueryRule, queryFiles, toQueryRecords } from './commands/query.ts';
|
|
8
9
|
import { buildConceptGraph, buildCoverageReport } from './commands/report.ts';
|
|
9
10
|
import { CLAUDE_SETTINGS, type SetupReport, setupClaudeHooks } from './commands/setup.ts';
|
|
10
|
-
import { inScope, runStamp } from './commands/stamp.ts';
|
|
11
|
+
import { inScope, resolveTargets, runStamp } from './commands/stamp.ts';
|
|
11
12
|
import { HOOK_EVENTS, type HookEvent, runClaudeCodeHook } from './hook/claudeCode.ts';
|
|
12
13
|
import { renderCoverageHtml } from './render/html.ts';
|
|
13
14
|
import { renderCoverageMarkdown } from './render/markdown.ts';
|
|
15
|
+
import type { StampSkip } from './stamp/patcher.ts';
|
|
14
16
|
|
|
15
17
|
const HELP = `atlas — the map of the codebase
|
|
16
18
|
|
|
17
|
-
Usage: atlas <command> [
|
|
19
|
+
Usage: atlas <command> [targets…] [flags]
|
|
18
20
|
|
|
19
21
|
Commands:
|
|
22
|
+
init start a .atlas/ here: config.ts with an include list for the languages
|
|
23
|
+
found, kinds.ts, and an empty concepts.ts
|
|
20
24
|
graph reverse indexes: concept → files, file → concepts, doc → concepts
|
|
21
|
-
check [
|
|
22
|
-
|
|
25
|
+
check [targets…] presence + vocab + reference + thesaurus existence (the CI command);
|
|
26
|
+
targets (files or folders; . is all) scope it and skip the
|
|
27
|
+
registry-wide reference checks
|
|
23
28
|
coverage unannotated files; @uses curation buckets; unresolved memberships
|
|
24
29
|
gate with --min <pct> and/or --ratchet (vs a committed baseline)
|
|
25
30
|
generate write MAP.md from the annotated tree
|
|
26
31
|
report coverage gaps + concept graph → COVERAGE.md (Mermaid) and atlas.html (Cytoscape)
|
|
27
32
|
query [predicate] find files by axis — flags (--kind/--partOf/--uses/--path) and/or a
|
|
28
33
|
json-rules predicate (the same AST used for authz/filtering)
|
|
29
|
-
stamp [
|
|
34
|
+
stamp [targets…] write/refresh @atlas blocks from the config rules (the patcher)
|
|
30
35
|
hook read|grep Claude Code PostToolUse hook: reads the hook JSON on stdin and prints
|
|
31
36
|
the concept neighbourhood (read) or matching concepts (grep) as
|
|
32
37
|
additionalContext; silent on any failure
|
|
@@ -35,7 +40,7 @@ Commands:
|
|
|
35
40
|
|
|
36
41
|
Flags:
|
|
37
42
|
--root <dir> repo root to operate on (default: cwd)
|
|
38
|
-
--json machine-readable output (graph/check/coverage/stamp)
|
|
43
|
+
--json machine-readable output (init/graph/check/coverage/stamp/query/report/setup)
|
|
39
44
|
--stdout print to stdout instead of writing a file (generate, report)
|
|
40
45
|
--out <dir> output directory for report files (report; default: root)
|
|
41
46
|
--md / --html emit only one report format (report; default: both)
|
|
@@ -53,6 +58,14 @@ Flags:
|
|
|
53
58
|
|
|
54
59
|
type Flags = Record<string, string | boolean>;
|
|
55
60
|
|
|
61
|
+
const SKIP_REASONS: Record<StampSkip, string> = {
|
|
62
|
+
unreadable:
|
|
63
|
+
'has a comment naming @atlas that is not a readable block (collapsed onto one line, or an example in a comment)',
|
|
64
|
+
'no-place': 'no place for a block (a PHP file must open with <?php)',
|
|
65
|
+
encoding:
|
|
66
|
+
'not valid in its encoding (e.g. Windows-1252); stamping would corrupt it — convert it to UTF-8 first',
|
|
67
|
+
};
|
|
68
|
+
|
|
56
69
|
// Flags that consume the next token as a value; everything else is boolean.
|
|
57
70
|
const VALUE_FLAGS = new Set(['root', 'min', 'baseline', 'out', 'kind', 'partOf', 'uses', 'path']);
|
|
58
71
|
|
|
@@ -127,15 +140,24 @@ type Ctx = {
|
|
|
127
140
|
env: CliEnv;
|
|
128
141
|
};
|
|
129
142
|
|
|
143
|
+
// "add atlas hook read, grep; refresh atlas hook grep", in the tense of the outcome
|
|
144
|
+
const setupChanges = (r: SetupReport, done: boolean): string =>
|
|
145
|
+
[
|
|
146
|
+
...(r.added.length ? [`${done ? 'added' : 'add'} atlas hook ${r.added.join(', ')}`] : []),
|
|
147
|
+
...(r.refreshed.length
|
|
148
|
+
? [`${done ? 'refreshed' : 'refresh'} atlas hook ${r.refreshed.join(', ')}`]
|
|
149
|
+
: []),
|
|
150
|
+
].join('; ');
|
|
151
|
+
|
|
130
152
|
const logSetup = (log: (s?: string) => void, r: SetupReport, offered: boolean): void => {
|
|
131
153
|
if (r.status === 'unchanged') log(`✓ ${r.settings} already has the atlas hooks`);
|
|
132
154
|
else if (r.status === 'dry-run')
|
|
133
155
|
log(
|
|
134
156
|
offered
|
|
135
157
|
? `skipped: ${r.settings} unchanged`
|
|
136
|
-
: `would
|
|
158
|
+
: `would ${setupChanges(r, false)} in ${r.settings} — re-run with --yes to write`,
|
|
137
159
|
);
|
|
138
|
-
else log(`✓ ${r.status} ${r.settings}:
|
|
160
|
+
else log(`✓ ${r.status} ${r.settings}: ${setupChanges(r, true)}`);
|
|
139
161
|
for (const n of r.notes) log(` note: ${n}`);
|
|
140
162
|
};
|
|
141
163
|
|
|
@@ -161,16 +183,33 @@ const dispatch = async (
|
|
|
161
183
|
return done(0);
|
|
162
184
|
}
|
|
163
185
|
|
|
186
|
+
case 'init': {
|
|
187
|
+
const report = await init(root);
|
|
188
|
+
if (json) log(JSON.stringify(report, null, 2));
|
|
189
|
+
else {
|
|
190
|
+
log(`✓ wrote ${report.written.join(', ')}`);
|
|
191
|
+
log(' languages found:');
|
|
192
|
+
for (const l of report.languages)
|
|
193
|
+
log(` ${l.entry} — ${l.files} file(s), ${l.style} comments`);
|
|
194
|
+
log('next:');
|
|
195
|
+
log(' 1. add concepts to .atlas/concepts.ts and stamp rules to .atlas/config.ts');
|
|
196
|
+
log(' 2. bunx @inixiative/atlas stamp --write (writes @atlas blocks from the rules)');
|
|
197
|
+
log(' 3. bunx @inixiative/atlas check (every file tagged, vocab valid)');
|
|
198
|
+
log(' 4. bunx @inixiative/atlas setup --yes (Claude Code read/grep hooks)');
|
|
199
|
+
}
|
|
200
|
+
return done(0);
|
|
201
|
+
}
|
|
202
|
+
|
|
164
203
|
case 'setup': {
|
|
165
|
-
const plan = setupClaudeHooks(root, { write: false });
|
|
204
|
+
const plan = setupClaudeHooks(root, { write: false, version: await version() });
|
|
166
205
|
let report = plan;
|
|
167
206
|
let offered = false;
|
|
168
207
|
if (plan.status === 'dry-run') {
|
|
169
|
-
const question = `Add atlas's PostToolUse hooks (${plan.added.join(', ')})
|
|
208
|
+
const question = `Add or refresh atlas's PostToolUse hooks (${[...plan.added, ...plan.refreshed].join(', ')}) in ${CLAUDE_SETTINGS}?`;
|
|
170
209
|
const confirm = flags.yes === true ? undefined : env.confirm;
|
|
171
210
|
offered = confirm !== undefined;
|
|
172
211
|
const accepted = flags.yes === true || (confirm !== undefined && (await confirm(question)));
|
|
173
|
-
if (accepted) report = setupClaudeHooks(root, { write: true });
|
|
212
|
+
if (accepted) report = setupClaudeHooks(root, { write: true, version: await version() });
|
|
174
213
|
}
|
|
175
214
|
if (json) log(JSON.stringify(report, null, 2));
|
|
176
215
|
else logSetup(log, report, offered);
|
|
@@ -178,13 +217,13 @@ const dispatch = async (
|
|
|
178
217
|
}
|
|
179
218
|
|
|
180
219
|
case 'check': {
|
|
181
|
-
const
|
|
220
|
+
const targets = resolveTargets(root, positionals.slice(1));
|
|
182
221
|
const warnOnly = flags['warn-only'] === true;
|
|
183
222
|
const full = await analyze(root);
|
|
184
|
-
const scoped =
|
|
185
|
-
? { ...full, files: full.files.filter((f) => inScope(f.path,
|
|
223
|
+
const scoped = targets.length
|
|
224
|
+
? { ...full, files: full.files.filter((f) => inScope(f.path, targets)) }
|
|
186
225
|
: full;
|
|
187
|
-
const result = await runCheck(scoped, { references:
|
|
226
|
+
const result = await runCheck(scoped, { references: targets.length === 0 });
|
|
188
227
|
|
|
189
228
|
if (json) log(JSON.stringify({ ...result, warnOnly }, null, 2));
|
|
190
229
|
else if (result.ok) log('✓ atlas check passed');
|
|
@@ -242,6 +281,7 @@ const dispatch = async (
|
|
|
242
281
|
log(
|
|
243
282
|
` unannotated (${c.unannotated.length}):\n${c.unannotated.map((f) => ` ${f}`).join('\n')}`,
|
|
244
283
|
);
|
|
284
|
+
if (c.pathTagged.length) log(` tagged by path (no comment style): ${c.pathTagged.length}`);
|
|
245
285
|
log(
|
|
246
286
|
` @uses — curated ${c.uses.curated.length}, curated-empty ${c.uses.curatedEmpty.length}, proposed ${c.uses.proposed.length}, uncurated ${c.uses.uncurated.length}`,
|
|
247
287
|
);
|
|
@@ -354,10 +394,18 @@ const dispatch = async (
|
|
|
354
394
|
case 'stamp': {
|
|
355
395
|
const mode = flags.overwrite === true ? 'overwrite' : 'additive';
|
|
356
396
|
const write = flags.write === true;
|
|
357
|
-
const { changes, unresolved } = await runStamp(root, {
|
|
397
|
+
const { changes, unresolved, skipped } = await runStamp(root, {
|
|
398
|
+
mode,
|
|
399
|
+
targets: resolveTargets(root, positionals.slice(1)),
|
|
400
|
+
write,
|
|
401
|
+
});
|
|
358
402
|
if (json) {
|
|
359
403
|
log(
|
|
360
|
-
JSON.stringify(
|
|
404
|
+
JSON.stringify(
|
|
405
|
+
{ changes: changes.map((c) => ({ path: c.path })), unresolved, skipped },
|
|
406
|
+
null,
|
|
407
|
+
2,
|
|
408
|
+
),
|
|
361
409
|
);
|
|
362
410
|
} else {
|
|
363
411
|
if (!changes.length) log('✓ nothing to stamp — already up to date');
|
|
@@ -375,6 +423,10 @@ const dispatch = async (
|
|
|
375
423
|
);
|
|
376
424
|
for (const u of unresolved) log(` ${u.file}: ${u.category}:${u.value}`);
|
|
377
425
|
}
|
|
426
|
+
if (skipped.length) {
|
|
427
|
+
log(`⚠ ${skipped.length} file(s) not stamped:`);
|
|
428
|
+
for (const s of skipped) log(` ${s.file}: ${SKIP_REASONS[s.reason]}`);
|
|
429
|
+
}
|
|
378
430
|
}
|
|
379
431
|
return done(0);
|
|
380
432
|
}
|
|
@@ -385,3 +437,6 @@ const dispatch = async (
|
|
|
385
437
|
return done(1);
|
|
386
438
|
}
|
|
387
439
|
};
|
|
440
|
+
|
|
441
|
+
// `bun src/cli.ts …` runs the CLI as well; the package's bin is bin/atlas.ts.
|
|
442
|
+
if (import.meta.main) await import('../bin/atlas.ts');
|
package/src/commands/check.ts
CHANGED
|
@@ -16,11 +16,19 @@ export type Problem = {
|
|
|
16
16
|
|
|
17
17
|
export type CheckResult = { ok: boolean; problems: Problem[] };
|
|
18
18
|
|
|
19
|
-
// presence — every considered (non-ignored) file carries an @atlas block
|
|
19
|
+
// presence — every considered (non-ignored) file carries an @atlas block, or, when it can't hold
|
|
20
|
+
// a comment, a stamp rule tags its path.
|
|
20
21
|
export const checkPresence = (a: Analysis): Problem[] =>
|
|
21
22
|
a.files
|
|
22
23
|
.filter((f) => f.annotation === null)
|
|
23
|
-
.map((f) => ({
|
|
24
|
+
.map((f) => ({
|
|
25
|
+
kind: 'presence' as const,
|
|
26
|
+
file: f.path,
|
|
27
|
+
message:
|
|
28
|
+
f.tagging === 'path'
|
|
29
|
+
? 'no comment style for this file and no stamp rule tags its path'
|
|
30
|
+
: 'missing @atlas block',
|
|
31
|
+
}));
|
|
24
32
|
|
|
25
33
|
// vocab existence — @kind is in the vocab; @partOf/@uses name a concept that
|
|
26
34
|
// EXISTS in the registry (not: is the file really part of it).
|
package/src/commands/coverage.ts
CHANGED
|
@@ -14,6 +14,9 @@ export type Coverage = {
|
|
|
14
14
|
proposed: string[]; // tentative @uses? — patcher proposed, awaiting acceptance
|
|
15
15
|
curated: string[]; // real @uses values
|
|
16
16
|
};
|
|
17
|
+
// files with no comment style, tagged by their path; they can't carry @uses, so they sit
|
|
18
|
+
// outside the @uses buckets.
|
|
19
|
+
pathTagged: string[];
|
|
17
20
|
// membership captures (partOfFor) that matched no concept — fillable signal, not an error.
|
|
18
21
|
unresolved: { file: string; category: string; value: string }[];
|
|
19
22
|
};
|
|
@@ -69,10 +72,13 @@ export const coverage = (a: Analysis): Coverage => {
|
|
|
69
72
|
curated: [] as string[],
|
|
70
73
|
};
|
|
71
74
|
const unresolved: Coverage['unresolved'] = [];
|
|
75
|
+
const pathTagged: string[] = [];
|
|
72
76
|
|
|
73
|
-
for (const { path, annotation } of a.files) {
|
|
77
|
+
for (const { path, tagging, annotation } of a.files) {
|
|
74
78
|
if (!annotation) {
|
|
75
79
|
unannotated.push(path);
|
|
80
|
+
} else if (tagging === 'path') {
|
|
81
|
+
pathTagged.push(path);
|
|
76
82
|
} else {
|
|
77
83
|
const bucket =
|
|
78
84
|
annotation.usesState === 'absent'
|
|
@@ -94,6 +100,7 @@ export const coverage = (a: Analysis): Coverage => {
|
|
|
94
100
|
annotated: a.files.length - unannotated.length,
|
|
95
101
|
unannotated,
|
|
96
102
|
uses,
|
|
103
|
+
pathTagged,
|
|
97
104
|
unresolved,
|
|
98
105
|
};
|
|
99
106
|
};
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { walkFiles } from '../fs/walk.ts';
|
|
4
|
+
import { type CommentStyleName, entryFor } from '../syntax/comments.ts';
|
|
5
|
+
|
|
6
|
+
// `atlas init` writes a starter `.atlas/`: config.ts with an include list for the languages the
|
|
7
|
+
// repo has, kinds.ts from the example, and concepts.ts with the example's guidance and no
|
|
8
|
+
// concepts. Proposing the concept registry is a person's (or Foundry setup's agent's) job.
|
|
9
|
+
|
|
10
|
+
const EXAMPLE = resolve(import.meta.dir, '../../examples/atlas-config');
|
|
11
|
+
|
|
12
|
+
export type Language = { entry: string; style: CommentStyleName; files: number };
|
|
13
|
+
export type InitReport = { dir: string; languages: Language[]; written: string[] };
|
|
14
|
+
|
|
15
|
+
// The table entries (`.py`, `Dockerfile`) the repo's files use, most files first, spelled as the
|
|
16
|
+
// files spell them: matching ignores case but the include globs don't, so `analysis.R` must
|
|
17
|
+
// yield `**/*.R`, not the table's `.r`.
|
|
18
|
+
export const detectLanguages = async (root: string): Promise<Language[]> => {
|
|
19
|
+
const counts = new Map<string, Language>();
|
|
20
|
+
for (const path of await walkFiles(root, [], () => true)) {
|
|
21
|
+
const match = entryFor(path);
|
|
22
|
+
if (!match) continue;
|
|
23
|
+
const name = path.slice(path.lastIndexOf('/') + 1);
|
|
24
|
+
const entry = match.entry.startsWith('.') ? name.slice(-match.entry.length) : name;
|
|
25
|
+
const seen = counts.get(entry) ?? { entry, style: match.style, files: 0 };
|
|
26
|
+
seen.files += 1;
|
|
27
|
+
counts.set(entry, seen);
|
|
28
|
+
}
|
|
29
|
+
return [...counts.values()].sort((a, b) => b.files - a.files || a.entry.localeCompare(b.entry));
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const globFor = (entry: string): string => (entry.startsWith('.') ? `**/*${entry}` : `**/${entry}`);
|
|
33
|
+
|
|
34
|
+
const configSource = (languages: Language[]): string => {
|
|
35
|
+
const include = languages
|
|
36
|
+
.map((l) => ` '${globFor(l.entry)}', // ${l.files} file(s), ${l.style} comments`)
|
|
37
|
+
.join('\n');
|
|
38
|
+
return `import { defineConfig } from '@inixiative/atlas/config';
|
|
39
|
+
|
|
40
|
+
// Written by \`atlas init\` from the languages in this repo. Narrow \`include\` to what you want
|
|
41
|
+
// mapped, list tests and generated files under \`ignore\`, and add stamp rules (path → @kind,
|
|
42
|
+
// @partOf) as in @inixiative/atlas examples/atlas-config/config.ts. A file with no comment style
|
|
43
|
+
// (.json, .txt) is tagged by the stamp rules that match its path; add its glob to \`include\`.
|
|
44
|
+
export default defineConfig({
|
|
45
|
+
include: [
|
|
46
|
+
${include}
|
|
47
|
+
],
|
|
48
|
+
ignore: [],
|
|
49
|
+
stamp: [],
|
|
50
|
+
});
|
|
51
|
+
`;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// The example's guidance, with an empty registry.
|
|
55
|
+
const conceptsSource = async (): Promise<string> => {
|
|
56
|
+
const example = await Bun.file(join(EXAMPLE, 'concepts.ts')).text();
|
|
57
|
+
const head = example.slice(0, example.indexOf('export const CONCEPTS'));
|
|
58
|
+
return `${head}// Starter written by \`atlas init\`: no concepts yet.\nexport const CONCEPTS: ConceptRegistry = {};\n`;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export const init = async (root: string): Promise<InitReport> => {
|
|
62
|
+
const dir = join(root, '.atlas');
|
|
63
|
+
if (existsSync(dir)) throw new Error(`${dir} already exists; atlas init only starts a new one`);
|
|
64
|
+
const languages = await detectLanguages(root);
|
|
65
|
+
if (languages.length === 0)
|
|
66
|
+
throw new Error(
|
|
67
|
+
'no files in a comment style atlas knows; write .atlas/config.ts by hand and add your file types under `comments`',
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const files: Record<string, string> = {
|
|
71
|
+
'config.ts': configSource(languages),
|
|
72
|
+
'kinds.ts': await Bun.file(join(EXAMPLE, 'kinds.ts')).text(),
|
|
73
|
+
'concepts.ts': await conceptsSource(),
|
|
74
|
+
};
|
|
75
|
+
mkdirSync(dir, { recursive: true });
|
|
76
|
+
for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text, 'utf8');
|
|
77
|
+
return { dir: '.atlas', languages, written: Object.keys(files).map((n) => `.atlas/${n}`) };
|
|
78
|
+
};
|
package/src/commands/report.ts
CHANGED
|
Binary file
|
package/src/commands/setup.ts
CHANGED
|
@@ -13,47 +13,86 @@ const HOOKS: Record<HookEvent, { matcher: string; statusMessage: string }> = {
|
|
|
13
13
|
grep: { matcher: 'Grep', statusMessage: 'atlas: concepts matching this pattern' },
|
|
14
14
|
};
|
|
15
15
|
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
// working when the session's cwd moves into a subdirectory
|
|
19
|
-
// committed settings.json silent for a teammate who hasn't run `bun install` yet.
|
|
16
|
+
// How the hook runs atlas. A repo that depends on @inixiative/atlas runs its own install (not
|
|
17
|
+
// `bunx atlas`, which would fetch an unrelated npm `atlas` package); $CLAUDE_PROJECT_DIR keeps it
|
|
18
|
+
// working when the session's cwd moves into a subdirectory, and the existence guard keeps a
|
|
19
|
+
// committed settings.json silent for a teammate who hasn't run `bun install` yet. Any other repo
|
|
20
|
+
// (Python, Go, docs) has no node_modules, so the hook runs the scoped package through bunx,
|
|
21
|
+
// pinned to the version that wrote it.
|
|
22
|
+
export type HookRunner = { installed: true } | { installed: false; version?: string };
|
|
23
|
+
|
|
20
24
|
const ATLAS_BIN = '"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas"';
|
|
21
|
-
export const hookCommandFor = (
|
|
22
|
-
|
|
25
|
+
export const hookCommandFor = (
|
|
26
|
+
event: HookEvent,
|
|
27
|
+
runner: HookRunner = { installed: true },
|
|
28
|
+
): string => {
|
|
29
|
+
if (runner.installed) return `[ -e ${ATLAS_BIN} ] && bun ${ATLAS_BIN} hook ${event} || true`;
|
|
30
|
+
const pkg = runner.version ? `@inixiative/atlas@${runner.version}` : '@inixiative/atlas';
|
|
31
|
+
return `cd "$CLAUDE_PROJECT_DIR" && bunx ${pkg} hook ${event} || true`;
|
|
32
|
+
};
|
|
23
33
|
|
|
24
|
-
|
|
34
|
+
// A repo installs atlas when its package.json depends on it.
|
|
35
|
+
export const runnerFor = (root: string, version?: string): HookRunner => {
|
|
36
|
+
const pkg = join(root, 'package.json');
|
|
37
|
+
if (existsSync(pkg) && /"@inixiative\/atlas"\s*:/.test(readFileSync(pkg, 'utf8')))
|
|
38
|
+
return { installed: true };
|
|
39
|
+
return { installed: false, version };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const hookCommand = (event: HookEvent, runner?: HookRunner): HookCommand => ({
|
|
25
43
|
type: 'command',
|
|
26
|
-
command: hookCommandFor(event),
|
|
44
|
+
command: hookCommandFor(event, runner),
|
|
27
45
|
timeout: 20,
|
|
28
46
|
statusMessage: HOOKS[event].statusMessage,
|
|
29
47
|
});
|
|
30
48
|
|
|
31
|
-
export const atlasHookEntry = (event: HookEvent): MatcherGroup => ({
|
|
49
|
+
export const atlasHookEntry = (event: HookEvent, runner?: HookRunner): MatcherGroup => ({
|
|
32
50
|
matcher: HOOKS[event].matcher,
|
|
33
|
-
hooks: [hookCommand(event)],
|
|
51
|
+
hooks: [hookCommand(event, runner)],
|
|
34
52
|
});
|
|
35
53
|
|
|
36
|
-
|
|
54
|
+
// `atlas hook read`, `atlas.ts" hook read`, `@inixiative/atlas@0.5.0 hook read`.
|
|
55
|
+
const ATLAS_HOOK = (event: HookEvent) =>
|
|
56
|
+
new RegExp(`\\batlas(\\.ts)?(@[\\w.-]+)?"?\\s+hook\\s+${event}\\b`);
|
|
37
57
|
|
|
38
58
|
const hasAtlasHook = (groups: MatcherGroup[], event: HookEvent): boolean =>
|
|
39
59
|
groups.some((g) => (g.hooks ?? []).some((h) => ATLAS_HOOK(event).test(h.command ?? '')));
|
|
40
60
|
|
|
61
|
+
// A command in one of the two forms setup writes. Only these are refreshed; a hand-written
|
|
62
|
+
// atlas hook is the repo's own and is left alone.
|
|
63
|
+
const WRITTEN_BY_SETUP = (event: HookEvent) =>
|
|
64
|
+
new RegExp(
|
|
65
|
+
`^(?:\\[ -e "\\$CLAUDE_PROJECT_DIR/node_modules/\\.bin/atlas" \\] && bun "\\$CLAUDE_PROJECT_DIR/node_modules/\\.bin/atlas"|cd "\\$CLAUDE_PROJECT_DIR" && bunx @inixiative/atlas(?:@[\\w.-]+)?) hook ${event} (?:2>/dev/null )?\\|\\| true$`,
|
|
66
|
+
);
|
|
67
|
+
|
|
41
68
|
// Merge the two PostToolUse entries into existing settings without touching anything
|
|
42
69
|
// else: an existing group for the same matcher gains the command; otherwise a new group
|
|
43
|
-
// is appended. An entry already present
|
|
44
|
-
|
|
70
|
+
// is appended. An atlas entry already present is left alone, unless setup wrote it and it
|
|
71
|
+
// no longer matches this repo (a pinned version after an upgrade, bunx after atlas was
|
|
72
|
+
// installed): that one is refreshed in place.
|
|
73
|
+
export const mergeAtlasHooks = (
|
|
74
|
+
settings: ClaudeSettings,
|
|
75
|
+
runner?: HookRunner,
|
|
76
|
+
): { added: HookEvent[]; refreshed: HookEvent[] } => {
|
|
45
77
|
settings.hooks ??= {};
|
|
46
78
|
settings.hooks.PostToolUse ??= [];
|
|
47
79
|
const groups = settings.hooks.PostToolUse;
|
|
48
80
|
const added: HookEvent[] = [];
|
|
81
|
+
const refreshed: HookEvent[] = [];
|
|
49
82
|
for (const event of HOOK_EVENTS) {
|
|
83
|
+
const want = hookCommandFor(event, runner);
|
|
84
|
+
const stale = groups
|
|
85
|
+
.flatMap((g) => g.hooks ?? [])
|
|
86
|
+
.filter((h) => h.command !== want && WRITTEN_BY_SETUP(event).test(h.command ?? ''));
|
|
87
|
+
for (const hook of stale) hook.command = want;
|
|
88
|
+
if (stale.length > 0) refreshed.push(event);
|
|
50
89
|
if (hasAtlasHook(groups, event)) continue;
|
|
51
90
|
const same = groups.find((g) => g.matcher === HOOKS[event].matcher)?.hooks;
|
|
52
|
-
if (Array.isArray(same)) same.push(hookCommand(event));
|
|
53
|
-
else groups.push(atlasHookEntry(event));
|
|
91
|
+
if (Array.isArray(same)) same.push(hookCommand(event, runner));
|
|
92
|
+
else groups.push(atlasHookEntry(event, runner));
|
|
54
93
|
added.push(event);
|
|
55
94
|
}
|
|
56
|
-
return { added };
|
|
95
|
+
return { added, refreshed };
|
|
57
96
|
};
|
|
58
97
|
|
|
59
98
|
// The hand-copied predecessors mix gloss and atlas; once atlas's own hook is in, their
|
|
@@ -93,12 +132,16 @@ const settingsShapeError = (settings: ClaudeSettings): string | undefined => {
|
|
|
93
132
|
export type SetupReport = {
|
|
94
133
|
settings: string;
|
|
95
134
|
status: 'created' | 'updated' | 'unchanged' | 'dry-run';
|
|
96
|
-
// with status dry-run: the entries a write would add
|
|
135
|
+
// with status dry-run: the entries a write would add, and those it would refresh
|
|
97
136
|
added: HookEvent[];
|
|
137
|
+
refreshed: HookEvent[];
|
|
98
138
|
notes: string[];
|
|
99
139
|
};
|
|
100
140
|
|
|
101
|
-
export const setupClaudeHooks = (
|
|
141
|
+
export const setupClaudeHooks = (
|
|
142
|
+
root: string,
|
|
143
|
+
options: { write: boolean; version?: string },
|
|
144
|
+
): SetupReport => {
|
|
102
145
|
const path = join(root, CLAUDE_SETTINGS);
|
|
103
146
|
const exists = existsSync(path);
|
|
104
147
|
const text = exists ? readFileSync(path, 'utf8') : '';
|
|
@@ -123,11 +166,12 @@ export const setupClaudeHooks = (root: string, options: { write: boolean }): Set
|
|
|
123
166
|
for (const legacy of legacyHooks(settings))
|
|
124
167
|
notes.push(`legacy hook still configured: ${legacy} (its atlas half duplicates atlas hook)`);
|
|
125
168
|
|
|
126
|
-
const { added } = mergeAtlasHooks(settings);
|
|
127
|
-
|
|
128
|
-
if (
|
|
169
|
+
const { added, refreshed } = mergeAtlasHooks(settings, runnerFor(root, options.version));
|
|
170
|
+
const report = { settings: CLAUDE_SETTINGS, added, refreshed, notes };
|
|
171
|
+
if (added.length + refreshed.length === 0) return { ...report, status: 'unchanged' };
|
|
172
|
+
if (!options.write) return { ...report, status: 'dry-run' };
|
|
129
173
|
|
|
130
174
|
mkdirSync(join(root, '.claude'), { recursive: true });
|
|
131
175
|
writeFileSync(path, `${JSON.stringify(settings, null, exists ? indentOf(text) : 2)}\n`, 'utf8');
|
|
132
|
-
return {
|
|
176
|
+
return { ...report, status: exists ? 'updated' : 'created' };
|
|
133
177
|
};
|