@inixiative/atlas 0.2.0 → 0.3.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/README.md +76 -0
- package/bin/atlas.ts +11 -1
- package/package.json +3 -3
- package/src/cli.ts +63 -3
- package/src/commands/graph.ts +6 -2
- package/src/commands/setup.ts +133 -0
- package/src/hook/cachedGraph.ts +57 -0
- package/src/hook/claudeCode.ts +69 -0
- package/src/hook/neighbourhood.ts +130 -0
- package/src/index.ts +24 -0
package/README.md
CHANGED
|
@@ -85,6 +85,9 @@ atlas coverage # unannotated files; @uses curation buckets; unresolved member
|
|
|
85
85
|
atlas generate # write MAP.md from the annotated tree
|
|
86
86
|
atlas report # coverage gaps + concept graph → COVERAGE.md (Mermaid) and atlas.html (Cytoscape)
|
|
87
87
|
atlas stamp [dir] # write/refresh @atlas blocks from the rules (the patcher; dry-run by default)
|
|
88
|
+
atlas hook read # Claude Code PostToolUse hook: the concept neighbourhood of the file just read
|
|
89
|
+
atlas hook grep # Claude Code PostToolUse hook: the concepts a grep pattern names
|
|
90
|
+
atlas setup # offer to add both hooks to .claude/settings.json (--yes: no prompt)
|
|
88
91
|
```
|
|
89
92
|
|
|
90
93
|
Common flags: `--root <dir>`, `--json`, `generate --stdout`, `stamp --write`, `stamp --overwrite`,
|
|
@@ -108,6 +111,79 @@ before opening it. In an A/B test on a repo with a transitive dependency, agents
|
|
|
108
111
|
used `atlas graph` and solved a "what reaches redis (directly or transitively)" question in ~2 tool
|
|
109
112
|
calls; agents left to `grep` took 2–3× as many and risk missing the transitive edge entirely.
|
|
110
113
|
|
|
114
|
+
### Hooks: the neighbourhood on every Read and Grep
|
|
115
|
+
|
|
116
|
+
The map only helps if the agent looks at it. `atlas hook read` and `atlas hook grep` put it in
|
|
117
|
+
front of the agent without asking: when it reads a file, it sees which concepts the file is part
|
|
118
|
+
of, how many sibling files and `@uses` consumers each concept has, and the file's own `@uses`.
|
|
119
|
+
Agents under-weight small primitives because they can't see how much relies on them; the
|
|
120
|
+
consumer count is that reach, stated as a fact.
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
atlas neighbourhood of src/test/factories/userFactory.ts:
|
|
124
|
+
|
|
125
|
+
factory, 1 of 2 factories in primitive:testFactories
|
|
126
|
+
|
|
127
|
+
primitive:testFactories — 2 other file(s), 1 consumer(s) via @uses; `bunx atlas query --partOf primitive:testFactories` lists all
|
|
128
|
+
src/test/factories/buildFactory.ts
|
|
129
|
+
src/test/factories/organizationFactory.ts
|
|
130
|
+
|
|
131
|
+
@uses feature:users — load-bearing dependencies; `bunx atlas query --partOf <concept>` shows what implements each
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
A file of `@kind factory` or `@kind constructor` also gets a line counting that kind in its
|
|
135
|
+
concept (`REACH_KINDS`). On Grep, the pattern's longest identifier is matched against concept
|
|
136
|
+
names and the matching concepts' files are listed.
|
|
137
|
+
|
|
138
|
+
Install them with `atlas setup` (asks first; `atlas setup --yes` for scripts and agents). It
|
|
139
|
+
merges two `PostToolUse` entries into `.claude/settings.json`, leaves every other key and hook as it
|
|
140
|
+
was, and adds nothing on a second run:
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{
|
|
144
|
+
"hooks": {
|
|
145
|
+
"PostToolUse": [
|
|
146
|
+
{
|
|
147
|
+
"matcher": "Read",
|
|
148
|
+
"hooks": [
|
|
149
|
+
{
|
|
150
|
+
"type": "command",
|
|
151
|
+
"command": "[ -e \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" ] && bun \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" hook read || true",
|
|
152
|
+
"timeout": 20,
|
|
153
|
+
"statusMessage": "atlas: concept neighbourhood of this file"
|
|
154
|
+
}
|
|
155
|
+
]
|
|
156
|
+
},
|
|
157
|
+
{
|
|
158
|
+
"matcher": "Grep",
|
|
159
|
+
"hooks": [
|
|
160
|
+
{
|
|
161
|
+
"type": "command",
|
|
162
|
+
"command": "[ -e \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" ] && bun \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" hook grep || true",
|
|
163
|
+
"timeout": 20,
|
|
164
|
+
"statusMessage": "atlas: concepts matching this pattern"
|
|
165
|
+
}
|
|
166
|
+
]
|
|
167
|
+
}
|
|
168
|
+
]
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
How they behave:
|
|
174
|
+
|
|
175
|
+
- **Silent on failure.** Bad input, no `.atlas/` above the file, an unannotated file, atlas not
|
|
176
|
+
installed yet (the command checks for the binary first): no output, exit 0. Set `ATLAS_HOOK_DEBUG=1` to see errors on stderr.
|
|
177
|
+
- **The owning `.atlas/` is the one above the file**, so a file in a worktree maps against that
|
|
178
|
+
worktree's config even when the session runs from the main checkout.
|
|
179
|
+
- **Cached graph.** The graph is built with atlas's own `analyze` and cached per repo root in the
|
|
180
|
+
OS temp dir for 10 minutes, keyed by atlas version and rebuilt early when a `.atlas/` file
|
|
181
|
+
changes.
|
|
182
|
+
- **Harness-agnostic core.** `renderNeighbourhood(graph, relPath)` and
|
|
183
|
+
`renderConceptMatches(graph, pattern)` return plain text; `runClaudeCodeHook` is the Claude Code
|
|
184
|
+
adapter (stdin JSON in, `hookSpecificOutput.additionalContext` out). Another harness needs only
|
|
185
|
+
its own adapter.
|
|
186
|
+
|
|
111
187
|
## Visualize
|
|
112
188
|
|
|
113
189
|
`atlas report` emits two artifacts:
|
package/bin/atlas.ts
CHANGED
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
import { runCli } from '../src/cli.ts';
|
|
3
3
|
|
|
4
|
-
const { code, out } = await runCli(process.argv.slice(2), {
|
|
4
|
+
const { code, out } = await runCli(process.argv.slice(2), {
|
|
5
|
+
cwd: process.cwd(),
|
|
6
|
+
stdin: () => Bun.stdin.text(),
|
|
7
|
+
confirm: process.stdin.isTTY
|
|
8
|
+
? async (question) => {
|
|
9
|
+
const answer = prompt(`${question} [Y/n]`);
|
|
10
|
+
if (answer === null) return false;
|
|
11
|
+
return answer.trim() === '' || /^y(es)?$/i.test(answer.trim());
|
|
12
|
+
}
|
|
13
|
+
: undefined,
|
|
14
|
+
});
|
|
5
15
|
if (out) (code === 0 ? console.log : console.error)(out);
|
|
6
16
|
process.exit(code);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inixiative/atlas",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "The map of the codebase — @atlas code annotations + a seam registry + a drift-proof MAP.md. A map that can only assert what is mechanically true.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -53,13 +53,13 @@
|
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@biomejs/biome": "2.5.2",
|
|
56
|
-
"@inixiative/config": "^0.5.
|
|
56
|
+
"@inixiative/config": "^0.5.102",
|
|
57
57
|
"@types/bun": "1.4.2",
|
|
58
58
|
"lefthook": "2.1.9",
|
|
59
59
|
"typescript": "6.0.3"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@inixiative/json-rules": "^3.
|
|
62
|
+
"@inixiative/json-rules": "^3.5.4"
|
|
63
63
|
},
|
|
64
64
|
"packageManager": "bun@1.4.2"
|
|
65
65
|
}
|
package/src/cli.ts
CHANGED
|
@@ -6,7 +6,9 @@ import { generate } from './commands/generate.ts';
|
|
|
6
6
|
import { graph } from './commands/graph.ts';
|
|
7
7
|
import { flagsToRule, type QueryRule, queryFiles, toQueryRecords } from './commands/query.ts';
|
|
8
8
|
import { buildConceptGraph, buildCoverageReport } from './commands/report.ts';
|
|
9
|
+
import { CLAUDE_SETTINGS, type SetupReport, setupClaudeHooks } from './commands/setup.ts';
|
|
9
10
|
import { inScope, runStamp } from './commands/stamp.ts';
|
|
11
|
+
import { HOOK_EVENTS, type HookEvent, runClaudeCodeHook } from './hook/claudeCode.ts';
|
|
10
12
|
import { renderCoverageHtml } from './render/html.ts';
|
|
11
13
|
import { renderCoverageMarkdown } from './render/markdown.ts';
|
|
12
14
|
|
|
@@ -25,6 +27,11 @@ Commands:
|
|
|
25
27
|
query [predicate] find files by axis — flags (--kind/--partOf/--uses/--path) and/or a
|
|
26
28
|
json-rules predicate (the same AST used for authz/filtering)
|
|
27
29
|
stamp [target] write/refresh @atlas blocks from the config rules (the patcher)
|
|
30
|
+
hook read|grep Claude Code PostToolUse hook: reads the hook JSON on stdin and prints
|
|
31
|
+
the concept neighbourhood (read) or matching concepts (grep) as
|
|
32
|
+
additionalContext; silent on any failure
|
|
33
|
+
setup offer to add the read/grep hooks to .claude/settings.json (merges,
|
|
34
|
+
never duplicates); --yes adds them without asking
|
|
28
35
|
|
|
29
36
|
Flags:
|
|
30
37
|
--root <dir> repo root to operate on (default: cwd)
|
|
@@ -40,6 +47,7 @@ Flags:
|
|
|
40
47
|
--write persist changes (stamp; default is a dry-run)
|
|
41
48
|
--overwrite resync derivable @kind/@partOf, preserving curated @uses (stamp)
|
|
42
49
|
--kind/--partOf/--uses/--path <v> axis filters (query; AND together, combine with a predicate)
|
|
50
|
+
--yes accept setup's offer without prompting (non-interactive)
|
|
43
51
|
--version print version
|
|
44
52
|
--help this help`;
|
|
45
53
|
|
|
@@ -77,9 +85,17 @@ const version = async (): Promise<string> => {
|
|
|
77
85
|
return pkg.version ?? pkg.default?.version ?? '0.0.0';
|
|
78
86
|
};
|
|
79
87
|
|
|
88
|
+
export type CliEnv = {
|
|
89
|
+
cwd: string;
|
|
90
|
+
// the hook's input; read lazily so no other command blocks on stdin
|
|
91
|
+
stdin?: () => Promise<string>;
|
|
92
|
+
// setup's offer; absent = non-interactive (only --yes writes)
|
|
93
|
+
confirm?: (question: string) => Promise<boolean>;
|
|
94
|
+
};
|
|
95
|
+
|
|
80
96
|
export const runCli = async (
|
|
81
97
|
argv: string[],
|
|
82
|
-
env:
|
|
98
|
+
env: CliEnv,
|
|
83
99
|
): Promise<{ code: number; out: string }> => {
|
|
84
100
|
const out: string[] = [];
|
|
85
101
|
const log = (s = ''): void => void out.push(s);
|
|
@@ -97,7 +113,7 @@ export const runCli = async (
|
|
|
97
113
|
// Error boundary: any thrown error (bad config, IO, corrupt baseline) becomes a
|
|
98
114
|
// clean one-line message + exit 1, never an unhandled rejection / stack trace.
|
|
99
115
|
try {
|
|
100
|
-
return await dispatch(command, positionals, flags, { root, json, log, done });
|
|
116
|
+
return await dispatch(command, positionals, flags, { root, json, log, done, env });
|
|
101
117
|
} catch (err) {
|
|
102
118
|
return { code: 1, out: `atlas: ${err instanceof Error ? err.message : String(err)}` };
|
|
103
119
|
}
|
|
@@ -108,15 +124,59 @@ type Ctx = {
|
|
|
108
124
|
json: boolean;
|
|
109
125
|
log: (s?: string) => void;
|
|
110
126
|
done: (code: number) => { code: number; out: string };
|
|
127
|
+
env: CliEnv;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
const logSetup = (log: (s?: string) => void, r: SetupReport, offered: boolean): void => {
|
|
131
|
+
if (r.status === 'unchanged') log(`✓ ${r.settings} already has the atlas hooks`);
|
|
132
|
+
else if (r.status === 'dry-run')
|
|
133
|
+
log(
|
|
134
|
+
offered
|
|
135
|
+
? `skipped: ${r.settings} unchanged`
|
|
136
|
+
: `would add atlas hook ${r.added.join(', ')} to ${r.settings} — re-run with --yes to write`,
|
|
137
|
+
);
|
|
138
|
+
else log(`✓ ${r.status} ${r.settings}: added atlas hook ${r.added.join(', ')}`);
|
|
139
|
+
for (const n of r.notes) log(` note: ${n}`);
|
|
111
140
|
};
|
|
112
141
|
|
|
113
142
|
const dispatch = async (
|
|
114
143
|
command: string,
|
|
115
144
|
positionals: string[],
|
|
116
145
|
flags: Flags,
|
|
117
|
-
{ root, json, log, done }: Ctx,
|
|
146
|
+
{ root, json, log, done, env }: Ctx,
|
|
118
147
|
): Promise<{ code: number; out: string }> => {
|
|
119
148
|
switch (command) {
|
|
149
|
+
case 'hook': {
|
|
150
|
+
const event = positionals[1] as HookEvent | undefined;
|
|
151
|
+
if (!event || !HOOK_EVENTS.includes(event)) {
|
|
152
|
+
log(`hook needs an event: ${HOOK_EVENTS.join(' | ')}`);
|
|
153
|
+
return done(1);
|
|
154
|
+
}
|
|
155
|
+
let stdin = '';
|
|
156
|
+
try {
|
|
157
|
+
stdin = (await env.stdin?.()) ?? '';
|
|
158
|
+
} catch {}
|
|
159
|
+
const output = await runClaudeCodeHook(event, stdin, { version: await version() });
|
|
160
|
+
if (output) log(output);
|
|
161
|
+
return done(0);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
case 'setup': {
|
|
165
|
+
const plan = setupClaudeHooks(root, { write: false });
|
|
166
|
+
let report = plan;
|
|
167
|
+
let offered = false;
|
|
168
|
+
if (plan.status === 'dry-run') {
|
|
169
|
+
const question = `Add atlas's PostToolUse hooks (${plan.added.join(', ')}) to ${CLAUDE_SETTINGS}?`;
|
|
170
|
+
const confirm = flags.yes === true ? undefined : env.confirm;
|
|
171
|
+
offered = confirm !== undefined;
|
|
172
|
+
const accepted = flags.yes === true || (confirm !== undefined && (await confirm(question)));
|
|
173
|
+
if (accepted) report = setupClaudeHooks(root, { write: true });
|
|
174
|
+
}
|
|
175
|
+
if (json) log(JSON.stringify(report, null, 2));
|
|
176
|
+
else logSetup(log, report, offered);
|
|
177
|
+
return done(0);
|
|
178
|
+
}
|
|
179
|
+
|
|
120
180
|
case 'check': {
|
|
121
181
|
const target = positionals[1];
|
|
122
182
|
const warnOnly = flags['warn-only'] === true;
|
package/src/commands/graph.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { invert } from '../registry/invert.ts';
|
|
|
7
7
|
export type Graph = {
|
|
8
8
|
conceptToFiles: Record<string, string[]>; // via @partOf (membership)
|
|
9
9
|
usesConsumers: Record<string, string[]>; // via @uses (dependency)
|
|
10
|
-
fileToConcepts: Record<string, { partOf: string[]; uses: string[] }>;
|
|
10
|
+
fileToConcepts: Record<string, { kind: string[]; partOf: string[]; uses: string[] }>;
|
|
11
11
|
docToConcepts: Record<string, string[]>;
|
|
12
12
|
};
|
|
13
13
|
|
|
@@ -23,7 +23,11 @@ export const graph = (a: Analysis): Graph => {
|
|
|
23
23
|
|
|
24
24
|
for (const { path, annotation } of a.files) {
|
|
25
25
|
if (!annotation) continue;
|
|
26
|
-
fileToConcepts[path] = {
|
|
26
|
+
fileToConcepts[path] = {
|
|
27
|
+
kind: annotation.kind,
|
|
28
|
+
partOf: annotation.partOf,
|
|
29
|
+
uses: annotation.uses,
|
|
30
|
+
};
|
|
27
31
|
for (const concept of annotation.partOf) push(conceptToFiles, concept, path);
|
|
28
32
|
for (const concept of annotation.uses) push(usesConsumers, concept, path);
|
|
29
33
|
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { HOOK_EVENTS, type HookEvent } from '../hook/claudeCode.ts';
|
|
4
|
+
|
|
5
|
+
export const CLAUDE_SETTINGS = '.claude/settings.json';
|
|
6
|
+
|
|
7
|
+
type HookCommand = { type: string; command?: string; [key: string]: unknown };
|
|
8
|
+
type MatcherGroup = { matcher?: string; hooks?: HookCommand[]; [key: string]: unknown };
|
|
9
|
+
type ClaudeSettings = { hooks?: Record<string, MatcherGroup[]>; [key: string]: unknown };
|
|
10
|
+
|
|
11
|
+
const HOOKS: Record<HookEvent, { matcher: string; statusMessage: string }> = {
|
|
12
|
+
read: { matcher: 'Read', statusMessage: 'atlas: concept neighbourhood of this file' },
|
|
13
|
+
grep: { matcher: 'Grep', statusMessage: 'atlas: concepts matching this pattern' },
|
|
14
|
+
};
|
|
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.
|
|
20
|
+
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`;
|
|
23
|
+
|
|
24
|
+
const hookCommand = (event: HookEvent): HookCommand => ({
|
|
25
|
+
type: 'command',
|
|
26
|
+
command: hookCommandFor(event),
|
|
27
|
+
timeout: 20,
|
|
28
|
+
statusMessage: HOOKS[event].statusMessage,
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export const atlasHookEntry = (event: HookEvent): MatcherGroup => ({
|
|
32
|
+
matcher: HOOKS[event].matcher,
|
|
33
|
+
hooks: [hookCommand(event)],
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const ATLAS_HOOK = (event: HookEvent) => new RegExp(`\\batlas(\\.ts)?"?\\s+hook\\s+${event}\\b`);
|
|
37
|
+
|
|
38
|
+
const hasAtlasHook = (groups: MatcherGroup[], event: HookEvent): boolean =>
|
|
39
|
+
groups.some((g) => (g.hooks ?? []).some((h) => ATLAS_HOOK(event).test(h.command ?? '')));
|
|
40
|
+
|
|
41
|
+
// Merge the two PostToolUse entries into existing settings without touching anything
|
|
42
|
+
// 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[] } => {
|
|
45
|
+
settings.hooks ??= {};
|
|
46
|
+
settings.hooks.PostToolUse ??= [];
|
|
47
|
+
const groups = settings.hooks.PostToolUse;
|
|
48
|
+
const added: HookEvent[] = [];
|
|
49
|
+
for (const event of HOOK_EVENTS) {
|
|
50
|
+
if (hasAtlasHook(groups, event)) continue;
|
|
51
|
+
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));
|
|
54
|
+
added.push(event);
|
|
55
|
+
}
|
|
56
|
+
return { added };
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
// The hand-copied predecessors mix gloss and atlas; once atlas's own hook is in, their
|
|
60
|
+
// atlas half is a duplicate the repo should drop.
|
|
61
|
+
const legacyHooks = (settings: ClaudeSettings): string[] =>
|
|
62
|
+
(settings.hooks?.PostToolUse ?? [])
|
|
63
|
+
.flatMap((g) => g.hooks ?? [])
|
|
64
|
+
.map((h) => h.command ?? '')
|
|
65
|
+
.filter((c) => /glossAtlasOn(Read|Grep)/.test(c));
|
|
66
|
+
|
|
67
|
+
const indentOf = (text: string): string | number => {
|
|
68
|
+
const line = text.split('\n').find((l) => /^\s+\S/.test(l));
|
|
69
|
+
if (!line) return 2;
|
|
70
|
+
const lead = /^\s+/.exec(line)?.[0] ?? '';
|
|
71
|
+
return lead.startsWith('\t') ? '\t' : lead.length;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
const isObject = (v: unknown): v is Record<string, unknown> =>
|
|
75
|
+
typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
76
|
+
|
|
77
|
+
// The merge walks hooks.PostToolUse[].hooks[]; refuse a file whose shape would make
|
|
78
|
+
// that walk throw, rather than surfacing a TypeError.
|
|
79
|
+
const settingsShapeError = (settings: ClaudeSettings): string | undefined => {
|
|
80
|
+
if (settings.hooks === undefined) return undefined;
|
|
81
|
+
if (!isObject(settings.hooks)) return '"hooks" is not an object';
|
|
82
|
+
const post: unknown = settings.hooks.PostToolUse;
|
|
83
|
+
if (post === undefined) return undefined;
|
|
84
|
+
if (!Array.isArray(post)) return '"hooks.PostToolUse" is not an array';
|
|
85
|
+
for (const group of post as unknown[]) {
|
|
86
|
+
if (!isObject(group)) return 'a "hooks.PostToolUse" entry is not an object';
|
|
87
|
+
if (group.hooks !== undefined && !Array.isArray(group.hooks))
|
|
88
|
+
return 'a "hooks.PostToolUse" entry has a non-array "hooks"';
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export type SetupReport = {
|
|
94
|
+
settings: string;
|
|
95
|
+
status: 'created' | 'updated' | 'unchanged' | 'dry-run';
|
|
96
|
+
// with status dry-run: the entries a write would add
|
|
97
|
+
added: HookEvent[];
|
|
98
|
+
notes: string[];
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export const setupClaudeHooks = (root: string, options: { write: boolean }): SetupReport => {
|
|
102
|
+
const path = join(root, CLAUDE_SETTINGS);
|
|
103
|
+
const exists = existsSync(path);
|
|
104
|
+
const text = exists ? readFileSync(path, 'utf8') : '';
|
|
105
|
+
let settings: ClaudeSettings;
|
|
106
|
+
try {
|
|
107
|
+
settings = exists && text.trim() !== '' ? (JSON.parse(text) as ClaudeSettings) : {};
|
|
108
|
+
} catch (err) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`${CLAUDE_SETTINGS} is not valid JSON (${err instanceof Error ? err.message : String(err)}); not touching it`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
if (!isObject(settings))
|
|
114
|
+
throw new Error(`${CLAUDE_SETTINGS} is not a JSON object; not touching it`);
|
|
115
|
+
const shapeError = settingsShapeError(settings);
|
|
116
|
+
if (shapeError) throw new Error(`${CLAUDE_SETTINGS}: ${shapeError}; not touching it`);
|
|
117
|
+
|
|
118
|
+
const notes: string[] = [];
|
|
119
|
+
if (!existsSync(join(root, '.atlas')))
|
|
120
|
+
notes.push(
|
|
121
|
+
'no .atlas/ here yet: the hooks stay silent until one exists (see examples/atlas-config)',
|
|
122
|
+
);
|
|
123
|
+
for (const legacy of legacyHooks(settings))
|
|
124
|
+
notes.push(`legacy hook still configured: ${legacy} (its atlas half duplicates atlas hook)`);
|
|
125
|
+
|
|
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 };
|
|
129
|
+
|
|
130
|
+
mkdirSync(join(root, '.claude'), { recursive: true });
|
|
131
|
+
writeFileSync(path, `${JSON.stringify(settings, null, exists ? indentOf(text) : 2)}\n`, 'utf8');
|
|
132
|
+
return { settings: CLAUDE_SETTINGS, status: exists ? 'updated' : 'created', added, notes };
|
|
133
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { analyze } from '../analyze.ts';
|
|
6
|
+
import { type Graph, graph } from '../commands/graph.ts';
|
|
7
|
+
|
|
8
|
+
export const GRAPH_CACHE_TTL_MS = 10 * 60 * 1000;
|
|
9
|
+
|
|
10
|
+
export type CachedGraphOptions = { ttlMs?: number; cacheDir?: string; version?: string };
|
|
11
|
+
|
|
12
|
+
// ATLAS_HOOK_CACHE_DIR moves the cache (tests isolate it; a repo can pin it).
|
|
13
|
+
const defaultCacheDir = (): string =>
|
|
14
|
+
process.env.ATLAS_HOOK_CACHE_DIR || join(tmpdir(), 'atlas-hooks');
|
|
15
|
+
|
|
16
|
+
const cachePathFor = (root: string, cacheDir: string, version: string): string =>
|
|
17
|
+
join(
|
|
18
|
+
cacheDir,
|
|
19
|
+
`graph-${createHash('sha1').update(`${version}\0${root}`).digest('hex').slice(0, 16)}.json`,
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
// A `.atlas/` edit (new concept, new rule) makes the cached graph wrong before the TTL does.
|
|
23
|
+
const configNewerThan = (root: string, mtimeMs: number): boolean => {
|
|
24
|
+
const dir = join(root, '.atlas');
|
|
25
|
+
return readdirSync(dir).some((entry) => statSync(join(dir, entry)).mtimeMs > mtimeMs);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// The hooks fire on every Read/Grep and a full analyze walks the whole tree (seconds on a
|
|
29
|
+
// large repo), so the graph is cached per root for a short TTL. Keyed by atlas version so
|
|
30
|
+
// an upgrade never reads a graph of an older shape.
|
|
31
|
+
export const cachedGraph = async (
|
|
32
|
+
root: string,
|
|
33
|
+
options: CachedGraphOptions = {},
|
|
34
|
+
): Promise<Graph | undefined> => {
|
|
35
|
+
if (!existsSync(join(root, '.atlas'))) return undefined;
|
|
36
|
+
const ttlMs = options.ttlMs ?? GRAPH_CACHE_TTL_MS;
|
|
37
|
+
const cacheDir = options.cacheDir ?? defaultCacheDir();
|
|
38
|
+
const cachePath = cachePathFor(root, cacheDir, options.version ?? '');
|
|
39
|
+
|
|
40
|
+
if (existsSync(cachePath)) {
|
|
41
|
+
const { mtimeMs } = statSync(cachePath);
|
|
42
|
+
// mtimes carry sub-millisecond precision that Date.now() lacks; allow that much skew,
|
|
43
|
+
// but a cache dated well in the future is not trusted as fresh.
|
|
44
|
+
const age = Date.now() - mtimeMs;
|
|
45
|
+
if (age > -1_000 && age < ttlMs && !configNewerThan(root, mtimeMs)) {
|
|
46
|
+
return (await Bun.file(cachePath).json()) as Graph;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const fresh = graph(await analyze(root));
|
|
51
|
+
mkdirSync(cacheDir, { recursive: true });
|
|
52
|
+
// Write-then-rename: parallel hooks (a Read and a Grep in one turn) never read a torn file.
|
|
53
|
+
const tmp = `${cachePath}.${process.pid}.tmp`;
|
|
54
|
+
writeFileSync(tmp, JSON.stringify(fresh), 'utf8');
|
|
55
|
+
renameSync(tmp, cachePath);
|
|
56
|
+
return fresh;
|
|
57
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { join, resolve } from 'node:path';
|
|
2
|
+
import { type CachedGraphOptions, cachedGraph } from './cachedGraph.ts';
|
|
3
|
+
import { findAtlasRoot, renderConceptMatches, renderNeighbourhood } from './neighbourhood.ts';
|
|
4
|
+
|
|
5
|
+
// Claude Code adapter: PostToolUse stdin JSON in, `hookSpecificOutput.additionalContext`
|
|
6
|
+
// out. The core (neighbourhood.ts) stays harness-agnostic; only this file knows Claude.
|
|
7
|
+
|
|
8
|
+
export type HookEvent = 'read' | 'grep';
|
|
9
|
+
export const HOOK_EVENTS: readonly HookEvent[] = ['read', 'grep'];
|
|
10
|
+
|
|
11
|
+
type PostToolUseInput = {
|
|
12
|
+
cwd?: string;
|
|
13
|
+
tool_input?: { file_path?: string; pattern?: string; path?: string };
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const MAX_CHARS = 8000;
|
|
17
|
+
|
|
18
|
+
export const toAdditionalContext = (text: string): string => {
|
|
19
|
+
const trimmed = text.trim();
|
|
20
|
+
if (trimmed === '') return '';
|
|
21
|
+
const body =
|
|
22
|
+
trimmed.length > MAX_CHARS
|
|
23
|
+
? `${trimmed.slice(0, MAX_CHARS)}\n… (truncated; bunx atlas query --partOf <concept> lists the rest)`
|
|
24
|
+
: trimmed;
|
|
25
|
+
return JSON.stringify({
|
|
26
|
+
suppressOutput: true,
|
|
27
|
+
hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: body },
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const contextFor = async (
|
|
32
|
+
event: HookEvent,
|
|
33
|
+
input: PostToolUseInput,
|
|
34
|
+
cache: CachedGraphOptions,
|
|
35
|
+
): Promise<string | undefined> => {
|
|
36
|
+
if (event === 'read') {
|
|
37
|
+
const filePath = input.tool_input?.file_path;
|
|
38
|
+
if (!filePath) return undefined;
|
|
39
|
+
const location = findAtlasRoot(filePath);
|
|
40
|
+
if (!location) return undefined;
|
|
41
|
+
const g = await cachedGraph(location.root, cache);
|
|
42
|
+
return g && renderNeighbourhood(g, location.relPath);
|
|
43
|
+
}
|
|
44
|
+
const pattern = input.tool_input?.pattern;
|
|
45
|
+
if (!pattern) return undefined;
|
|
46
|
+
const cwd = input.cwd ?? process.cwd();
|
|
47
|
+
const anchor = input.tool_input?.path ? resolve(cwd, input.tool_input.path) : cwd;
|
|
48
|
+
// Probe a child of the anchor so a directory anchor's own `.atlas/` is found.
|
|
49
|
+
const location = findAtlasRoot(join(anchor, '__atlas_probe__'));
|
|
50
|
+
if (!location) return undefined;
|
|
51
|
+
const g = await cachedGraph(location.root, cache);
|
|
52
|
+
return g && renderConceptMatches(g, pattern);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// Never throws: a hook that errors surfaces on every Read/Grep, so silence is the
|
|
56
|
+
// failure mode. Set ATLAS_HOOK_DEBUG to see the error on stderr.
|
|
57
|
+
export const runClaudeCodeHook = async (
|
|
58
|
+
event: HookEvent,
|
|
59
|
+
stdin: string,
|
|
60
|
+
cache: CachedGraphOptions = {},
|
|
61
|
+
): Promise<string> => {
|
|
62
|
+
try {
|
|
63
|
+
const input = JSON.parse(stdin) as PostToolUseInput;
|
|
64
|
+
return toAdditionalContext((await contextFor(event, input, cache)) ?? '');
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (process.env.ATLAS_HOOK_DEBUG) console.error(error);
|
|
67
|
+
return '';
|
|
68
|
+
}
|
|
69
|
+
};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import type { Graph } from '../commands/graph.ts';
|
|
4
|
+
|
|
5
|
+
// The harness-agnostic core of the read/grep hooks: path in, text out. Adapters
|
|
6
|
+
// (Claude Code today) own stdin/stdout shapes; nothing here knows about a harness.
|
|
7
|
+
|
|
8
|
+
export type AtlasLocation = { root: string; relPath: string };
|
|
9
|
+
|
|
10
|
+
// Kinds whose line also counts how many of that kind the concept holds. These are
|
|
11
|
+
// the files that build things for many callers, the ones agents under-weight.
|
|
12
|
+
export const REACH_KINDS: readonly string[] = ['factory', 'constructor'];
|
|
13
|
+
|
|
14
|
+
const SIBLING_SAMPLE = 12;
|
|
15
|
+
const MAX_CONCEPT_FILES = 20;
|
|
16
|
+
const MIN_TOKEN = 4;
|
|
17
|
+
|
|
18
|
+
// The owning `.atlas/` is the one above the file, not the session cwd: the file may
|
|
19
|
+
// live in a worktree while the session runs from the main checkout.
|
|
20
|
+
export const findAtlasRoot = (absolutePath: string): AtlasLocation | undefined => {
|
|
21
|
+
const target = resolve(absolutePath);
|
|
22
|
+
let dir = dirname(target);
|
|
23
|
+
while (true) {
|
|
24
|
+
if (existsSync(join(dir, '.atlas'))) {
|
|
25
|
+
return { root: dir, relPath: relative(dir, target).split(sep).join('/') };
|
|
26
|
+
}
|
|
27
|
+
const parent = dirname(dir);
|
|
28
|
+
if (parent === dir) return undefined;
|
|
29
|
+
dir = parent;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const plural = (word: string): string => {
|
|
34
|
+
if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
|
|
35
|
+
if (/(s|x|z|ch|sh)$/.test(word)) return `${word}es`;
|
|
36
|
+
return `${word}s`;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const kindLines = (
|
|
40
|
+
graph: Graph,
|
|
41
|
+
relPath: string,
|
|
42
|
+
partOf: string[],
|
|
43
|
+
kinds: readonly string[],
|
|
44
|
+
): string[] => {
|
|
45
|
+
const own = graph.fileToConcepts[relPath]?.kind ?? [];
|
|
46
|
+
const lines: string[] = [];
|
|
47
|
+
for (const kind of own.filter((k) => kinds.includes(k))) {
|
|
48
|
+
for (const concept of partOf) {
|
|
49
|
+
const count = (graph.conceptToFiles[concept] ?? []).filter((file) =>
|
|
50
|
+
graph.fileToConcepts[file]?.kind.includes(kind),
|
|
51
|
+
).length;
|
|
52
|
+
lines.push(`${kind}, 1 of ${count} ${plural(kind)} in ${concept}`);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return lines;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// The read-side neighbourhood: which concepts the file is part of, how many
|
|
59
|
+
// siblings and @uses consumers each has, and the file's own load-bearing @uses.
|
|
60
|
+
export const renderNeighbourhood = (
|
|
61
|
+
graph: Graph,
|
|
62
|
+
relPath: string,
|
|
63
|
+
options: { kinds?: readonly string[] } = {},
|
|
64
|
+
): string | undefined => {
|
|
65
|
+
const membership = graph.fileToConcepts[relPath];
|
|
66
|
+
if (!membership) return undefined;
|
|
67
|
+
const partOfBlocks = membership.partOf.map((concept) => {
|
|
68
|
+
const siblings = (graph.conceptToFiles[concept] ?? []).filter((file) => file !== relPath);
|
|
69
|
+
const sample = siblings.slice(0, SIBLING_SAMPLE).map((file) => ` ${file}`);
|
|
70
|
+
const more =
|
|
71
|
+
siblings.length > SIBLING_SAMPLE ? [` … ${siblings.length - SIBLING_SAMPLE} more`] : [];
|
|
72
|
+
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
73
|
+
return [
|
|
74
|
+
`${concept} — ${siblings.length} other file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
75
|
+
...sample,
|
|
76
|
+
...more,
|
|
77
|
+
].join('\n');
|
|
78
|
+
});
|
|
79
|
+
const usesBlock =
|
|
80
|
+
membership.uses.length > 0
|
|
81
|
+
? [
|
|
82
|
+
`@uses ${membership.uses.join(', ')} — load-bearing dependencies; \`bunx atlas query --partOf <concept>\` shows what implements each`,
|
|
83
|
+
]
|
|
84
|
+
: [];
|
|
85
|
+
const kinds = kindLines(graph, relPath, membership.partOf, options.kinds ?? REACH_KINDS);
|
|
86
|
+
const kindBlock = kinds.length > 0 ? [kinds.join('\n')] : [];
|
|
87
|
+
const blocks = [...kindBlock, ...partOfBlocks, ...usesBlock];
|
|
88
|
+
if (partOfBlocks.length === 0 && usesBlock.length === 0) return undefined;
|
|
89
|
+
return `atlas neighbourhood of ${relPath}:\n\n${blocks.join('\n\n')}`;
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
// A grep pattern is a regex, not a symbol; only its longest identifier-shaped run
|
|
93
|
+
// is worth looking up.
|
|
94
|
+
export const identifierToken = (pattern: string): string | undefined => {
|
|
95
|
+
const tokens = pattern.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
|
|
96
|
+
const longest = tokens.sort((a, b) => b.length - a.length)[0];
|
|
97
|
+
return longest && longest.length >= MIN_TOKEN ? longest : undefined;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
// The grep-side lookup: concepts whose name the pattern's identifier names (exactly,
|
|
101
|
+
// or as a prefix either way once both are long enough to mean something).
|
|
102
|
+
export const renderConceptMatches = (graph: Graph, pattern: string): string | undefined => {
|
|
103
|
+
const token = identifierToken(pattern);
|
|
104
|
+
if (!token) return undefined;
|
|
105
|
+
const lower = token.toLowerCase();
|
|
106
|
+
const hits = Object.keys(graph.conceptToFiles)
|
|
107
|
+
.sort()
|
|
108
|
+
.filter((concept) => {
|
|
109
|
+
const name = concept.split(':')[1]?.toLowerCase() ?? '';
|
|
110
|
+
return (
|
|
111
|
+
name === lower ||
|
|
112
|
+
(name.length >= 5 && lower.startsWith(name)) ||
|
|
113
|
+
(lower.length >= 5 && name.startsWith(lower))
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
if (hits.length === 0) return undefined;
|
|
117
|
+
const blocks = hits.map((concept) => {
|
|
118
|
+
const files = graph.conceptToFiles[concept] ?? [];
|
|
119
|
+
const sample = files.slice(0, MAX_CONCEPT_FILES).map((file) => ` ${file}`);
|
|
120
|
+
const more =
|
|
121
|
+
files.length > MAX_CONCEPT_FILES ? [` … ${files.length - MAX_CONCEPT_FILES} more`] : [];
|
|
122
|
+
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
123
|
+
return [
|
|
124
|
+
`${concept} — ${files.length} file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
125
|
+
...sample,
|
|
126
|
+
...more,
|
|
127
|
+
].join('\n');
|
|
128
|
+
});
|
|
129
|
+
return `atlas concept(s) matching "${token}":\n\n${blocks.join('\n\n')}`;
|
|
130
|
+
};
|
package/src/index.ts
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
// Public API — what a consuming repo's `.atlas/` config imports.
|
|
2
2
|
|
|
3
|
+
export type { Graph } from './commands/graph.ts';
|
|
4
|
+
export {
|
|
5
|
+
atlasHookEntry,
|
|
6
|
+
CLAUDE_SETTINGS,
|
|
7
|
+
hookCommandFor,
|
|
8
|
+
mergeAtlasHooks,
|
|
9
|
+
type SetupReport,
|
|
10
|
+
setupClaudeHooks,
|
|
11
|
+
} from './commands/setup.ts';
|
|
3
12
|
export {
|
|
4
13
|
type AtlasConfigInput,
|
|
5
14
|
defineConfig,
|
|
@@ -11,6 +20,21 @@ export {
|
|
|
11
20
|
type StampRule,
|
|
12
21
|
type TagValue,
|
|
13
22
|
} from './config/defineConfig.ts';
|
|
23
|
+
export { type CachedGraphOptions, cachedGraph, GRAPH_CACHE_TTL_MS } from './hook/cachedGraph.ts';
|
|
24
|
+
export {
|
|
25
|
+
HOOK_EVENTS,
|
|
26
|
+
type HookEvent,
|
|
27
|
+
runClaudeCodeHook,
|
|
28
|
+
toAdditionalContext,
|
|
29
|
+
} from './hook/claudeCode.ts';
|
|
30
|
+
export {
|
|
31
|
+
type AtlasLocation,
|
|
32
|
+
findAtlasRoot,
|
|
33
|
+
identifierToken,
|
|
34
|
+
REACH_KINDS,
|
|
35
|
+
renderConceptMatches,
|
|
36
|
+
renderNeighbourhood,
|
|
37
|
+
} from './hook/neighbourhood.ts';
|
|
14
38
|
export { type AtlasAnnotation, parseAtlasBlock, type UsesState } from './parse/parseAtlasBlock.ts';
|
|
15
39
|
export { invert } from './registry/invert.ts';
|
|
16
40
|
export {
|