@inixiative/atlas 0.2.0 → 0.4.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 +153 -3
- package/bin/atlas.ts +11 -1
- package/examples/atlas-config/README.md +3 -1
- package/examples/atlas-config/thesaurus.ts +21 -0
- package/package.json +3 -3
- package/src/cli.ts +64 -4
- package/src/commands/check.ts +73 -26
- package/src/commands/graph.ts +33 -2
- package/src/commands/setup.ts +133 -0
- package/src/config/defineConfig.ts +2 -1
- package/src/config/load.ts +24 -4
- package/src/hook/cachedGraph.ts +57 -0
- package/src/hook/claudeCode.ts +69 -0
- package/src/hook/neighbourhood.ts +289 -0
- package/src/index.ts +26 -0
- package/src/registry/types.ts +8 -0
package/README.md
CHANGED
|
@@ -44,7 +44,8 @@ repo **owns** its concept registry.
|
|
|
44
44
|
.atlas/
|
|
45
45
|
config.ts // stamp rules (path → tags) + ignore + reference resolvers
|
|
46
46
|
kinds.ts // @kind vocab — extends atlas's defaults
|
|
47
|
-
concepts.ts
|
|
47
|
+
concepts.ts // the concept registry — repo-OWNED, structure only
|
|
48
|
+
thesaurus.ts // optional: per concept, the phrases people search with + its doc (see Thesaurus)
|
|
48
49
|
```
|
|
49
50
|
|
|
50
51
|
```ts
|
|
@@ -74,17 +75,21 @@ export default defineConfig({
|
|
|
74
75
|
```
|
|
75
76
|
|
|
76
77
|
A complete, commented set you can copy into your repo's `.atlas/` is in
|
|
77
|
-
[`examples/atlas-config/`](./examples/atlas-config/) (`kinds.ts`, `concepts.ts`, `config.ts
|
|
78
|
+
[`examples/atlas-config/`](./examples/atlas-config/) (`kinds.ts`, `concepts.ts`, `config.ts`,
|
|
79
|
+
`thesaurus.ts`).
|
|
78
80
|
|
|
79
81
|
## CLI
|
|
80
82
|
|
|
81
83
|
```bash
|
|
82
84
|
atlas graph # reverse indexes: concept → files, file → concepts, doc → concepts
|
|
83
|
-
atlas check # presence + vocab
|
|
85
|
+
atlas check # presence + vocab + reference + thesaurus existence (the CI command)
|
|
84
86
|
atlas coverage # unannotated files; @uses curation buckets; unresolved memberships
|
|
85
87
|
atlas generate # write MAP.md from the annotated tree
|
|
86
88
|
atlas report # coverage gaps + concept graph → COVERAGE.md (Mermaid) and atlas.html (Cytoscape)
|
|
87
89
|
atlas stamp [dir] # write/refresh @atlas blocks from the rules (the patcher; dry-run by default)
|
|
90
|
+
atlas hook read # Claude Code PostToolUse hook: the concept neighbourhood of the file just read
|
|
91
|
+
atlas hook grep # Claude Code PostToolUse hook: the concepts a grep pattern names
|
|
92
|
+
atlas setup # offer to add both hooks to .claude/settings.json (--yes: no prompt)
|
|
88
93
|
```
|
|
89
94
|
|
|
90
95
|
Common flags: `--root <dir>`, `--json`, `generate --stdout`, `stamp --write`, `stamp --overwrite`,
|
|
@@ -108,6 +113,151 @@ before opening it. In an A/B test on a repo with a transitive dependency, agents
|
|
|
108
113
|
used `atlas graph` and solved a "what reaches redis (directly or transitively)" question in ~2 tool
|
|
109
114
|
calls; agents left to `grep` took 2–3× as many and risk missing the transitive edge entirely.
|
|
110
115
|
|
|
116
|
+
### Hooks: the neighbourhood on every Read and Grep
|
|
117
|
+
|
|
118
|
+
The map only helps if the agent looks at it. `atlas hook read` and `atlas hook grep` put it in
|
|
119
|
+
front of the agent without asking: when it reads a file, it sees which concepts the file is part
|
|
120
|
+
of, how many sibling files and `@uses` consumers each concept has, and the file's own `@uses`.
|
|
121
|
+
Agents under-weight small primitives because they can't see how much relies on them; the
|
|
122
|
+
consumer count is that reach, stated as a fact.
|
|
123
|
+
|
|
124
|
+
```
|
|
125
|
+
atlas neighbourhood of src/test/factories/userFactory.ts:
|
|
126
|
+
|
|
127
|
+
factory, 1 of 2 factories in primitive:testFactories
|
|
128
|
+
|
|
129
|
+
primitive:testFactories — 2 other file(s), 1 consumer(s) via @uses; `bunx atlas query --partOf primitive:testFactories` lists all
|
|
130
|
+
src/test/factories/buildFactory.ts
|
|
131
|
+
src/test/factories/organizationFactory.ts
|
|
132
|
+
|
|
133
|
+
@uses feature:users — load-bearing dependencies; `bunx atlas query --partOf <concept>` shows what implements each
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
A file of `@kind factory` or `@kind constructor` also gets a line counting that kind in its
|
|
137
|
+
concept (`REACH_KINDS`). On Grep, the pattern is matched first against the
|
|
138
|
+
[thesaurus](#thesaurus), then its longest identifier against concept names, and the matching
|
|
139
|
+
concepts' files are listed.
|
|
140
|
+
|
|
141
|
+
Install them with `atlas setup` (asks first; `atlas setup --yes` for scripts and agents). It
|
|
142
|
+
merges two `PostToolUse` entries into `.claude/settings.json`, leaves every other key and hook as it
|
|
143
|
+
was, and adds nothing on a second run:
|
|
144
|
+
|
|
145
|
+
```json
|
|
146
|
+
{
|
|
147
|
+
"hooks": {
|
|
148
|
+
"PostToolUse": [
|
|
149
|
+
{
|
|
150
|
+
"matcher": "Read",
|
|
151
|
+
"hooks": [
|
|
152
|
+
{
|
|
153
|
+
"type": "command",
|
|
154
|
+
"command": "[ -e \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" ] && bun \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" hook read || true",
|
|
155
|
+
"timeout": 20,
|
|
156
|
+
"statusMessage": "atlas: concept neighbourhood of this file"
|
|
157
|
+
}
|
|
158
|
+
]
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
"matcher": "Grep",
|
|
162
|
+
"hooks": [
|
|
163
|
+
{
|
|
164
|
+
"type": "command",
|
|
165
|
+
"command": "[ -e \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" ] && bun \"$CLAUDE_PROJECT_DIR/node_modules/.bin/atlas\" hook grep || true",
|
|
166
|
+
"timeout": 20,
|
|
167
|
+
"statusMessage": "atlas: concepts matching this pattern"
|
|
168
|
+
}
|
|
169
|
+
]
|
|
170
|
+
}
|
|
171
|
+
]
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
How they behave:
|
|
177
|
+
|
|
178
|
+
- **Silent on failure.** Bad input, no `.atlas/` above the file, an unannotated file, atlas not
|
|
179
|
+
installed yet (the command checks for the binary first): no output, exit 0. Set `ATLAS_HOOK_DEBUG=1` to see errors on stderr.
|
|
180
|
+
- **The owning `.atlas/` is the one above the file**, so a file in a worktree maps against that
|
|
181
|
+
worktree's config even when the session runs from the main checkout.
|
|
182
|
+
- **Cached graph.** The graph is built with atlas's own `analyze` and cached per repo root in the
|
|
183
|
+
OS temp dir for 10 minutes, keyed by atlas version and rebuilt early when any `.atlas/` file
|
|
184
|
+
(`thesaurus.ts` included) changes.
|
|
185
|
+
- **Harness-agnostic core.** `renderNeighbourhood(graph, relPath)` and
|
|
186
|
+
`renderConceptMatches(graph, pattern)` return plain text; `runClaudeCodeHook` is the Claude Code
|
|
187
|
+
adapter (stdin JSON in, `hookSpecificOutput.additionalContext` out). Another harness needs only
|
|
188
|
+
its own adapter.
|
|
189
|
+
|
|
190
|
+
### Thesaurus
|
|
191
|
+
|
|
192
|
+
A grep for the job ("seed a user", "lock", "factory") names no concept, so the grep hook used to
|
|
193
|
+
say nothing at exactly the moment an agent was looking for something that already exists. The
|
|
194
|
+
thesaurus sits beside the registry and makes those searches land. Like a book's thesaurus it is
|
|
195
|
+
keyed by the thing, not the word: each concept lists the phrases people search with when they mean
|
|
196
|
+
it, and where its doc is, so a hit also says where to read.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
// .atlas/thesaurus.ts — optional. Keyed by concept id from concepts.ts.
|
|
200
|
+
import type { Thesaurus } from '@inixiative/atlas';
|
|
201
|
+
|
|
202
|
+
export const THESAURUS: Thesaurus = {
|
|
203
|
+
'primitive:testFactories': {
|
|
204
|
+
phrases: ['seed a user', 'factory', 'fixture'],
|
|
205
|
+
doc: 'TESTING.md#factories', // optional: a `docs:` value + optional #section
|
|
206
|
+
},
|
|
207
|
+
'primitive:mutex': { phrases: ['lock', 'serialize'] }, // doc defaults to the concept's first `docs:`
|
|
208
|
+
};
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
`doc` takes the same value a `docs:` entry in `concepts.ts` does and goes through the same
|
|
212
|
+
`references.docs` resolver (as written when there is none); a `#section` is kept on the end. Leave
|
|
213
|
+
it out and the concept's first `docs:` entry is used, so a doc is never written twice.
|
|
214
|
+
|
|
215
|
+
Matching is case-insensitive and on whole words or phrases:
|
|
216
|
+
|
|
217
|
+
- **Words, in order.** One alternative of the pattern spells the phrase in consecutive whole words,
|
|
218
|
+
compared joined: camelCase and `snake_case` split, `a`/`an`/`the`/`to`/`of`/`for` ignored.
|
|
219
|
+
`seedUser` and `seed_user` match "seed a user", `acquireLock` matches "lock",
|
|
220
|
+
`createGitHubClient` matches "github". `unlock`, `lockfile` and `seed|user` (two alternatives)
|
|
221
|
+
match nothing. Only an unescaped `|`, `(` or `)` separates alternatives.
|
|
222
|
+
- **Conjugations.** Each phrase word also matches its simple English inflections: `-s`, `-es`,
|
|
223
|
+
`-ing`, `-ed`, `-er`; a final `e` dropped before `-ing`/`-ed`/`-er`; a final consonant after a
|
|
224
|
+
single vowel doubled (`log` → `logging`, `logger`; `stop` → `stopped`); a consonant + `y` becoming
|
|
225
|
+
`-ies`/`-ied`. So "lock" matches `locks`, `locking`, `locked`, `locker`; "serialize" matches
|
|
226
|
+
`serializing`, `serialized`; "factory" matches `factories`. A three-letter word keeps its `e`
|
|
227
|
+
before `-er`, so "use" matches `using` and `used` but not `user`. It is a suffix rule, not a
|
|
228
|
+
stemmer, and stays whole-word: `unlocked`, `blocking` and `serializable` don't match. Write
|
|
229
|
+
phrases in their base form.
|
|
230
|
+
- **The pattern as a regex.** The pattern matches the whole phrase (`seed.*user`, `factor(y|ies)`),
|
|
231
|
+
provided one of its own literal words of three or more letters starts a word of the phrase, so
|
|
232
|
+
`.*` matches nothing and `lock|.*` reaches "lock the door" but not "unlock the door". This
|
|
233
|
+
reading follows regex semantics rather than whole words, and is skipped for patterns over 200
|
|
234
|
+
characters, nested quantifiers, more than four unbounded quantifiers, and syntax JavaScript can't
|
|
235
|
+
parse.
|
|
236
|
+
|
|
237
|
+
Thesaurus hits are listed first, labelled with the phrase so the agent knows a person made the
|
|
238
|
+
mapping, with a `read:` line pointing at the doc; past eight concepts the rest are counted, not
|
|
239
|
+
listed. Then come the concept-name matches not already shown:
|
|
240
|
+
|
|
241
|
+
```
|
|
242
|
+
atlas concept(s) matching "seeding.*users?":
|
|
243
|
+
|
|
244
|
+
primitive:testFactories (thesaurus "seed a user") — 3 file(s), 1 consumer(s) via @uses; `bunx atlas query --partOf primitive:testFactories` lists all
|
|
245
|
+
read: docs/claude/TESTING.md#factories
|
|
246
|
+
src/test/factories/buildFactory.ts
|
|
247
|
+
src/test/factories/organizationFactory.ts
|
|
248
|
+
src/test/factories/userFactory.ts
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
`atlas check` flags an entry for a concept the registry doesn't have, an empty phrase list, an empty
|
|
252
|
+
phrase (one with no letter or digit), and a `doc` whose file doesn't resolve to a real file; a
|
|
253
|
+
scoped `atlas check <target>` skips the doc check like the other reference checks. `loadConfig`
|
|
254
|
+
refuses an entry with any key besides `phrases` and `doc`, so a `docs:` typo can't silently fall
|
|
255
|
+
back to the default doc. Whether a phrase is apt is the curator's call.
|
|
256
|
+
|
|
257
|
+
**Keeping it up:** when a search misses and you later find the thing, add the words you searched
|
|
258
|
+
with to that concept's phrases. Phrases come from how people describe the job, never from a test
|
|
259
|
+
case's expected answer: a thesaurus tuned to its tests only teaches the tests.
|
|
260
|
+
|
|
111
261
|
## Visualize
|
|
112
262
|
|
|
113
263
|
`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);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Example `.atlas/` config
|
|
2
2
|
|
|
3
|
-
Copy these
|
|
3
|
+
Copy these files into a **`.atlas/`** folder at your repo root, then adjust them to your
|
|
4
4
|
layout. This is the entire configuration surface — atlas ships the `@kind` defaults; **your repo
|
|
5
5
|
owns the concept registry.**
|
|
6
6
|
|
|
@@ -9,6 +9,7 @@ owns the concept registry.**
|
|
|
9
9
|
kinds.ts # @kind vocab — atlas's defaults, extended with any roles you add
|
|
10
10
|
concepts.ts # the concept registry — repo-OWNED, structure only (the one you'll edit most)
|
|
11
11
|
config.ts # stamp rules (path → tags), ignore globs, and reference resolvers
|
|
12
|
+
thesaurus.ts # optional: per concept, the phrases people search with + its doc, for `atlas hook grep`
|
|
12
13
|
```
|
|
13
14
|
|
|
14
15
|
The key idea: atlas hardcodes **no** concept classes (`feature`/`primitive`/…) and **no** constituent
|
|
@@ -21,6 +22,7 @@ concept that exists, that a `@kind` is in your vocab, and that referenced docs r
|
|
|
21
22
|
| [`concepts.ts`](./concepts.ts) | constantly | add a concept when you add a feature/primitive; list its constituent folders so `@partOf` auto-fills |
|
|
22
23
|
| [`config.ts`](./config.ts) | rarely | structural globs → `@kind`; capture globs → `@partOf` via membership |
|
|
23
24
|
| [`kinds.ts`](./kinds.ts) | rarely | only when a role the defaults don't cover shows up |
|
|
25
|
+
| [`thesaurus.ts`](./thesaurus.ts) | when a search misses | add the words you searched with to the concept you found |
|
|
24
26
|
|
|
25
27
|
After copying, `bunx atlas stamp --write` fills `@kind`/`@partOf` from the rules, `bunx atlas check`
|
|
26
28
|
gates it, and `bunx atlas generate` writes `MAP.md`.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Thesaurus } from '@inixiative/atlas';
|
|
2
|
+
|
|
3
|
+
// The thesaurus — optional, keyed by concept. Each concept lists the phrases people search
|
|
4
|
+
// with when they mean it, so `atlas hook grep` lands on it for "send an email" or "queue"
|
|
5
|
+
// even though no concept is named that, and points the agent at where to read.
|
|
6
|
+
//
|
|
7
|
+
// `doc` is a `docs:` value as concepts.ts writes it (run through `references.docs`) plus an
|
|
8
|
+
// optional `#section`. Leave it out to use the concept's first `docs:` entry.
|
|
9
|
+
// Write phrases in their base form: "lock" also matches locks, locking, locked.
|
|
10
|
+
//
|
|
11
|
+
// Upkeep: when a search misses and you later find the thing, add the words you searched
|
|
12
|
+
// with to that concept's phrases. Phrases come from how people describe the job, never from
|
|
13
|
+
// a test's expected answer.
|
|
14
|
+
export const THESAURUS: Thesaurus = {
|
|
15
|
+
'feature:email': { phrases: ['send an email', 'mail'], doc: 'COMMUNICATIONS.md#sending' },
|
|
16
|
+
'feature:billing': { phrases: ['invoice', 'charge a customer'] },
|
|
17
|
+
'feature:featureFlags': { phrases: ['feature flag', 'toggle'] },
|
|
18
|
+
'primitive:authz': { phrases: ['permission', 'authorize'] },
|
|
19
|
+
'primitive:caching': { phrases: ['memoize', 'cache'] },
|
|
20
|
+
'primitive:jobs': { phrases: ['background job', 'queue', 'schedule'] },
|
|
21
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inixiative/atlas",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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.103",
|
|
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
|
|
|
@@ -16,7 +18,7 @@ Usage: atlas <command> [target] [flags]
|
|
|
16
18
|
|
|
17
19
|
Commands:
|
|
18
20
|
graph reverse indexes: concept → files, file → concepts, doc → concepts
|
|
19
|
-
check [target] presence + vocab + reference existence (the CI command);
|
|
21
|
+
check [target] presence + vocab + reference + thesaurus existence (the CI command);
|
|
20
22
|
a target scopes to a path and skips registry-wide reference checks
|
|
21
23
|
coverage unannotated files; @uses curation buckets; unresolved memberships
|
|
22
24
|
gate with --min <pct> and/or --ratchet (vs a committed baseline)
|
|
@@ -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/check.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
2
|
import type { Analysis } from '../analyze.ts';
|
|
3
|
+
import type { ReferenceResolver } from '../config/defineConfig.ts';
|
|
4
|
+
import { splitDoc } from './graph.ts';
|
|
3
5
|
|
|
4
6
|
// Enforcement is EXISTENCE, not correctness: presence of a block, validity of
|
|
5
|
-
// the vocabulary used,
|
|
7
|
+
// the vocabulary used, existence of referenced docs, and thesaurus entries that
|
|
8
|
+
// name real concepts. atlas never
|
|
6
9
|
// checks "is this @partOf actually true" or any derived status — fool's errands.
|
|
7
10
|
export type Problem = {
|
|
8
|
-
kind: 'presence' | 'vocab' | 'reference';
|
|
11
|
+
kind: 'presence' | 'vocab' | 'reference' | 'thesaurus';
|
|
9
12
|
file?: string;
|
|
10
13
|
concept?: string;
|
|
11
14
|
message: string;
|
|
@@ -48,47 +51,91 @@ export const checkVocab = (a: Analysis): Problem[] => {
|
|
|
48
51
|
return problems;
|
|
49
52
|
};
|
|
50
53
|
|
|
54
|
+
// Resolve one reference value and confirm the file exists. The resolver is consumer code — a
|
|
55
|
+
// throw is reported, never an unhandled crash of the whole check.
|
|
56
|
+
type MissingReference = { rel: string } | { threw: string } | undefined;
|
|
57
|
+
|
|
58
|
+
const missingReference = async (
|
|
59
|
+
root: string,
|
|
60
|
+
resolver: ReferenceResolver,
|
|
61
|
+
value: string,
|
|
62
|
+
): Promise<MissingReference> => {
|
|
63
|
+
let rel: string;
|
|
64
|
+
try {
|
|
65
|
+
rel = resolver(value);
|
|
66
|
+
} catch (err) {
|
|
67
|
+
return { threw: err instanceof Error ? err.message : String(err) };
|
|
68
|
+
}
|
|
69
|
+
return (await Bun.file(resolve(root, rel)).exists()) ? undefined : { rel };
|
|
70
|
+
};
|
|
71
|
+
|
|
51
72
|
// reference existence — a concept's doc paths resolve to real files.
|
|
52
73
|
export const checkReferences = async (a: Analysis): Promise<Problem[]> => {
|
|
53
74
|
const problems: Problem[] = [];
|
|
54
75
|
for (const [concept, entry] of Object.entries(a.config.concepts)) {
|
|
55
76
|
for (const [field, resolver] of Object.entries(a.config.references)) {
|
|
56
77
|
for (const value of entry[field] ?? []) {
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
message: `${concept}: ${field} resolver threw on '${value}': ${msg}`,
|
|
68
|
-
});
|
|
69
|
-
continue;
|
|
70
|
-
}
|
|
71
|
-
if (!(await Bun.file(resolve(a.root, rel)).exists())) {
|
|
72
|
-
problems.push({
|
|
73
|
-
kind: 'reference',
|
|
74
|
-
concept,
|
|
75
|
-
message: `${concept}: ${field} reference '${value}' → ${rel} does not exist`,
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
+
const missing = await missingReference(a.root, resolver, value);
|
|
79
|
+
if (!missing) continue;
|
|
80
|
+
problems.push({
|
|
81
|
+
kind: 'reference',
|
|
82
|
+
concept,
|
|
83
|
+
message:
|
|
84
|
+
'threw' in missing
|
|
85
|
+
? `${concept}: ${field} resolver threw on '${value}': ${missing.threw}`
|
|
86
|
+
: `${concept}: ${field} reference '${value}' → ${missing.rel} does not exist`,
|
|
87
|
+
});
|
|
78
88
|
}
|
|
79
89
|
}
|
|
80
90
|
}
|
|
81
91
|
return problems;
|
|
82
92
|
};
|
|
83
93
|
|
|
94
|
+
const THESAURUS_FILE = '.atlas/thesaurus.ts';
|
|
95
|
+
|
|
96
|
+
// thesaurus existence — every entry is a registered concept with at least one non-blank
|
|
97
|
+
// phrase, and its own `doc` (the file part, before any `#section`) resolves to a real file
|
|
98
|
+
// through the same `references.docs` resolver. The doc check is a reference check, so a
|
|
99
|
+
// scoped run skips it like the others. A defaulted doc is a `docs:` entry that
|
|
100
|
+
// checkReferences already covers. Whether a phrase is *apt* is the curator's call.
|
|
101
|
+
export const checkThesaurus = async (
|
|
102
|
+
a: Analysis,
|
|
103
|
+
opts: { references?: boolean } = {},
|
|
104
|
+
): Promise<Problem[]> => {
|
|
105
|
+
const concepts = new Set(Object.keys(a.config.concepts));
|
|
106
|
+
const resolver = a.config.references.docs ?? ((value: string) => value);
|
|
107
|
+
const problems: Problem[] = [];
|
|
108
|
+
const flag = (concept: string, message: string) =>
|
|
109
|
+
problems.push({ kind: 'thesaurus', file: THESAURUS_FILE, concept, message });
|
|
110
|
+
for (const [concept, { phrases, doc }] of Object.entries(a.config.thesaurus)) {
|
|
111
|
+
if (!concepts.has(concept))
|
|
112
|
+
flag(concept, `thesaurus names '${concept}', which is not a registered concept`);
|
|
113
|
+
if (phrases.length === 0) flag(concept, `thesaurus entry '${concept}' has no phrases`);
|
|
114
|
+
// A phrase with no letter or digit can never match a search.
|
|
115
|
+
if (phrases.some((phrase) => !/[\p{L}\p{N}]/u.test(phrase)))
|
|
116
|
+
flag(concept, `thesaurus entry '${concept}' has an empty phrase`);
|
|
117
|
+
if (doc !== undefined && opts.references !== false) {
|
|
118
|
+
const missing = await missingReference(a.root, resolver, splitDoc(doc).file);
|
|
119
|
+
if (missing)
|
|
120
|
+
flag(
|
|
121
|
+
concept,
|
|
122
|
+
'threw' in missing
|
|
123
|
+
? `thesaurus entry '${concept}': docs resolver threw on doc '${doc}': ${missing.threw}`
|
|
124
|
+
: `thesaurus entry '${concept}': doc '${doc}' → ${missing.rel} does not exist`,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return problems;
|
|
129
|
+
};
|
|
130
|
+
|
|
84
131
|
// Reference existence is a registry-wide concern, so it is skipped when a run is
|
|
85
|
-
// scoped to a subset of files (incremental PR checks)
|
|
86
|
-
//
|
|
132
|
+
// scoped to a subset of files (incremental PR checks). The thesaurus shape checks stay on:
|
|
133
|
+
// they read only `.atlas/` config, which is whole in every run.
|
|
87
134
|
export const runCheck = async (
|
|
88
135
|
a: Analysis,
|
|
89
136
|
opts: { references?: boolean } = {},
|
|
90
137
|
): Promise<CheckResult> => {
|
|
91
|
-
const problems = [...checkPresence(a), ...checkVocab(a)];
|
|
138
|
+
const problems = [...checkPresence(a), ...checkVocab(a), ...(await checkThesaurus(a, opts))];
|
|
92
139
|
if (opts.references !== false) problems.push(...(await checkReferences(a)));
|
|
93
140
|
return { ok: problems.length === 0, problems };
|
|
94
141
|
};
|
package/src/commands/graph.ts
CHANGED
|
@@ -7,8 +7,9 @@ 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
|
+
thesaurus: Record<string, { phrases: string[]; doc?: string }>; // doc resolved to a repo path
|
|
12
13
|
};
|
|
13
14
|
|
|
14
15
|
const push = (rec: Record<string, string[]>, key: string, val: string): void => {
|
|
@@ -16,6 +17,31 @@ const push = (rec: Record<string, string[]>, key: string, val: string): void =>
|
|
|
16
17
|
rec[key].push(val);
|
|
17
18
|
};
|
|
18
19
|
|
|
20
|
+
// Split `FILE.md#section` so only the file goes through the `references.docs` resolver.
|
|
21
|
+
export const splitDoc = (doc: string): { file: string; section?: string } => {
|
|
22
|
+
const hash = doc.indexOf('#');
|
|
23
|
+
return hash < 0 ? { file: doc } : { file: doc.slice(0, hash), section: doc.slice(hash + 1) };
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// The doc a thesaurus entry points at, as a repo path: its own `doc`, else the concept's first
|
|
27
|
+
// `docs:` entry, through the same resolver `atlas check` uses (identity when none is set).
|
|
28
|
+
const resolvedThesaurus = (a: Analysis): Graph['thesaurus'] => {
|
|
29
|
+
const resolver = a.config.references.docs ?? ((value: string) => value);
|
|
30
|
+
return Object.fromEntries(
|
|
31
|
+
Object.entries(a.config.thesaurus).map(([concept, entry]) => {
|
|
32
|
+
const doc = entry.doc ?? a.config.concepts[concept]?.docs?.[0];
|
|
33
|
+
if (doc === undefined) return [concept, { phrases: entry.phrases }];
|
|
34
|
+
const { file, section } = splitDoc(doc);
|
|
35
|
+
try {
|
|
36
|
+
const path = resolver(file);
|
|
37
|
+
return [concept, { phrases: entry.phrases, doc: section ? `${path}#${section}` : path }];
|
|
38
|
+
} catch {
|
|
39
|
+
return [concept, { phrases: entry.phrases }]; // `atlas check` reports the throw
|
|
40
|
+
}
|
|
41
|
+
}),
|
|
42
|
+
);
|
|
43
|
+
};
|
|
44
|
+
|
|
19
45
|
export const graph = (a: Analysis): Graph => {
|
|
20
46
|
const conceptToFiles: Record<string, string[]> = {};
|
|
21
47
|
const usesConsumers: Record<string, string[]> = {};
|
|
@@ -23,7 +49,11 @@ export const graph = (a: Analysis): Graph => {
|
|
|
23
49
|
|
|
24
50
|
for (const { path, annotation } of a.files) {
|
|
25
51
|
if (!annotation) continue;
|
|
26
|
-
fileToConcepts[path] = {
|
|
52
|
+
fileToConcepts[path] = {
|
|
53
|
+
kind: annotation.kind,
|
|
54
|
+
partOf: annotation.partOf,
|
|
55
|
+
uses: annotation.uses,
|
|
56
|
+
};
|
|
27
57
|
for (const concept of annotation.partOf) push(conceptToFiles, concept, path);
|
|
28
58
|
for (const concept of annotation.uses) push(usesConsumers, concept, path);
|
|
29
59
|
}
|
|
@@ -35,5 +65,6 @@ export const graph = (a: Analysis): Graph => {
|
|
|
35
65
|
usesConsumers,
|
|
36
66
|
fileToConcepts,
|
|
37
67
|
docToConcepts: invert(a.config.concepts, 'docs'),
|
|
68
|
+
thesaurus: resolvedThesaurus(a),
|
|
38
69
|
};
|
|
39
70
|
};
|
|
@@ -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
|
+
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ConceptRegistry } from '../registry/types.ts';
|
|
1
|
+
import type { ConceptRegistry, Thesaurus } from '../registry/types.ts';
|
|
2
2
|
|
|
3
3
|
// `partOfFor` is a LAZY descriptor, not a value. The consumer's config.ts can
|
|
4
4
|
// reference it before the concept registry is loaded; the stamp engine resolves it
|
|
@@ -62,4 +62,5 @@ export const defineConfig = (config: AtlasConfigInput): AtlasConfigInput => conf
|
|
|
62
62
|
export type LoadedConfig = ConfigDefaults & {
|
|
63
63
|
kinds: readonly string[];
|
|
64
64
|
concepts: ConceptRegistry;
|
|
65
|
+
thesaurus: Thesaurus;
|
|
65
66
|
};
|
package/src/config/load.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
2
|
import { DEFAULT_INCLUDE } from '../fs/walk.ts';
|
|
3
|
-
import type { ConceptRegistry } from '../registry/types.ts';
|
|
3
|
+
import type { ConceptRegistry, Thesaurus } from '../registry/types.ts';
|
|
4
4
|
import { DEFAULT_KINDS } from '../vocab/kinds.ts';
|
|
5
5
|
import type { AtlasConfigInput, LoadedConfig } from './defineConfig.ts';
|
|
6
6
|
|
|
@@ -24,19 +24,21 @@ const named = <T>(
|
|
|
24
24
|
throw new Error(`.atlas/${file} exists but exports none of: ${names.join(', ')}`);
|
|
25
25
|
};
|
|
26
26
|
|
|
27
|
-
// Load the consumer's `.atlas/` config: kinds → concepts → config (no
|
|
27
|
+
// Load the consumer's `.atlas/` config: kinds → concepts → thesaurus → config (no
|
|
28
28
|
// evaluation-order coupling, since partOfFor is a lazy descriptor). atlas ships
|
|
29
|
-
// the kinds defaults; the repo OWNS concepts.ts.
|
|
29
|
+
// the kinds defaults; the repo OWNS concepts.ts and the optional thesaurus.ts.
|
|
30
30
|
export const loadConfig = async (root: string): Promise<LoadedConfig> => {
|
|
31
31
|
const dir = resolve(root, '.atlas');
|
|
32
|
-
const [kindsMod, conceptsMod, configMod] = await Promise.all([
|
|
32
|
+
const [kindsMod, conceptsMod, thesaurusMod, configMod] = await Promise.all([
|
|
33
33
|
loadModule(resolve(dir, 'kinds.ts')),
|
|
34
34
|
loadModule(resolve(dir, 'concepts.ts')),
|
|
35
|
+
loadModule(resolve(dir, 'thesaurus.ts')),
|
|
35
36
|
loadModule(resolve(dir, 'config.ts')),
|
|
36
37
|
]);
|
|
37
38
|
|
|
38
39
|
const kinds = named<readonly string[]>(kindsMod, 'kinds.ts', 'KINDS', 'default') ?? DEFAULT_KINDS;
|
|
39
40
|
const concepts = named<ConceptRegistry>(conceptsMod, 'concepts.ts', 'CONCEPTS', 'default') ?? {};
|
|
41
|
+
const thesaurus = named<Thesaurus>(thesaurusMod, 'thesaurus.ts', 'THESAURUS', 'default') ?? {};
|
|
40
42
|
const cfg = named<AtlasConfigInput>(configMod, 'config.ts', 'default', 'config') ?? {};
|
|
41
43
|
|
|
42
44
|
// Concept keys are either `class:name` (a layer member) or a bare classless
|
|
@@ -51,9 +53,27 @@ export const loadConfig = async (root: string): Promise<LoadedConfig> => {
|
|
|
51
53
|
}
|
|
52
54
|
}
|
|
53
55
|
|
|
56
|
+
// A malformed entry would be read character by character downstream; refuse it here.
|
|
57
|
+
for (const [concept, entry] of Object.entries(thesaurus)) {
|
|
58
|
+
const { phrases, doc, ...rest } = (entry ?? {}) as Partial<Record<string, unknown>>;
|
|
59
|
+
if (
|
|
60
|
+
typeof entry !== 'object' ||
|
|
61
|
+
entry === null ||
|
|
62
|
+
Object.keys(rest).length > 0 || // a `docs:` typo would silently fall back to the default doc
|
|
63
|
+
!Array.isArray(phrases) ||
|
|
64
|
+
phrases.some((phrase) => typeof phrase !== 'string') ||
|
|
65
|
+
(doc !== undefined && typeof doc !== 'string')
|
|
66
|
+
) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`.atlas/thesaurus.ts: '${concept}' must be { phrases: string[]; doc?: string }`,
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
54
73
|
return {
|
|
55
74
|
kinds,
|
|
56
75
|
concepts,
|
|
76
|
+
thesaurus,
|
|
57
77
|
stamp: cfg.stamp ?? [],
|
|
58
78
|
ignore: cfg.ignore ?? [],
|
|
59
79
|
include: cfg.include ?? DEFAULT_INCLUDE,
|
|
@@ -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,289 @@
|
|
|
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
|
+
const MAX_THESAURUS_CONCEPTS = 8;
|
|
18
|
+
const MAX_QUOTED_PATTERN = 80;
|
|
19
|
+
|
|
20
|
+
// The owning `.atlas/` is the one above the file, not the session cwd: the file may
|
|
21
|
+
// live in a worktree while the session runs from the main checkout.
|
|
22
|
+
export const findAtlasRoot = (absolutePath: string): AtlasLocation | undefined => {
|
|
23
|
+
const target = resolve(absolutePath);
|
|
24
|
+
let dir = dirname(target);
|
|
25
|
+
while (true) {
|
|
26
|
+
if (existsSync(join(dir, '.atlas'))) {
|
|
27
|
+
return { root: dir, relPath: relative(dir, target).split(sep).join('/') };
|
|
28
|
+
}
|
|
29
|
+
const parent = dirname(dir);
|
|
30
|
+
if (parent === dir) return undefined;
|
|
31
|
+
dir = parent;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const plural = (word: string): string => {
|
|
36
|
+
if (/[^aeiou]y$/.test(word)) return `${word.slice(0, -1)}ies`;
|
|
37
|
+
if (/(s|x|z|ch|sh)$/.test(word)) return `${word}es`;
|
|
38
|
+
return `${word}s`;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const kindLines = (
|
|
42
|
+
graph: Graph,
|
|
43
|
+
relPath: string,
|
|
44
|
+
partOf: string[],
|
|
45
|
+
kinds: readonly string[],
|
|
46
|
+
): string[] => {
|
|
47
|
+
const own = graph.fileToConcepts[relPath]?.kind ?? [];
|
|
48
|
+
const lines: string[] = [];
|
|
49
|
+
for (const kind of own.filter((k) => kinds.includes(k))) {
|
|
50
|
+
for (const concept of partOf) {
|
|
51
|
+
const count = (graph.conceptToFiles[concept] ?? []).filter((file) =>
|
|
52
|
+
graph.fileToConcepts[file]?.kind.includes(kind),
|
|
53
|
+
).length;
|
|
54
|
+
lines.push(`${kind}, 1 of ${count} ${plural(kind)} in ${concept}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return lines;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// The read-side neighbourhood: which concepts the file is part of, how many
|
|
61
|
+
// siblings and @uses consumers each has, and the file's own load-bearing @uses.
|
|
62
|
+
export const renderNeighbourhood = (
|
|
63
|
+
graph: Graph,
|
|
64
|
+
relPath: string,
|
|
65
|
+
options: { kinds?: readonly string[] } = {},
|
|
66
|
+
): string | undefined => {
|
|
67
|
+
const membership = graph.fileToConcepts[relPath];
|
|
68
|
+
if (!membership) return undefined;
|
|
69
|
+
const partOfBlocks = membership.partOf.map((concept) => {
|
|
70
|
+
const siblings = (graph.conceptToFiles[concept] ?? []).filter((file) => file !== relPath);
|
|
71
|
+
const sample = siblings.slice(0, SIBLING_SAMPLE).map((file) => ` ${file}`);
|
|
72
|
+
const more =
|
|
73
|
+
siblings.length > SIBLING_SAMPLE ? [` … ${siblings.length - SIBLING_SAMPLE} more`] : [];
|
|
74
|
+
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
75
|
+
return [
|
|
76
|
+
`${concept} — ${siblings.length} other file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
77
|
+
...sample,
|
|
78
|
+
...more,
|
|
79
|
+
].join('\n');
|
|
80
|
+
});
|
|
81
|
+
const usesBlock =
|
|
82
|
+
membership.uses.length > 0
|
|
83
|
+
? [
|
|
84
|
+
`@uses ${membership.uses.join(', ')} — load-bearing dependencies; \`bunx atlas query --partOf <concept>\` shows what implements each`,
|
|
85
|
+
]
|
|
86
|
+
: [];
|
|
87
|
+
const kinds = kindLines(graph, relPath, membership.partOf, options.kinds ?? REACH_KINDS);
|
|
88
|
+
const kindBlock = kinds.length > 0 ? [kinds.join('\n')] : [];
|
|
89
|
+
const blocks = [...kindBlock, ...partOfBlocks, ...usesBlock];
|
|
90
|
+
if (partOfBlocks.length === 0 && usesBlock.length === 0) return undefined;
|
|
91
|
+
return `atlas neighbourhood of ${relPath}:\n\n${blocks.join('\n\n')}`;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// A grep pattern is a regex, not a symbol; only its longest identifier-shaped run
|
|
95
|
+
// is worth looking up.
|
|
96
|
+
export const identifierToken = (pattern: string): string | undefined => {
|
|
97
|
+
const tokens = pattern.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
|
|
98
|
+
const longest = tokens.sort((a, b) => b.length - a.length)[0];
|
|
99
|
+
return longest && longest.length >= MIN_TOKEN ? longest : undefined;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// Words a phrase carries no meaning in: "seed a user" and `seedUser` are the same search.
|
|
103
|
+
const FILLER = new Set(['a', 'an', 'the', 'to', 'of', 'for']);
|
|
104
|
+
|
|
105
|
+
// The lowercase words of a phrase or identifier: camelCase and regex escapes (`\b`, `\w`)
|
|
106
|
+
// split, punctuation and regex syntax dropped. Filler words go unless they are all there is.
|
|
107
|
+
const wordsOf = (text: string): string[] => {
|
|
108
|
+
const words = (
|
|
109
|
+
text
|
|
110
|
+
.replace(/\\[A-Za-z]/g, ' ')
|
|
111
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
112
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
|
|
113
|
+
.match(/[\p{L}\p{N}]+/gu) ?? []
|
|
114
|
+
).map((word) => word.toLowerCase());
|
|
115
|
+
const meaningful = words.filter((word) => !FILLER.has(word));
|
|
116
|
+
return meaningful.length > 0 ? meaningful : words;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
// The conjugations a search may use for a word, by a small suffix rule (no stemmer): plural
|
|
120
|
+
// `-s`/`-es`, `-ing`, `-ed`, `-er`; a final `e` drops before a vowel suffix (serialize →
|
|
121
|
+
// serializing, serialized, serializer); a final consonant after a single vowel doubles (log →
|
|
122
|
+
// logging, logger; stop → stopped); a consonant + `y` becomes `-ies`/`-ied` (factory →
|
|
123
|
+
// factories). Words under three letters are taken as written, and a 3-letter word keeps its
|
|
124
|
+
// `e` before `-er`, so "use" reaches `using` and `used` but never `user`.
|
|
125
|
+
const conjugations = (word: string): string[] => {
|
|
126
|
+
if (word.length < 3) return [word];
|
|
127
|
+
const forms = [word, `${word}s`, `${word}es`, `${word}ing`, `${word}ed`, `${word}er`];
|
|
128
|
+
const stem = word.slice(0, -1);
|
|
129
|
+
if (word.endsWith('e'))
|
|
130
|
+
forms.push(`${stem}ing`, `${stem}ed`, ...(word.length >= 4 ? [`${stem}er`] : []));
|
|
131
|
+
if (/[^aeiou][aeiou][^aeiouwxy]$/.test(word))
|
|
132
|
+
forms.push(...['ing', 'ed', 'er'].map((suffix) => word + word.slice(-1) + suffix));
|
|
133
|
+
if (/[^aeiou]y$/.test(word)) forms.push(`${stem}ies`, `${stem}ied`);
|
|
134
|
+
return forms;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// A phrase, prepared once per hook call: its words, each word's conjugations, and the longest
|
|
138
|
+
// text a match could span (so a long pattern is only scanned that far from each start).
|
|
139
|
+
type PreparedPhrase = { phrase: string; words: string[]; forms: string[][]; maxLength: number };
|
|
140
|
+
|
|
141
|
+
const preparePhrase = (phrase: string): PreparedPhrase => {
|
|
142
|
+
const words = wordsOf(phrase);
|
|
143
|
+
const forms = words.map(conjugations);
|
|
144
|
+
const maxLength = forms.reduce((sum, list) => sum + Math.max(...list.map((f) => f.length)), 0);
|
|
145
|
+
return { phrase, words, forms, maxLength };
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
// One alternative of the pattern: its words joined, and where each word ends in that text.
|
|
149
|
+
type Segment = { text: string; ends: number[] };
|
|
150
|
+
|
|
151
|
+
// The pattern's alternatives, each read on its own: `seed|user` searches "seed" or "user",
|
|
152
|
+
// never the phrase "seed a user". An escaped `\(`, `\)` or `\|` is a literal, not a boundary.
|
|
153
|
+
const segmentsOf = (pattern: string): Segment[] =>
|
|
154
|
+
pattern
|
|
155
|
+
.replace(/\\[|()]/g, ' ')
|
|
156
|
+
.split(/[|()]/)
|
|
157
|
+
.map(wordsOf)
|
|
158
|
+
.filter((words) => words.length > 0)
|
|
159
|
+
.map((words) => {
|
|
160
|
+
let at = 0;
|
|
161
|
+
return { text: words.join(''), ends: words.map((word) => (at += word.length)) };
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// Does a run of consecutive pattern words spell the phrase, each phrase word in one of its
|
|
165
|
+
// conjugations? Compared joined, so the split doesn't matter: `seedingUsers` spells "seed a
|
|
166
|
+
// user", `createGitHubClient` spells "github", `github` spells "GitHub". The run starts and ends
|
|
167
|
+
// on word boundaries, so `unlock` never spells "lock" and `lockfile` never does either.
|
|
168
|
+
const spells = ({ text, ends }: Segment, { words, forms, maxLength }: PreparedPhrase): boolean => {
|
|
169
|
+
if (words.length === 0) return false;
|
|
170
|
+
const boundaries = new Set(ends);
|
|
171
|
+
const walk = (i: number, at: number, limit: number): boolean =>
|
|
172
|
+
i === forms.length
|
|
173
|
+
? boundaries.has(at)
|
|
174
|
+
: (forms[i] ?? []).some(
|
|
175
|
+
(form) =>
|
|
176
|
+
at + form.length <= limit &&
|
|
177
|
+
text.startsWith(form, at) &&
|
|
178
|
+
walk(i + 1, at + form.length, limit),
|
|
179
|
+
);
|
|
180
|
+
return [0, ...ends.slice(0, -1)].some((start) => walk(0, start, start + maxLength));
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const MAX_REGEX_PATTERN = 200;
|
|
184
|
+
const MAX_UNBOUNDED_QUANTIFIERS = 4;
|
|
185
|
+
|
|
186
|
+
// The pattern read as a regex over a whole phrase, compiled once per hook call, or not at all
|
|
187
|
+
// for long patterns, nested or piled-up quantifiers (they backtrack for seconds in JavaScript),
|
|
188
|
+
// and syntax JavaScript can't parse (the word reading still applies).
|
|
189
|
+
type RegexReading = { regex: RegExp; literals: string[] } | undefined;
|
|
190
|
+
|
|
191
|
+
const regexReadingOf = (pattern: string): RegexReading => {
|
|
192
|
+
if (pattern.length > MAX_REGEX_PATTERN || /\)[+*{]/.test(pattern)) return undefined;
|
|
193
|
+
if ((pattern.match(/[*+]|\{\d+,\}/g) ?? []).length > MAX_UNBOUNDED_QUANTIFIERS) return undefined;
|
|
194
|
+
// A quantifier after a run binds only its last letter (`fixtures?`), so that letter is optional.
|
|
195
|
+
const literals = [...pattern.replace(/\\[A-Za-z]/g, ' ').matchAll(/(\p{L}{3,})([?*{])?/gu)]
|
|
196
|
+
.map(([, run = '', quantifier]) => (quantifier ? run.slice(0, -1) : run).toLowerCase())
|
|
197
|
+
.filter((literal) => literal.length >= 3);
|
|
198
|
+
if (literals.length === 0) return undefined;
|
|
199
|
+
try {
|
|
200
|
+
new RegExp(pattern); // on its own first: `a)|(b` must not escape the anchors below
|
|
201
|
+
return { regex: new RegExp(`^(?:${pattern})$`, 'i'), literals };
|
|
202
|
+
} catch {
|
|
203
|
+
return undefined;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
// Does a grep pattern search for this thesaurus phrase? Either one alternative of the pattern
|
|
208
|
+
// spells it (see `spells`), or the pattern, read as a regex, matches the whole phrase
|
|
209
|
+
// (`seed.*user`, `factor(y|ies)`). The regex reading also needs one of the pattern's own
|
|
210
|
+
// literal words to start a word of the phrase, so `.*` matches nothing and `lock|.*` reaches
|
|
211
|
+
// "lock" but not "unlock".
|
|
212
|
+
const searchesFor = (
|
|
213
|
+
segments: Segment[],
|
|
214
|
+
reading: RegexReading,
|
|
215
|
+
phrase: PreparedPhrase,
|
|
216
|
+
): boolean => {
|
|
217
|
+
if (segments.some((segment) => spells(segment, phrase))) return true;
|
|
218
|
+
if (!reading) return false;
|
|
219
|
+
const { regex, literals } = reading;
|
|
220
|
+
if (!literals.some((literal) => phrase.words.some((word) => word.startsWith(literal))))
|
|
221
|
+
return false;
|
|
222
|
+
return regex.test(phrase.phrase.trim());
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const conceptBlock = (graph: Graph, concept: string, label: string): string => {
|
|
226
|
+
const files = graph.conceptToFiles[concept] ?? [];
|
|
227
|
+
const sample = files.slice(0, MAX_CONCEPT_FILES).map((file) => ` ${file}`);
|
|
228
|
+
const more =
|
|
229
|
+
files.length > MAX_CONCEPT_FILES ? [` … ${files.length - MAX_CONCEPT_FILES} more`] : [];
|
|
230
|
+
const consumers = graph.usesConsumers[concept]?.length ?? 0;
|
|
231
|
+
const doc = graph.thesaurus[concept]?.doc;
|
|
232
|
+
return [
|
|
233
|
+
`${concept}${label} — ${files.length} file(s)${consumers > 0 ? `, ${consumers} consumer(s) via @uses` : ''}; \`bunx atlas query --partOf ${concept}\` lists all`,
|
|
234
|
+
...(doc ? [` read: ${doc}`] : []),
|
|
235
|
+
...sample,
|
|
236
|
+
...more,
|
|
237
|
+
].join('\n');
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
// The grep-side lookup. First the thesaurus (`.atlas/thesaurus.ts`): each concept's phrases,
|
|
241
|
+
// the words people search with when they mean it; a hit is labelled with the phrase so the
|
|
242
|
+
// agent knows a person made that mapping, and points at the concept's doc. Then concepts
|
|
243
|
+
// whose name the pattern's identifier names (exactly, or as a prefix either way once both are
|
|
244
|
+
// long enough to mean something), skipping any the thesaurus already showed.
|
|
245
|
+
export const renderConceptMatches = (graph: Graph, pattern: string): string | undefined => {
|
|
246
|
+
const segments = segmentsOf(pattern);
|
|
247
|
+
const reading = regexReadingOf(pattern);
|
|
248
|
+
const viaThesaurus = new Map<string, string[]>();
|
|
249
|
+
for (const [concept, { phrases }] of Object.entries(graph.thesaurus)) {
|
|
250
|
+
const hits = [...new Set(phrases)].filter((phrase) =>
|
|
251
|
+
searchesFor(segments, reading, preparePhrase(phrase)),
|
|
252
|
+
);
|
|
253
|
+
if (hits.length > 0) viaThesaurus.set(concept, hits);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const token = identifierToken(pattern);
|
|
257
|
+
const lower = token?.toLowerCase();
|
|
258
|
+
const byName = lower
|
|
259
|
+
? Object.keys(graph.conceptToFiles).filter((concept) => {
|
|
260
|
+
if (viaThesaurus.has(concept)) return false;
|
|
261
|
+
const name = concept.split(':')[1]?.toLowerCase() ?? '';
|
|
262
|
+
return (
|
|
263
|
+
name === lower ||
|
|
264
|
+
(name.length >= 5 && lower.startsWith(name)) ||
|
|
265
|
+
(lower.length >= 5 && name.startsWith(lower))
|
|
266
|
+
);
|
|
267
|
+
})
|
|
268
|
+
: [];
|
|
269
|
+
|
|
270
|
+
// A broad phrase on many concepts must not crowd out the rest of the answer.
|
|
271
|
+
const thesaurusHits = [...viaThesaurus.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
272
|
+
const shown = thesaurusHits.slice(0, MAX_THESAURUS_CONCEPTS);
|
|
273
|
+
const hidden = thesaurusHits.length - shown.length;
|
|
274
|
+
const blocks = [
|
|
275
|
+
...shown.map(([concept, hits]) =>
|
|
276
|
+
conceptBlock(
|
|
277
|
+
graph,
|
|
278
|
+
concept,
|
|
279
|
+
` (thesaurus ${hits.map((phrase) => `"${phrase}"`).join(', ')})`,
|
|
280
|
+
),
|
|
281
|
+
),
|
|
282
|
+
...(hidden > 0 ? [`… ${hidden} more concept(s) via the thesaurus; narrow the pattern`] : []),
|
|
283
|
+
...byName.sort().map((concept) => conceptBlock(graph, concept, '')),
|
|
284
|
+
];
|
|
285
|
+
if (blocks.length === 0) return undefined;
|
|
286
|
+
const quoted =
|
|
287
|
+
pattern.length > MAX_QUOTED_PATTERN ? `${pattern.slice(0, MAX_QUOTED_PATTERN)}…` : pattern;
|
|
288
|
+
return `atlas concept(s) matching "${quoted}":\n\n${blocks.join('\n\n')}`;
|
|
289
|
+
};
|
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 {
|
|
@@ -18,5 +42,7 @@ export {
|
|
|
18
42
|
type ConceptRegistry,
|
|
19
43
|
conceptClass,
|
|
20
44
|
conceptClasses,
|
|
45
|
+
type Thesaurus,
|
|
46
|
+
type ThesaurusEntry,
|
|
21
47
|
} from './registry/types.ts';
|
|
22
48
|
export { DEFAULT_KINDS, type DefaultKind } from './vocab/kinds.ts';
|
package/src/registry/types.ts
CHANGED
|
@@ -10,6 +10,14 @@ export type ConceptEntry = Record<string, string[]>;
|
|
|
10
10
|
// from these keys, never an enum atlas ships.
|
|
11
11
|
export type ConceptRegistry = Record<string, ConceptEntry>;
|
|
12
12
|
|
|
13
|
+
// The thesaurus: each concept's phrases, the words people search with when they mean it,
|
|
14
|
+
// and where its doc is. Curated by hand from how people describe the job, so a grep for
|
|
15
|
+
// "seed a user" lands on `primitive:testFactories` and points at the doc to read.
|
|
16
|
+
// `doc` is a `docs:` value as concepts.ts writes it (run through `references.docs`), with an
|
|
17
|
+
// optional `#section`; it defaults to the concept's first `docs:` entry.
|
|
18
|
+
export type ThesaurusEntry = { phrases: string[]; doc?: string };
|
|
19
|
+
export type Thesaurus = Record<string, ThesaurusEntry>;
|
|
20
|
+
|
|
13
21
|
// `class:name` → its class (the prefix). Returns null for a malformed key.
|
|
14
22
|
export const conceptClass = (key: string): string | null => {
|
|
15
23
|
const idx = key.indexOf(':');
|