ai-code-map 0.0.0-stage → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,341 @@
1
+ # Post-alpha execution roadmap
2
+
3
+ > Status: Milestones 1, 1.1, and 1.1.1 are implemented. Alpha.2 adds bounded compiler lifetimes.
4
+ > The alpha.2 release benchmark records the resource decision before Milestone 2.
5
+
6
+ This document turns the high-level backlog into an ordered, measurable delivery plan. `PROJECT.md`
7
+ remains the product and architecture source of truth. The
8
+ [reviewed real-world alpha baseline](../benchmarks/results/alpha-real-world-baseline-2026-08-06.md)
9
+ is the aggregate evidence behind the priorities below; raw runs remain local because they contain
10
+ machine paths and external-project filenames.
11
+
12
+ ## Why this order
13
+
14
+ The alpha proved that the scanner can package, install, and build deterministic artifacts in a stable invocation environment. It did not yet prove the full product thesis.
15
+
16
+ Three gates remain, and they depend on one another:
17
+
18
+ 1. The semantic map must be correct and independent of the caller's working directory.
19
+ 2. The query result given to an AI must be bounded and smaller than indiscriminate source reading.
20
+ 3. Task-level experiments must show that the bounded map improves retrieval or planning in practice.
21
+
22
+ Building MCP, watch mode, cloud features, or a natural-language command before these gates would expose an unstable foundation through more interfaces.
23
+
24
+ ## Delivery sequence
25
+
26
+ | Order | Milestone | Product question answered | Exit signal |
27
+ | ----: | ----------------------------------- | ------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
28
+ | 1 | Semantic correctness | Does the same project always produce the same correct semantic map? | CWD-independent, per-config results pass unit and real-repo gates |
29
+ | 1.1 | Correctness and freshness hardening | Can persisted semantic evidence be trusted and safely reused? | Complete input closure, artifact integrity, provenance, and relation gates pass |
30
+ | 2 | Bounded context and query | Can an agent retrieve useful facts within a strict budget? | Compact output is bounded, ranked, explicit about omissions |
31
+ | 3 | Real-world regression baseline | Did correctness and context work improve the measured alpha? | Reproducible comparison report on the same three repositories |
32
+ | 4 | Task-level AI evaluation | Does the map save tokens/time without harming plan quality? | Controlled A/B results across a labeled task set |
33
+ | 5 | Product and integration expansion | Which interface should carry the proven capability? | Evidence-based choice of MCP, watch mode, framework work, and commercial features |
34
+
35
+ ## Milestone 1 — semantic correctness
36
+
37
+ Priority: **P0**.
38
+
39
+ ### Outcome
40
+
41
+ `--root` and the discovered TypeScript configuration graph completely determine the semantic environment. The process working directory, scanner checkout, and global/ambient packages outside the selected project cannot change canonical results.
42
+
43
+ Every indexed TypeScript or JavaScript file is analyzed exactly once under a deterministic owning compiler unit. Project references, extended configurations, workspace boundaries, and uncovered files are handled explicitly rather than being flattened into one accidental `Program`.
44
+
45
+ ### Behavioral contract
46
+
47
+ #### 1. Working-directory independence
48
+
49
+ - Identical sources, configuration, CLI arguments, package state, and analyzer versions produce byte-identical canonical artifacts when invoked from unrelated working directories.
50
+ - A second unchanged scan reports an empty change set and `wrote: false`.
51
+ - Compiler hosts and module/type resolution are anchored to the selected compiler unit, never to `process.cwd()` or the scanner installation directory.
52
+ - Stored paths and diagnostics remain project-relative and do not leak absolute paths.
53
+
54
+ #### 2. Compiler configuration graph
55
+
56
+ - Discover applicable `tsconfig.json`, `jsconfig.json`, bounded `tsconfig.*.json` candidates, workspace configs, transitive `extends`, and project `references` within the selected root.
57
+ - Parse configuration through the TypeScript API; do not execute project files or dynamically load JavaScript configuration.
58
+ - Respect each parsed config's `files`, `include`, `exclude`, compiler options, base URL, paths, JavaScript policy, and project references.
59
+ - Reject or diagnose config/reference traversal outside the selected real root.
60
+ - Treat solution-style configs as graph nodes even when they own no files directly.
61
+
62
+ #### 3. Deterministic file ownership
63
+
64
+ - Assign every indexed JS/TS file to one owning compiler unit.
65
+ - Prefer configs that actually include the file; define and document stable precedence for overlaps.
66
+ - Use a safe root-anchored fallback unit for indexed files not owned by any valid config.
67
+ - Analyze an owned file once even when several Programs can see it through imports or references.
68
+ - Preserve cross-unit symbol targets, imports, calls, references, and stable IDs after normalized contributions are merged.
69
+
70
+ #### 4. Freshness completeness
71
+
72
+ The freshness fingerprint must change when a semantic input changes, including:
73
+
74
+ - root, owning, referenced, or transitively extended TypeScript configs;
75
+ - relevant root/workspace package metadata and dependency versions/ranges;
76
+ - relevant workspace manifests and lockfiles;
77
+ - the normalized compiler-unit graph and ownership decisions;
78
+ - TypeScript, semantic resolver, syntax parser, analyzer, rule-pack, configuration, and schema versions.
79
+
80
+ An unchanged graph must keep the same fingerprint. Changing output location alone must not silently change semantic facts.
81
+
82
+ #### 5. Resource discipline
83
+
84
+ - Do not retain every large TypeScript `Program` and `TypeChecker` after its unit has been normalized when they are no longer needed.
85
+ - Make unit processing order deterministic.
86
+ - Record or document the chosen Program lifecycle and its cross-unit trade-offs.
87
+ - On the same machine and protocol, no representative repository may regress more than 10% above its alpha peak-RSS baseline without an explicit, documented decision.
88
+ - Scan time regressions above 15% require investigation and explanation; correctness takes priority over speed.
89
+
90
+ #### 6. Safety and compatibility
91
+
92
+ - Never execute scanned application code, config files, plugins, or package scripts.
93
+ - Preserve the public alpha CLI flow and existing default React/TypeScript analyzers.
94
+ - Preserve custom semantic-resolver compatibility where practical; if a contract must evolve, provide a compatibility path and document it.
95
+ - Keep Tree-sitter/ast-grep development-only during this milestone.
96
+ - Treat persisted schema changes explicitly: regenerate checked-in schemas, bump compatibility versions when required, and produce actionable rescan errors.
97
+
98
+ ### Required acceptance scenarios
99
+
100
+ The permanent suite should contain the smallest non-redundant set of high-signal fixtures covering these distinct risks:
101
+
102
+ 1. Scan one fixture from its own directory and two unrelated directories containing conflicting ambient types; canonical results are identical.
103
+ 2. Two workspace packages use the same path-alias spelling for different local targets; each resolves to its own target.
104
+ 3. An application references a library project; definitions and cross-project calls resolve without duplicate persisted files or symbols.
105
+ 4. A root browser config and a sibling Node/tooling config own different files in the same package.
106
+ 5. Overlapping configs choose the same documented owner independent of discovery order.
107
+ 6. An indexed orphan file enters a fallback unit and remains analyzable.
108
+ 7. Changing an extended or referenced config makes `check` stale; an unchanged rescan performs no write.
109
+ 8. An out-of-root config reference or symlink is rejected or safely diagnosed without indexing outside content.
110
+
111
+ Each important test must identify a plausible faulty implementation it rejects. Tests should assert public API, CLI, and persisted behavior rather than private helper structure.
112
+
113
+ ### Real-project gates
114
+
115
+ Run the established protocol, writing maps only to a temporary directory and leaving target repositories untouched:
116
+
117
+ | Project | Alpha relations | Alpha peak RSS | Known configuration case |
118
+ | --------------- | --------------: | -------------: | ------------------------------------------------------ |
119
+ | `shade-factory` | 27,920 | 1,133 MiB | root config plus excluded nested TypeScript projects |
120
+ | `crm-back` | 19,852 | 1,312 MiB | ambient type resolution changed with caller CWD |
121
+ | `crm-front` | 31,199 | 884 MiB | root config plus a separate Node/tooling configuration |
122
+
123
+ Required results:
124
+
125
+ - target-root and scanner-root invocations produce identical canonical outputs;
126
+ - all repeated scans are current and report `wrote: false`;
127
+ - compiler-unit ownership is inspectable and explains the known multi-config cases;
128
+ - no new non-asset unresolved-import regression appears;
129
+ - peak RSS and elapsed time are compared with the alpha baseline;
130
+ - target repositories remain byte-for-byte and Git-status clean.
131
+
132
+ ### Deliverables
133
+
134
+ - compiler-unit discovery, ownership, and semantic coordination implementation;
135
+ - normalized compiler-unit metadata in an appropriate public or diagnostic representation;
136
+ - freshness hashing for the complete semantic input graph;
137
+ - independent behavioral tests and updated test contract;
138
+ - schema, API, limitation, architecture, and artifact documentation updates as applicable;
139
+ - a before/after benchmark report using the existing protocol.
140
+
141
+ ### Non-goals
142
+
143
+ - compact context selection or a natural-language task command;
144
+ - MCP, watch mode, cloud synchronization, authentication, billing, or telemetry;
145
+ - enabling experimental Next.js or NestJS analyzers by default;
146
+ - promoting Tree-sitter/ast-grep into the production scan path;
147
+ - embeddings, vector search, or an LLM inside deterministic map generation.
148
+
149
+ ### Exit criteria
150
+
151
+ Milestone 1 is complete only when:
152
+
153
+ - all acceptance scenarios pass;
154
+ - `pnpm test` and optional framework tests pass;
155
+ - typecheck, lint, formatting, schema synchronization, build, and package smoke checks pass;
156
+ - the three real repositories pass the CWD-invariance and freshness checks;
157
+ - resource measurements and any regression are documented;
158
+ - an independent validator confirms behavior from this contract, not from the implementation.
159
+
160
+ ## Milestone 1.1 — semantic correctness and freshness hardening
161
+
162
+ Priority: **P0, complete (2026-08-07)**.
163
+
164
+ Milestone 1.1 closed the correctness gaps found during the first compiler-unit rollout:
165
+
166
+ - freshness now records compiler-consumed in-root files, project/toolchain-scoped file/directory/readability probes, directory listings, symlink mappings, and exact consumed TypeScript library bytes, including unindexed imports and nested package metadata;
167
+ - default reuse validates the complete artifact set, cross-record invariants, companion byte hashes, a manifest integrity hash, and a stable built-in producer fingerprint;
168
+ - scan and check use the same raw-byte source hash;
169
+ - project-reference package imports can resolve to referenced source without prebuilt declarations or a test-only `paths` alias;
170
+ - indexed JavaScript excluded by configured `allowJs` policy receives deterministic fallback analysis and a portable diagnostic;
171
+ - compiler-unit namespaces, persisted paths, non-spoofable extension isolation, external call identities, React default-import renders, and relation occurrence identity are hardened;
172
+ - the schema was version 3 and older maps received an actionable rescan path.
173
+
174
+ Evidence:
175
+
176
+ - [behavioral contract](../tests/TEST_CONTRACT.md#milestone-11-semantic-correctness-and-freshness-hardening-contract)
177
+ - [real-world benchmark and Milestone 1 comparison](../benchmarks/results/milestone-1-1-real-world-2026-08-06.md)
178
+ - independent public-fixture regression coverage for relation provenance and occurrence identity
179
+
180
+ Warm scans remain 89.8–94.9% faster than fresh scans in the final recorded run. Correctness has measurable cost: all three targets crossed the fresh-time investigation threshold, and `crm-front` remains above the prior RSS gate. Those regressions are documented rather than traded for weaker freshness or evidence and remain an explicit input to Milestone 2 resource work.
181
+
182
+ ## Milestone 1.1.1 — correctness closure and release-grade validation
183
+
184
+ Priority: **P0, implementation complete; resource closure in alpha.2**.
185
+
186
+ This closure requires checker-identity import provenance, occurrence-preserving React evidence,
187
+ raw-byte artifact repair, canonical integrity helpers, redundant ownership validation, portable
188
+ alias/custom identifiers, root-level composite reference resolution, complete JavaScript fallback
189
+ diagnostics, and endpoint-honest unresolved audit grouping. Schema v4 adds `compilerUnit` and `lines`
190
+ to every manifest source entry and therefore requires a rescan.
191
+
192
+ The release benchmark now runs the packed `dist` CLI from target, packaged-scanner, and unrelated
193
+ working directories; requires byte-identical fresh outputs; records at least three fresh and warm
194
+ isolated samples; and reports median/range wall time, internal time, RSS, artifact/manifest sizes,
195
+ semantic-input counts, relation-quality groupings, package checksum, exact commands, source snapshot,
196
+ and Git state. Dirty-tree results are provisional; an official clean-commit run requires explicit
197
+ commit authorization. The alpha RSS gates remain 1,246 MiB, 1,443 MiB, and 972 MiB respectively;
198
+ both `crm-back` and `crm-front` were above them in the prior M1.1 measurements, so go/no-go cannot be
199
+ implied by correctness alone.
200
+
201
+ Both the provisional and subsequent clean-commit August runs exceeded all three RSS gates.
202
+ Alpha.2 addresses the measured cause: compiler heaps remained resident across units and through
203
+ serialization. Default scans now run each compiler unit in a sequential worker and wait for its
204
+ exit before continuing. A local V8 collection before handoff prevents the result clone from
205
+ overlapping the unreachable compiler heap. Only normalized records return to the coordinator. The worker uses
206
+ TypeScript's type-information JSDoc mode, which preserves JavaScript JSDoc types; the scanner does
207
+ not expose TypeScript JSDoc prose or semantic link diagnostics. Custom pipelines keep their original
208
+ in-process execution and full JSDoc access. No semantic inputs or artifact checks are removed.
209
+
210
+ The reviewed [alpha.2 release benchmark](../benchmarks/results/release-alpha-2-2026-11-01.md)
211
+ records the clean-commit results, unchanged thresholds, dependency caveats, and release decision.
212
+
213
+ Heuristic/unresolved relations keep inverse records for graph traversal but remain identifiable from
214
+ either endpoint and are excluded from future default compact context unless explicitly requested.
215
+
216
+ ## Milestone 2 — bounded context and query
217
+
218
+ Priority: **P0**, after Milestone 1.
219
+
220
+ ### Outcome
221
+
222
+ Expose a deterministic query layer that returns the smallest useful representation for a symbol or change surface. The full map remains an index and is never presented wholesale as AI context.
223
+
224
+ ### Scope
225
+
226
+ - Add relation direction, type, confidence/classification, and limit filters.
227
+ - Add a compact symbol representation that omits the full file record by default.
228
+ - Rank exact and framework-derived forward relations ahead of heuristic and derived inverse records.
229
+ - Return `truncated`, per-category totals, and omitted counts so absence is never confused with completeness.
230
+ - Support a replaceable token estimator and a hard output budget.
231
+ - Compare the compact map representation with the relevant source slice and choose source when it is smaller.
232
+ - Keep task-language interpretation outside the deterministic core; the first query API should accept structured selectors and constraints.
233
+
234
+ ### Initial quality gates
235
+
236
+ - Output never exceeds the requested budget except for a documented indivisible minimum record.
237
+ - Stable inputs and options produce byte-identical results.
238
+ - A 20-relation compact representation stays close to the successful baseline simulation rather than current unbounded `show` sizes.
239
+ - High-degree symbols do not crowd out their own signature, framework facts, or highest-confidence neighbors.
240
+ - Unknown, ambiguous, empty, and over-budget queries return explicit metadata and actionable errors.
241
+
242
+ ### Non-goals
243
+
244
+ - claiming task-level token savings before Milestone 4;
245
+ - hiding truncation;
246
+ - making an LLM call from `scan` or the query engine;
247
+ - treating a character-count proxy as a real tokenizer measurement.
248
+
249
+ ## Milestone 3 — real-world regression baseline
250
+
251
+ Priority: **P0**, immediately after bounded context exists.
252
+
253
+ ### Outcome
254
+
255
+ Repeat the exact alpha protocol on the same repository revisions and publish a comparable report.
256
+
257
+ ### Measurements
258
+
259
+ - indexed files, symbols, relations, diagnostics, and artifact sizes;
260
+ - fresh and repeated scan time;
261
+ - isolated-process peak RSS;
262
+ - CWD and installation-location invariance;
263
+ - config-unit ownership and freshness behavior;
264
+ - current `show`, compact query, selected source, and final chosen-context token counts using a real tokenizer;
265
+ - evidence spot-checks plus labeled precision/recall fixtures where available;
266
+ - package tarball installation and CLI smoke tests.
267
+
268
+ The report must separate regressions, intended semantic corrections, and representation/storage changes. Relation-count changes alone are not automatically improvements.
269
+
270
+ ## Milestone 4 — task-level AI evaluation
271
+
272
+ Priority: **P1**, only after Milestones 1–3 pass.
273
+
274
+ ### Hypothesis
275
+
276
+ For real maintenance tasks, map-first retrieval reduces context and navigation time while maintaining or improving relevant-file recall and plan quality.
277
+
278
+ ### Experimental design
279
+
280
+ Build a labeled set of approximately 12–20 tasks across React, Next.js, Node.js, and NestJS projects. Include feature work, bug localization, impact analysis, and cross-layer changes. For each task, record the expected files/symbols and a review rubric before running agents.
281
+
282
+ Compare at least:
283
+
284
+ - **control:** normal repository search and source reading;
285
+ - **map-first:** bounded map query, followed by source verification;
286
+ - optionally, **file-tree summary:** a cheap non-semantic baseline.
287
+
288
+ Use the same model, instructions, tool access, repository revision, and context ceiling. Randomize task order where practical and keep evaluators blind to the arm.
289
+
290
+ ### Pilot setup lessons (2026-11-01)
291
+
292
+ - Check CLI/model compatibility before collecting task results. Codex CLI `0.135.0` rejected
293
+ `gpt-6-astra`; the pilot used CLI `0.166.0` in a temporary directory without changing the global
294
+ installation. Preserve the selected model when repairing the runner.
295
+ - Use physical dependency copies inside each temporary project root, preserving internal package
296
+ symlinks. An external `node_modules` symlink increased unresolved-import diagnostics and invalidated
297
+ the initial setup. After replacing it, all six map companion artifacts matched the reference
298
+ byte for byte. Source discovery must still exclude dependency files.
299
+ - Fix tasks, scoring criteria, repeats, and a stopping budget before measured runs. Record failed
300
+ setup attempts separately; do not hide their overhead or mix them with valid A/B results. Keep
301
+ the original deadline when repairing the environment.
302
+ - Record actual input, cached-input, and output usage. Cached input is a subset of input, not an
303
+ additional token count. Report map construction separately when using prebuilt maps.
304
+ - Keep private source excerpts and raw agent logs out of public benchmark reports.
305
+
306
+ ### Primary metrics
307
+
308
+ - input and output tokens measured by the actual model/tokenizer;
309
+ - time to identify the first relevant file and time to final plan;
310
+ - relevant-file and relevant-symbol recall/precision;
311
+ - plan completeness, factual correctness, and unsupported claims under a fixed rubric;
312
+ - unnecessary files opened and repeated reads;
313
+ - failure rate when the map is incomplete or stale.
314
+
315
+ ### Decision rule
316
+
317
+ Do not market a token-saving percentage from simulated records. A claim is justified only if the task-level study shows a consistent improvement and reports the model, task set, protocol, sample size, and variance.
318
+
319
+ ## Milestone 5 — integrations and product expansion
320
+
321
+ Use Milestone 4 evidence to select the next surface rather than building every surface at once.
322
+
323
+ Likely order:
324
+
325
+ 1. read-only stdio MCP tools over the stable structured query API;
326
+ 2. watch mode and reusable TypeScript builder state for lower repeated-query latency;
327
+ 3. Next.js `src/app` and `src/pages` correctness, then independently validated NestJS maturity;
328
+ 4. optional local lexical/graph indexes when profiling shows that JSONL scans are the bottleneck;
329
+ 5. CI impact reports and team/shared-map workflows;
330
+ 6. commercial features such as hosted history, pull-request risk review, organization policies, collaboration, and usage analytics—with explicit privacy boundaries.
331
+
332
+ Tree-sitter remains a measured optimization candidate. Promote it only if repository-level experiments demonstrate a meaningful performance, recovery, or maintenance benefit after accounting for the still-required TypeScript semantic pass.
333
+
334
+ ## Release checkpoints
335
+
336
+ - **Correctness candidate:** Milestone 1 complete and independently validated.
337
+ - **Useful-context candidate:** Milestones 1–3 complete with bounded query evidence.
338
+ - **Product-proof candidate:** Milestone 4 complete with reproducible task-level results.
339
+ - **Integration beta:** selected Milestone 5 interface built on the proven query contract.
340
+
341
+ Tags, publication, deployment, and commercial claims require an explicit maintainer decision; completion of a milestone does not perform them automatically.
package/docs/schema.md ADDED
@@ -0,0 +1,133 @@
1
+ # Data schema quick reference
2
+
3
+ This document summarizes public record shapes in plain terms.
4
+
5
+ Canonical persisted records use schema version `4`. Schema v4 requires a rescan because manifest
6
+ source entries now redundantly bind compiler ownership and line counts.
7
+
8
+ ## Config schema (`config.schema.json`)
9
+
10
+ `init` writes a complete configuration with these fields. The runtime schema also supplies defaults when fields are omitted:
11
+
12
+ - `version: 1`
13
+ - `root: string`
14
+ - `include: string[]`
15
+ - `exclude: string[]`
16
+ - `frameworks: Array<"auto"|"typescript"|"node"|"react"|"nextjs"|"nestjs">`
17
+ - `output: string`
18
+ - `includePrivateSymbols: boolean`
19
+
20
+ Optional:
21
+
22
+ - `tsconfig: string`
23
+ - `concurrency: number` (1..64)
24
+
25
+ Defaults are provided by `initProject`/`createDefaultConfig`.
26
+
27
+ ## FileRecord shape
28
+
29
+ ```text
30
+ id, path, language, frameworks, compilerUnit, hash, lines
31
+ imports: [{ source, specifiers, resolved, external, kind, line }]
32
+ exports: [{ name, local, source, default, typeOnly }]
33
+ symbolIds: string[]
34
+ env: string[]
35
+ operations: [{ kind, api, line }]
36
+ syntax: { parser, factCount, hadErrors, fallbackFrom? }
37
+ ```
38
+
39
+ ## CompilerUnitRecord shape
40
+
41
+ ```text
42
+ id, kind, root, config?
43
+ references, extends, pathAliases
44
+ ```
45
+
46
+ `kind` is `configured` or `fallback`.
47
+
48
+ Exactly one `fallback` compiler unit must exist (it may own zero files).
49
+ Configured and generated IDs occupy different namespaces, so a real config named `fallback` cannot collide with the generated fallback unit.
50
+
51
+ ## ProjectRecord shape
52
+
53
+ `ProjectRecord.compilerUnits[]` holds the full ownership config graph.
54
+ `ProjectRecord.tsconfig` and `ProjectRecord.pathAliases` remain compatibility projections.
55
+
56
+ ## SymbolRecord shape
57
+
58
+ ```text
59
+ id, name, kind, file, range, exported, defaultExport?
60
+ signature?, documentation?, facts, sourceHash
61
+ ```
62
+
63
+ ## RelationRecord shape
64
+
65
+ ```text
66
+ from, type, to, confidence
67
+ origin{ file, line, range, explanation, classification, analyzer }
68
+ ```
69
+
70
+ `confidence` is expected to stay in `[0, 1]`.
71
+
72
+ `origin` also contains a full `range`, required `explanation`, producing `analyzer`, and `classification` (`exact`, `framework-derived`, `heuristic`, or `derived`).
73
+
74
+ `from`/`to`/`type` are normalised before write and then merged globally across compiler units.
75
+ Semantic relation identity additionally includes the origin file and full start/end range. Two calls on one line remain distinct, while competing analyzer contributions for the same semantic evidence range collapse deterministically.
76
+
77
+ ## ManifestRecord shape
78
+
79
+ ```text
80
+ schemaVersion, analyzerVersion, producer
81
+ semanticResolver, syntaxParser, analyzers
82
+ configHash, sourceFiles, semanticInputs, artifacts, integrityHash
83
+ ```
84
+
85
+ `sourceFiles` entries are `{ path, hash, compilerUnit, lines }`. `loadCodeMap` cross-checks all four
86
+ fields against `files.jsonl`; this catches one-sided coherent ownership or line-count rewrites. The
87
+ integrity model remains tamper-evident rather than authenticated: an actor rewriting every redundant
88
+ record and hash can still construct a different self-consistent map.
89
+
90
+ `semanticInputs` is a discriminated union:
91
+
92
+ ```text
93
+ { path, kind: "file", hash }
94
+ { path, kind: "resolution-probe", scope, targetKind, exists }
95
+ { path, kind: "directory-listing", scope, hash }
96
+ { path, kind: "symlink", scope, target }
97
+ { path, kind: "toolchain-file", hash }
98
+ ```
99
+
100
+ File and toolchain hashes always cover raw bytes. Resolution probes distinguish file, directory, and readable-file observations; `scope` is `project` or `toolchain`, so an absent TypeScript-library candidate cannot collide with a project path or disappear from freshness. Directory listings cover only compiler-observed child-directory names, and symlink records store an in-scope logical target or the opaque `<outside-root>` boundary marker. `artifacts` exactly covers every non-manifest companion using raw-byte SHA-256; `integrityHash` binds the remaining manifest fields, including producer identity and the semantic closure.
101
+
102
+ ## Freshness contract
103
+
104
+ Freshness eligibility combines these manifest fields:
105
+
106
+ - `configHash`: normalized scanner semantics, compiler-unit ownership, all config/`extends`/`references` inputs, and selected root/workspace manifests, dependency ranges, and lockfiles
107
+ - `semanticInputs`: compiler-observed in-root files; project/toolchain-scoped resolution probes, directory listings, and symlink mappings; and versioned TypeScript library bytes outside the persisted source inventory
108
+ - `producer`, component records, and version fields: built-in capability plus analyzer/parser/resolver/TypeScript/schema identity
109
+ - `artifacts` and `integrityHash`: every companion artifact's exact raw-byte hash plus integrity binding for manifest metadata
110
+
111
+ Paths in persisted facts and manifests are normalized as selected-root-relative. Stored paths reject
112
+ embedded drive/foreign-absolute forms as well as absolute and parent-traversing paths.
113
+ Runtime validation also cross-checks canonical compiler-unit identities and references, redundant
114
+ manifest/file ownership and line counts, file/symbol ownership, import records and import relations,
115
+ counts, endpoint existence, source hashes, ranges/lines, relation evidence, and containment/export
116
+ origin ownership.
117
+
118
+ Zod schemas in `src/schemas.ts` are the runtime/type source of truth. Checked-in Draft 2020-12 schemas under `schemas/` and `config.schema.json` are generated with `pnpm schema:generate` and verified with `pnpm schema:check`.
119
+
120
+ ## DiagnosticRecord shape
121
+
122
+ ```text
123
+ code, severity, message, file?, line?, column?
124
+ ```
125
+
126
+ ## CLI output reference
127
+
128
+ - `init` JSON: `{ root, configPath, created }`
129
+ - `scan` JSON: `{ root, outputDir, wrote, changes, elapsedMs, counts, criticalParseErrors }`
130
+ - `check` JSON: `{ status, current, root, outputDir, reasons, changes }`
131
+ - `show` JSON: `{ selector, matches }`
132
+
133
+ `show.matches[n] = { symbol, file, inbound, outbound }`.
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ ROOT=${1:-.}
5
+
6
+ pnpm exec ai-code-map init --root "$ROOT"
7
+ pnpm exec ai-code-map scan --root "$ROOT" --json
8
+ pnpm exec ai-code-map check --root "$ROOT" --json
9
+ pnpm exec ai-code-map show Calculator --root "$ROOT" --json
@@ -0,0 +1,33 @@
1
+ import {
2
+ checkFreshness,
3
+ createAnalyzer,
4
+ initProject,
5
+ loadCodeMap,
6
+ type FreshnessResult,
7
+ type ScanResult,
8
+ scanProject,
9
+ type ShowResult,
10
+ showSymbol,
11
+ NextJsAnalyzer,
12
+ NestJsAnalyzer,
13
+ } from "ai-code-map";
14
+
15
+ const root = process.cwd();
16
+
17
+ await initProject({ root });
18
+ const scan: ScanResult = await scanProject({ root });
19
+ console.log("scanned:", scan.counts);
20
+
21
+ const map = await loadCodeMap({ root });
22
+ const match: ShowResult = showSymbol(map, "Calculator");
23
+ console.log("calculator matches:", match.matches.length);
24
+
25
+ const freshness: FreshnessResult = await checkFreshness({ root });
26
+ console.log("fresh:", freshness.current, freshness.reasons);
27
+
28
+ const analyzer = createAnalyzer({
29
+ // Experimental and default-off in the alpha; opt in only for evaluation.
30
+ analyzers: [new NextJsAnalyzer(), new NestJsAnalyzer()],
31
+ });
32
+ await analyzer.scan({ root, output: ".ai/code-map-advanced" });
33
+ console.log("advanced scan complete");
package/package.json CHANGED
@@ -1,6 +1,82 @@
1
1
  {
2
2
  "name": "ai-code-map",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.3",
4
+ "description": "Local, deterministic semantic code maps for AI coding agents",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "author": "ai-code-map contributors",
9
+ "keywords": [
10
+ "static-analysis",
11
+ "typescript",
12
+ "javascript",
13
+ "react",
14
+ "nextjs",
15
+ "nestjs",
16
+ "ai"
17
+ ],
18
+ "engines": {
19
+ "node": ">=22"
20
+ },
21
+ "bin": {
22
+ "ai-code-map": "./dist/cli.js"
23
+ },
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ },
31
+ "./config.schema.json": "./config.schema.json",
32
+ "./schemas/*": "./schemas/*",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "config.schema.json",
38
+ "schemas",
39
+ "docs",
40
+ "examples",
41
+ "README.md",
42
+ "AGENTS.md",
43
+ "skills",
44
+ "LICENSE",
45
+ "CONTRIBUTING.md",
46
+ "SECURITY.md",
47
+ "CHANGELOG.md"
48
+ ],
49
+ "dependencies": {
50
+ "@manypkg/get-packages": "^3.1.0",
51
+ "commander": "^14.0.0",
52
+ "fast-glob": "^3.3.3",
53
+ "ignore": "^7.0.6",
54
+ "typescript": "^5.9.2",
55
+ "zod": "^4.0.0"
56
+ },
57
+ "devDependencies": {
58
+ "@ast-grep/napi": "0.45.0",
59
+ "@eslint/js": "^9.32.0",
60
+ "@types/node": "^22.17.0",
61
+ "eslint": "^9.32.0",
62
+ "prettier": "^3.6.2",
63
+ "tsup": "^8.5.0",
64
+ "tsx": "^4.20.3",
65
+ "typescript-eslint": "^8.39.0",
66
+ "vitest": "^3.2.4"
67
+ },
68
+ "scripts": {
69
+ "build": "tsup",
70
+ "lint": "eslint .",
71
+ "typecheck": "tsc --noEmit",
72
+ "test": "vitest run",
73
+ "test:watch": "vitest",
74
+ "format": "prettier --write .",
75
+ "format:check": "prettier --check .",
76
+ "schema:generate": "node --import tsx scripts/generate-schemas.ts",
77
+ "schema:check": "node --import tsx scripts/generate-schemas.ts --check",
78
+ "benchmark": "node --import tsx scripts/benchmark-parsers.ts",
79
+ "benchmark:real-world": "node --import tsx scripts/benchmark-real-world.ts",
80
+ "benchmark:tokens": "node --import tsx scripts/benchmark-tokens.ts"
81
+ }
6
82
  }