@inixiative/atlas 0.4.1 → 0.5.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 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> [target] [flags]
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 [target] presence + vocab + reference + thesaurus existence (the CI command);
22
- a target scopes to a path and skips registry-wide reference checks
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 [target] write/refresh @atlas blocks from the config rules (the patcher)
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 add atlas hook ${r.added.join(', ')} to ${r.settings} — re-run with --yes to write`,
158
+ : `would ${setupChanges(r, false)} in ${r.settings} — re-run with --yes to write`,
137
159
  );
138
- else log(`✓ ${r.status} ${r.settings}: added atlas hook ${r.added.join(', ')}`);
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(', ')}) to ${CLAUDE_SETTINGS}?`;
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 target = positionals[1];
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 = target
185
- ? { ...full, files: full.files.filter((f) => inScope(f.path, target)) }
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: target === undefined });
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, { mode, target: positionals[1], write });
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({ changes: changes.map((c) => ({ path: c.path })), unresolved }, null, 2),
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');
@@ -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) => ({ kind: 'presence' as const, file: f.path, message: 'missing @atlas block' }));
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).
@@ -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
+ };
Binary file
@@ -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
- // Runs the repo's own installed atlas (not `bunx atlas`, which would fetch an unrelated
17
- // npm `atlas` package when this one isn't installed). $CLAUDE_PROJECT_DIR keeps it
18
- // working when the session's cwd moves into a subdirectory. The existence guard keeps a
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 = (event: HookEvent): string =>
22
- `[ -e ${ATLAS_BIN} ] && bun ${ATLAS_BIN} hook ${event} || true`;
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
- const hookCommand = (event: HookEvent): HookCommand => ({
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
- const ATLAS_HOOK = (event: HookEvent) => new RegExp(`\\batlas(\\.ts)?"?\\s+hook\\s+${event}\\b`);
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 (any matcher group) is left alone.
44
- export const mergeAtlasHooks = (settings: ClaudeSettings): { added: HookEvent[] } => {
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 = (root: string, options: { write: boolean }): SetupReport => {
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
- if (added.length === 0) return { settings: CLAUDE_SETTINGS, status: 'unchanged', added, notes };
128
- if (!options.write) return { settings: CLAUDE_SETTINGS, status: 'dry-run', added, notes };
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 { settings: CLAUDE_SETTINGS, status: exists ? 'updated' : 'created', added, notes };
176
+ return { ...report, status: exists ? 'updated' : 'created' };
133
177
  };
@@ -1,48 +1,87 @@
1
- import { resolve } from 'node:path';
1
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { consideredFiles, encodeText, readText, type TextEncoding } from '../analyze.ts';
2
4
  import type { LoadedConfig } from '../config/defineConfig.ts';
3
5
  import { loadConfig } from '../config/load.ts';
4
6
  import { stampFor } from '../config/stamp.ts';
5
7
  import { mapLimit } from '../fs/concurrent.ts';
6
- import { walkFiles } from '../fs/walk.ts';
7
- import { applyStamp, type StampMode } from '../stamp/patcher.ts';
8
+ import { applyStamp, type StampMode, type StampSkip } from '../stamp/patcher.ts';
9
+ import type { CommentStyle } from '../syntax/comments.ts';
8
10
 
9
- export type StampChange = { path: string; before: string; after: string };
11
+ // `before`/`after` are the text; `encoding` is how the file stores it (written back the same way).
12
+ export type StampChange = { path: string; before: string; after: string; encoding?: TextEncoding };
10
13
  export type Unresolved = { file: string; category: string; value: string };
11
- export type StampResult = { changes: StampChange[]; unresolved: Unresolved[] };
14
+ export type Skipped = { file: string; reason: StampSkip };
15
+ export type StampResult = { changes: StampChange[]; unresolved: Unresolved[]; skipped: Skipped[] };
12
16
 
13
17
  const IO_CONCURRENCY = 64;
14
18
 
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);
19
+ // A file is in scope when no target is given, when a target IS the file, or when a target is a
20
+ // folder the file lives under. Targets are repo-relative and may be written `./src`, `src/` or
21
+ // `.` (the whole repo), as a shell or `dirname` produces them.
22
+ export const inScope = (path: string, targets: string[] = []): boolean => {
23
+ if (targets.length === 0) return true;
24
+ return targets.some((raw) => {
25
+ const target = raw.replace(/^(?:\.\/)+/, '').replace(/\/+$/, '');
26
+ if (target === '' || target === '.') return true;
27
+ return path === target || path.startsWith(`${target}/`);
28
+ });
29
+ };
30
+
31
+ // Command-line targets as repo-relative paths. A target is resolved against the repo root (an
32
+ // absolute path works too) and must exist inside it: a typo'd or outside path would otherwise
33
+ // scope a check to nothing and pass. It is read in its on-disk spelling, so `SRC/a.ts` on a
34
+ // case-insensitive disk still scopes to `src/a.ts`.
35
+ const onDisk = (path: string): string => {
36
+ const link = lstatSync(path).isSymbolicLink();
37
+ return link
38
+ ? join(realpathSync.native(dirname(path)), basename(path))
39
+ : realpathSync.native(path);
40
+ };
41
+ export const resolveTargets = (root: string, raw: string[]): string[] => {
42
+ if (raw.length === 0) return [];
43
+ if (!existsSync(root)) throw new Error(`no such directory: ${root}`);
44
+ // the root itself is resolved fully, link included (a project registered through a symlink)
45
+ const realRoot = realpathSync.native(resolve(root));
46
+ return raw.map((target) => {
47
+ const absolute = resolve(root, target);
48
+ try {
49
+ lstatSync(absolute);
50
+ } catch {
51
+ throw new Error(`no such file or folder: ${target}`);
52
+ }
53
+ // the root itself (`.`, or the root path when it is a symlink) is the whole repo
54
+ if (absolute === resolve(root)) return '.';
55
+ const rel = relative(realRoot, onDisk(absolute));
56
+ if (rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
57
+ throw new Error(`target is outside the repo root: ${target}`);
58
+ return rel === '' ? '.' : rel.replaceAll(sep, '/');
59
+ });
22
60
  };
23
61
 
24
62
  // Pure: what stamping a file WOULD do, or null if it's already up to date.
25
63
  export const computeStamp = (
26
- path: string,
64
+ file: { path: string; style: CommentStyle },
27
65
  source: string,
28
66
  config: LoadedConfig,
29
67
  mode: StampMode,
30
68
  ): StampChange | null => {
69
+ const { path } = file;
31
70
  const resolved = stampFor(path, config.stamp, config.concepts);
32
- const { content, changed } = applyStamp(source, resolved, mode);
71
+ const { content, changed } = applyStamp(source, resolved, file, mode);
33
72
  return changed ? { path, before: source, after: content } : null;
34
73
  };
35
74
 
36
75
  // Pure: the full change plan over an in-memory file set, scoped by target.
37
76
  export const planStamp = (
38
- files: { path: string; source: string }[],
77
+ files: { path: string; style: CommentStyle; source: string }[],
39
78
  config: LoadedConfig,
40
79
  mode: StampMode,
41
- target?: string,
80
+ targets: string[] = [],
42
81
  ): StampChange[] =>
43
82
  files
44
- .filter((f) => inScope(f.path, target))
45
- .map((f) => computeStamp(f.path, f.source, config, mode))
83
+ .filter((f) => inScope(f.path, targets))
84
+ .map((f) => computeStamp(f, f.source, config, mode))
46
85
  .filter((c): c is StampChange => c !== null);
47
86
 
48
87
  // IO: read the scoped files, plan, and (only with write) persist. Dry-run is
@@ -52,26 +91,55 @@ export const planStamp = (
52
91
  // to no concept — leaving a file under-stamped — is visible at write time.
53
92
  export const runStamp = async (
54
93
  root: string,
55
- opts: { mode: StampMode; target?: string; write: boolean },
94
+ opts: { mode: StampMode; targets?: string[]; write: boolean },
56
95
  ): Promise<StampResult> => {
57
96
  const config = await loadConfig(root);
58
- const paths = (await walkFiles(root, config.include, config.ignore)).filter((p) =>
59
- inScope(p, opts.target),
60
- );
61
- const files = await mapLimit(paths, IO_CONCURRENCY, async (path) => ({
62
- path,
63
- source: await Bun.file(resolve(root, path)).text(),
64
- }));
97
+ const scoped = (await consideredFiles(root, config)).filter((f) => inScope(f.path, opts.targets));
98
+ // A file with no comment style is tagged by its path; there is nothing to write into it.
99
+ const read = await mapLimit(scoped, IO_CONCURRENCY, async ({ path, style }) => {
100
+ if (!style) return null;
101
+ const read = await readText(root, path);
102
+ return read === null
103
+ ? null
104
+ : { path, style, source: read.text, encoding: read.encoding, exact: read.exact };
105
+ });
106
+ const files = read.filter((f) => f !== null);
65
107
 
66
- const changes = planStamp(files, config, opts.mode, opts.target);
108
+ const changes: StampChange[] = [];
109
+ const skipped: Skipped[] = [];
110
+ // the rules' result for each file, used for the stamp and for the unresolved report
111
+ const rules = new Map(
112
+ scoped.map(
113
+ (f) =>
114
+ [
115
+ f.path,
116
+ f.style === null ? f.stamp : stampFor(f.path, config.stamp, config.concepts),
117
+ ] as const,
118
+ ),
119
+ );
120
+ for (const file of files) {
121
+ const resolved = rules.get(file.path) ?? stampFor(file.path, config.stamp, config.concepts);
122
+ const result = applyStamp(file.source, resolved, file, opts.mode);
123
+ if (result.changed && !file.exact) skipped.push({ file: file.path, reason: 'encoding' });
124
+ else if (result.changed)
125
+ changes.push({
126
+ path: file.path,
127
+ before: file.source,
128
+ after: result.content,
129
+ encoding: file.encoding,
130
+ });
131
+ else if (result.skipped) skipped.push({ file: file.path, reason: result.skipped });
132
+ }
67
133
  const unresolved: Unresolved[] = [];
68
- for (const { path } of files) {
69
- for (const u of stampFor(path, config.stamp, config.concepts).unresolved) {
134
+ for (const [path, stamp] of rules) {
135
+ for (const u of stamp.unresolved) {
70
136
  unresolved.push({ file: path, category: u.category, value: u.value });
71
137
  }
72
138
  }
73
139
 
74
140
  if (opts.write)
75
- await mapLimit(changes, IO_CONCURRENCY, (c) => Bun.write(resolve(root, c.path), c.after));
76
- return { changes, unresolved };
141
+ await mapLimit(changes, IO_CONCURRENCY, (c) =>
142
+ Bun.write(resolve(root, c.path), encodeText(c.after, c.encoding ?? 'utf-8')),
143
+ );
144
+ return { changes, unresolved, skipped };
77
145
  };