Skip to content

feat(state-dir): .codemap/ directory consolidation + self-healing files (impl of PR #53 plan)#54

Merged
SutuSebastian merged 7 commits intomainfrom
feat/codemap-dir
May 3, 2026
Merged

feat(state-dir): .codemap/ directory consolidation + self-healing files (impl of PR #53 plan)#54
SutuSebastian merged 7 commits intomainfrom
feat/codemap-dir

Conversation

@SutuSebastian
Copy link
Copy Markdown
Contributor

@SutuSebastian SutuSebastian commented May 3, 2026

Summary

Implementation of PR #53's .codemap/ consolidation plan. Every codemap-managed path now lives under a single configurable state directory (default .codemap/); the per-feature root .gitignore patching surface is collapsed to zero via the self-healing .codemap/.gitignore reconciler.

Tracers

  1. application/state-dir.tsresolveStateDir({root, cliFlag, env}) per plan §D7; ResolvedCodemapConfig gains stateDir; databasePath defaults to <state-dir>/index.db. loadUserConfig now reads <state-dir>/config.{ts,js,json} (D8). Legacy <root>/.codemap.db + <root>/codemap.config.* paths dropped (pre-v1, no shim per D2). Bootstrap surfaces --state-dir + CODEMAP_STATE_DIR. Extracted bootstrap-codemap.ts helper consolidates the dance from 9 cmd-* files. 12 unit tests.
  2. ensureStateGitignore — self-healing reconciler in state-dir.ts (D11). Pure {before, after, written} shape; idempotent; rewrites user-edited files back to canonical (file is codemap-managed, header line declares it). 5 unit tests including older-version self-heal.
  3. ensureStateConfigapplication/state-config.ts (new). JSON: prune unknown keys with console.warn, alphabetical key sort, write only on drift. TS/JS: validate-only — never rewrites user code. 8 unit tests.
  4. Bootstrap orchestrationbootstrap-codemap.ts runs reconcilers before loadUserConfig. agents-init.ts's ensureGitignoreCodemapPattern rewritten to delegate to ensureStateGitignore — root .gitignore no longer touched.
  5. Docs sync + repo dogfood — README, docs/architecture.md § User config, docs/glossary.md (new entries for <state-dir>, CODEMAP_STATE_DIR, self-healing files), .agents/ + templates/agents/ rule + skill (Rule 10 lockstep). Repo's own root .gitignore slimmed (codemap entries removed); .codemap/.gitignore checked in (canonical content). fixtures/minimal/ dogfooded too. Plan deleted; minor changeset.

Smoke

```
$ rm -rf /tmp/cm-smoke && mkdir -p /tmp/cm-smoke/src && echo "export const x = 1;" > /tmp/cm-smoke/src/a.ts
$ codemap --root /tmp/cm-smoke
$ ls -la /tmp/cm-smoke/.codemap/
.gitignore index.db index.db-shm index.db-wal
```

Single boot creates the state-dir + self-healing .gitignore + index DB; root .gitignore is untouched.

Self-healing principle (D11) in action

Future PRs that add a new generated cache:

  1. Add the path to STATE_GITIGNORE_BODY (one line)
  2. Ship the feature

Every consumer's <state-dir>/.gitignore repairs itself on next codemap boot. No agents init re-run, no manual .gitignore edits, no migration script. The setup logic IS the migration.

Same for the JSON config schema (ensureStateConfig prunes removed fields, fills missing defaults via Zod, key-sorts).

Test plan

  • CodeRabbit reviews state-dir resolution precedence (D7), JSON reconciler edge cases (D8), ensureStateGitignore overwrite semantics (D11), and the bootstrap-codemap.ts ordering (reconcilers before loadUserConfig).
  • CI green on all 714 tests.

Pre-v1 cleanup for existing dev clones

  • `rm .codemap.db .codemap.db-shm .codemap.db-wal` once
  • If you have `/codemap.config.{ts,json}`: `mv codemap.config.ts .codemap/config.ts`
  • Done — next `codemap` run reconciles `.codemap/.gitignore` automatically

Summary by CodeRabbit

  • New Features

    • Introduced configurable state directory via --state-dir CLI option and CODEMAP_STATE_DIR environment variable.
    • Codemap now auto-reconciles generated files (.gitignore and config) on startup.
  • Refactor

    • Consolidated state artifacts under .codemap/ directory: database moved to .codemap/index.db, configuration to .codemap/config.{ts,js,json}, and gitignore patterns now managed in .codemap/.gitignore.
  • Documentation

    • Updated all guides and architecture documentation to reflect new state directory layout and configuration paths.

- application/state-dir.ts: resolveStateDir({root, cliFlag, env}) per plan §D7. Constants STATE_DIR_DEFAULT='.codemap', STATE_DB_NAME='index.db'. 12 unit tests cover precedence + relative/absolute paths.
- config.ts: ResolvedCodemapConfig gains stateDir; resolveCodemapConfig 3rd arg opts.stateDir; databasePath defaults to <stateDir>/index.db. User-supplied databasePath wins (escape hatch).
- config.ts: loadUserConfig reads <state-dir>/config.{ts,js,json} (D8); legacy <root>/codemap.config.* dropped (pre-v1).
- runtime.ts: getStateDir() getter.
- bootstrap.ts: --state-dir + CODEMAP_STATE_DIR; precedence per D7.
- bootstrap-codemap.ts (new): single helper extracts the loadUserConfig+resolveCodemapConfig+initCodemap+configureResolver dance from 9 cmd-* files. Tracer 4's ensureStateDir attaches here.
- All 9 cmd-* files refactored; stateDir threaded through interfaces + main.ts dispatch + ServerOpts (mcp/serve).
- audit-worktree.ts: cached entries at <sha>/.codemap/index.db (recursive layout — each cached worktree is its own self-contained codemap project).
- audit-engine.ts: makeWorktreeReindex stops hard-coding db path; openCodemapDatabase() reads from initialised runtime.
- sqlite-db.ts: openCodemapDatabase mkdirs the parent (state-dir may not exist on fresh project).

Dogfood:
- .codemap/.gitignore (self-managed, blacklist) — codemap repo + fixtures/minimal/
- root .gitignore: dropped .codemap.* and .codemap/audit-cache/ (nested .gitignore handles them)
- fixtures/minimal/.codemap.db* removed (stale legacy)

703 tests pass.
…er 2)

- STATE_GITIGNORE_BODY constant — single source of truth for the canonical blacklist.
- ensureStateGitignore(stateDir) — pure-shape return ({before, after, written}); idempotent (no write on steady state); auto-mkdir; user-edits rewritten back per D11 (file is codemap-managed; header line declares it).
- 5 tests cover: fresh write, idempotent, user-modified, older-version self-heal, returned shape matches disk.

Bumping STATE_GITIGNORE_BODY in a future PR is the entire migration — every consumer's project repairs itself on next codemap run.
…kill + changeset (Tracer 5)

- README.md: --state-dir flag, config-file location, self-healing callout
- docs/architecture.md: state-dir resolver in src/config.ts intro; bulk .codemap.db → .codemap/index.db; User config section rewritten with self-healing details (ensureStateGitignore + ensureStateConfig from src/application/, single attachment point in cli/bootstrap-codemap.ts)
- docs/glossary.md: new entries for '.codemap/' / <state-dir> / CODEMAP_STATE_DIR; '.codemap/index.db'; '.codemap/.gitignore' / self-healing files
- docs/roadmap.md: drop the consolidated-dir backlog item (it shipped)
- docs/research/fallow.md: Adjacent-shipped bullet referencing PR #53 (plan) + #54 (impl)
- .agents/rules/codemap.md + templates/agents/rules/codemap.md: bulk .codemap.db → .codemap/index.db; one-paragraph addition explaining state-dir + self-healing .gitignore (Rule 10 lockstep)
- .agents/skills/codemap/SKILL.md + templates/agents/skills/codemap/SKILL.md: bulk path update (Rule 10 lockstep)
- .changeset/codemap-dir-consolidation.md: minor — full design rationale + cleanup steps
- docs/plans/codemap-dir-consolidation.md: deleted per docs-governance Rule 3
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 3, 2026

🦋 Changeset detected

Latest commit: c36ad42

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@stainless-code/codemap Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 3, 2026

Warning

Rate limit exceeded

@SutuSebastian has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 43 minutes and 18 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ace0165e-c534-4eb8-b368-ad82be7f04a1

📥 Commits

Reviewing files that changed from the base of the PR and between 5df0e2f and c36ad42.

📒 Files selected for processing (8)
  • .agents/skills/codemap/SKILL.md
  • src/application/audit-worktree.ts
  • src/application/state-dir.test.ts
  • src/cli/bootstrap-codemap.ts
  • src/cli/bootstrap.ts
  • src/cli/main.ts
  • src/config.ts
  • templates/agents/skills/codemap/SKILL.md
📝 Walkthrough

Walkthrough

Codemap consolidates state artifacts into a configurable single directory (default .codemap/), replacing scattered .codemap.db + codemap.config.* locations with .codemap/index.db and .codemap/config.{ts,js,json}. New --state-dir CLI option and CODEMAP_STATE_DIR env var enable overrides. Self-healing reconcilers idempotently ensure .codemap/.gitignore and config file normalization on boot. Centralized bootstrap logic replaces per-command initialization across all CLI commands.

Changes

State Directory Consolidation

Layer / File(s) Summary
State-Dir Primitives
src/application/state-dir.ts, src/application/state-dir.test.ts
New helpers to resolve state dir path with CLI/env/default precedence, constants for DB/gitignore filenames, and ensureStateGitignore idempotent reconciler that writes canonical .gitignore only on drift.
Config Self-Healing
src/application/state-config.ts, src/application/state-config.test.ts
New ensureStateConfig reconciler validates <state-dir>/config.json, prunes unknown keys, sorts keys alphabetically, and rewrites only on drift; TS/JS configs are validate-only.
Config Loading & Paths
src/config.ts, src/config.test.ts
loadUserConfig and resolveCodemapConfig now accept optional stateDir parameter; default database path moves to <stateDir>/index.db; config file lookup targets <state-dir>/config.{ts,js,json} via new STATE_CONFIG_BASENAMES instead of root-level codemap.config.*.
Bootstrap Centralization
src/cli/bootstrap-codemap.ts, src/cli/bootstrap.ts
New bootstrapCodemap helper centralizes Codemap initialization: resolves state dir, ensures state files, loads user config, initializes runtime, and configures resolver; parseBootstrapArgs now parses --state-dir with env override precedence.
CLI Command Wiring
src/cli/cmd-*.ts, src/cli/main.ts
All 12+ command handlers (context, validate, show, snippet, mcp, watch, serve, impact, audit, query, index, query-drop-baseline, query-list-baselines) refactored to accept stateDir option and delegate bootstrap to bootstrapCodemap(opts) instead of inline initialization; main.ts threads stateDir from parsed args to all command calls.
Application-Level Integration
src/application/http-server.ts, src/application/mcp-server.ts, src/application/audit-engine.ts, src/application/audit-worktree.ts
HTTP/MCP server opts add optional stateDir field and forward to config loading; audit engine refactors DB lifecycle to use openCodemapDatabase() without path args; audit worktree cache updates to detect DB at new <worktree>/.codemap/index.db location.
Runtime & Database
src/runtime.ts, src/sqlite-db.ts
New getStateDir() export returns state dir from resolved config; openCodemapDatabase auto-creates parent directory when needed.
Agents Init Refactor
src/agents-init.ts, src/agents-init.test.ts
ensureGitignoreCodemapPattern now delegates to ensureStateGitignore instead of patching root .gitignore; tests refocused to verify state-dir .gitignore creation and idempotence, root .gitignore untouched.
Documentation & Fixtures
.agents/rules/codemap.md, .agents/skills/codemap/SKILL.md, .changeset/codemap-dir-consolidation.md, .codemap/.gitignore, fixtures/minimal/.codemap/.gitignore, README.md, docs/*.md, templates/*
All docs updated to reference .codemap/index.db instead of .codemap.db, <state-dir>/config.* instead of codemap.config.*, and new state-dir override behavior; deleted design plan (docs/plans/codemap-dir-consolidation.md); .gitignore entries for .codemap.* removed from root; new fixture .gitignore added under .codemap/.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI (main.ts)
    participant Parse as parseBootstrapArgs
    participant Bootstrap as bootstrapCodemap
    participant StateDir as State Dir Helpers
    participant Config as loadUserConfig
    participant Runtime as initCodemap
    participant Cmd as Command Handler

    CLI->>Parse: parseBootstrapArgs(argv)
    Parse-->>CLI: { root, configFile, stateDir, rest }
    
    CLI->>Bootstrap: bootstrapCodemap({ root, configFile, stateDir })
    Bootstrap->>StateDir: resolveStateDir({ root, cliFlag, env })
    StateDir-->>Bootstrap: absoluteStateDirPath
    
    Bootstrap->>StateDir: ensureStateGitignore(stateDir)
    StateDir-->>Bootstrap: { written: bool }
    
    Bootstrap->>StateDir: ensureStateConfig(stateDir)
    StateDir-->>Bootstrap: { found, written, warnings }
    
    Bootstrap->>Config: loadUserConfig(root, configFile, { stateDir })
    Config-->>Bootstrap: userConfig
    
    Bootstrap->>Runtime: initCodemap(resolveCodemapConfig(root, user, { stateDir }))
    Runtime-->>Bootstrap: ready
    
    Bootstrap-->>CLI: initialized
    CLI->>Cmd: runCommand(opts including stateDir)
    Cmd->>Runtime: getStateDir(), openDb(), query()
    Cmd-->>CLI: result
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • PR #53: Implements the planned .codemap/ directory consolidation design from the referenced plan doc, directly realizing the directory state refactor and self-healing reconciliation strategy.
  • PR #4: Modifies agents-init .gitignore handling; the main PR refactors agents-init to delegate gitignore management to state-dir helpers (ensureStateGitignore) rather than patching root .gitignore.
  • PR #30: Updates query baseline storage in SQLite; both PRs coordinate on database path relocation (from .codemap.db to .codemap/index.db) and affect baseline query persistence.

Suggested labels

enhancement, refactor, documentation

Poem

🐰 A burrow for treasures, now neat and aligned,
State sorted in folders, no files left behind,
The database hops to a .codemap/ home,
With .gitignore watching, and configs that roam,
Each command boots faster—consolidation's sweet song! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 64.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(state-dir): .codemap/ directory consolidation + self-healing files (impl of PR #53 plan)' accurately summarizes the main change: implementing directory consolidation with self-healing file reconciliation as planned in PR #53.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/codemap-dir

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 43 minutes and 18 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

…hored comments

Doc staleness sweep (after Tracer 5):
- docs/glossary.md, docs/agents.md, docs/benchmark.md, docs/why-codemap.md, docs/research/competitive-scan-2026-04.md, docs/research/fallow.md (B.6 row): bulk `.codemap.db` → `.codemap/index.db` everywhere except the intentional 'old → new' migration callouts.
- docs/architecture.md, docs/research/fallow.md, docs/packaging.md: `codemap.config.{ts,json}` → `<state-dir>/config.{ts,js,json}`.
- docs/agents.md § Git: rewritten to describe the self-managed <state-dir>/.gitignore reconciler instead of root-.gitignore patching.
- docs/benchmark.md: 'where the DB lives' updated; manual .gitignore note dropped (reconciler handles it).

Concise-comments sweep on this turn's authored comments:
- src/application/state-config.ts: 2 inline comments slimmed (TS/JS-validation-only and passthrough-rationale).
@SutuSebastian
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 3, 2026

✅ Actions performed

Full review triggered.

@SutuSebastian
Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 3, 2026

✅ Actions performed

Full review triggered.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
src/application/audit-worktree.ts (1)

53-53: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Three stale .codemap.db references in JSDoc not updated by this PR.

  • Line 53 (PopulatedCacheEntry.dbPath): "Absolute path to the \.codemap.db` inside that worktree."`
  • Line 126 (PopulateOpts.reindex): "must build \.codemap.db` inside it."`
  • Line 134 (populateWorktree docblock step 3): "builds \.codemap.db`"`

All three should be updated to .codemap/index.db to match the CACHE_ENTRY_DB_REL constant introduced on line 103.

📝 Proposed fix
-  /** Absolute path to the `.codemap.db` inside that worktree. */
+  /** Absolute path to the `.codemap/index.db` inside that worktree. */
   dbPath: string;
-  /** Reindex callback — receives the worktree path, must build `.codemap.db` inside it. */
+  /** Reindex callback — receives the worktree path, must build `.codemap/index.db` inside it. */
   reindex: (worktreePath: string) => Promise<void>;
-   * 3. caller's `reindex(<tmp>)` builds `.codemap.db`
+   * 3. caller's `reindex(<tmp>)` builds `.codemap/index.db`

Also applies to: 126-126, 134-134

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/application/audit-worktree.ts` at line 53, Update the three stale JSDoc
references that still say ".codemap.db" to the new path ".codemap/index.db":
change the comment for PopulatedCacheEntry.dbPath, the doc for
PopulateOpts.reindex, and the step in the populateWorktree docblock to reference
".codemap/index.db" (use the CACHE_ENTRY_DB_REL constant as the canonical
source) so the documentation matches the new CACHE_ENTRY_DB_REL constant
introduced in the file.
src/cli/bootstrap.ts (1)

8-57: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

printCliUsage() has stale .codemap.db references and missing docs for --state-dir / CODEMAP_STATE_DIR.

Three gaps after the --state-dir addition:

  1. Line 11: update .codemap.db → should be .codemap/index.db
  2. Line 35: keeps .codemap.db fresh → should be .codemap/index.db
  3. Line 49: Environment: list omits CODEMAP_STATE_DIR and --state-dir is not listed under Options
📝 Proposed fix
-Index (default): update .codemap.db for the project root (`--root` or cwd).
+Index (default): update .codemap/index.db for the project root (`--root` or cwd).
-Watch mode (long-running; keeps .codemap.db fresh on file edits):
+Watch mode (long-running; keeps .codemap/index.db fresh on file edits):
-Environment: CODEMAP_ROOT (same as --root)
+Environment: CODEMAP_ROOT (same as --root), CODEMAP_STATE_DIR (same as --state-dir)

Add to the Options section:

+  --state-dir DIR     State directory (default .codemap/ under root)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/bootstrap.ts` around lines 8 - 57, Update printCliUsage(): change the
two occurrences of ".codemap.db" to ".codemap/index.db" (the header "Index
(default): update .codemap.db for the project root" and the watch-mode line
"keeps .codemap.db fresh on file edits"); add documentation for --state-dir and
CODEMAP_STATE_DIR in the printed help by adding a new Options bullet for
"--state-dir <DIR>   State directory (overrides CODEMAP_STATE_DIR)" and update
the "Environment:" section to list CODEMAP_STATE_DIR alongside CODEMAP_ROOT so
that printCliUsage() accurately documents the new state-dir flag and environment
variable.
src/config.ts (1)

63-68: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Outdated JSDoc description for databasePath.

The description says "Default: <root>/.codemap.db" but the actual default is now <stateDir>/index.db (line 181). Update the description to reflect the new default location.

📝 Proposed fix
     databasePath: z
       .string()
       .optional()
       .describe(
-        "SQLite database path, relative to root or absolute. Default: `<root>/.codemap.db`.",
+        "SQLite database path, relative to root or absolute. Default: `<state-dir>/index.db`.",
       ),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/config.ts` around lines 63 - 68, The JSDoc for the zod field databasePath
(the describe(...) call on the databasePath schema) is outdated; update its
description string to state the correct default "<stateDir>/index.db" (or
similar wording referencing stateDir) instead of "<root>/.codemap.db" so the
describe(...) on databasePath matches the actual default used elsewhere (e.g.,
the default used when building the state directory and index DB).
src/cli/main.ts (1)

312-314: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Pass stateDir through query --baselines.

Line 313 is the one query dispatch path that still drops stateDir, so codemap query --baselines falls back to the default DB instead of the caller-selected state directory.

Suggested fix
     if (parsed.kind === "listBaselines") {
-      await runListBaselinesCmd({ root, configFile, json: parsed.json });
+      await runListBaselinesCmd({
+        root,
+        configFile,
+        stateDir,
+        json: parsed.json,
+      });
       return;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/main.ts` around lines 312 - 314, The query dispatch for the
"listBaselines" path drops the selected state directory so `codemap query
--baselines` uses the default DB; update the call to runListBaselinesCmd in the
branch where parsed.kind === "listBaselines" to pass the stateDir the same way
other query variants do (include the stateDir variable alongside root,
configFile and json), ensuring runListBaselinesCmd receives the caller-selected
state directory and uses it to open the correct DB.
🧹 Nitpick comments (4)
src/application/state-dir.test.ts (1)

116-126: 💤 Low value

Redundant require for mkdirSync.

mkdirSync is already imported at the top of the file (line 5). The inline require("node:fs") is unnecessary.

♻️ Suggested fix
   it("self-heals when an older codemap version's content is missing today's entries", () => {
     // Older shape — pre-audit-cache: only the DB lines.
     const olderBody =
       "# old codemap-managed file\nindex.db\nindex.db-shm\nindex.db-wal\n";
-    const { mkdirSync } = require("node:fs") as typeof import("node:fs");
     mkdirSync(stateDir, { recursive: true });
     writeFileSync(join(stateDir, ".gitignore"), olderBody, "utf-8");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/application/state-dir.test.ts` around lines 116 - 126, The test
unnecessarily re-requires mkdirSync; remove the inline require and use the
existing top-level import (mkdirSync) instead — edit the test in
src/application/state-dir.test.ts to delete the "const { mkdirSync } =
require('node:fs')" line and keep the call to mkdirSync(stateDir, { recursive:
true }); so the test continues to call mkdirSync and validate
ensureStateGitignore(stateDir) without duplicate imports.
.changeset/codemap-dir-consolidation.md (1)

9-19: 💤 Low value

Consider adding a language specifier to the fenced code block.

The directory tree structure could benefit from a language specifier (e.g., text or plaintext) to satisfy markdown linting rules, though this is purely cosmetic for a tree diagram.

🔧 Suggested fix
-```
+```text
 <root>/
 └── .codemap/                 ← override via --state-dir / CODEMAP_STATE_DIR
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.changeset/codemap-dir-consolidation.md around lines 9 - 19, The markdown
fenced code block showing the directory tree (starting with "<root>/" and
".codemap/") lacks a language specifier; update the opening fence from ``` to a
language-tagged fence such as ```text or ```plaintext so the tree block
satisfies markdown linting rules and renders as plain text.
src/cli/cmd-index.ts (1)

8-14: 💤 Low value

Consider adding JSDoc documentation for runIndexCmd.

Other command handlers (runShowCmd, runWatchCmd, runImpactCmd, etc.) have JSDoc comments describing their behavior. For consistency, runIndexCmd should have similar documentation.

📝 Proposed fix
+/**
+ * Run `codemap index`. Bootstraps codemap, opens db, then indexes files
+ * based on mode: `--files <paths>` for specific files, `--full` for full
+ * rebuild, or incremental by default.
+ */
 export async function runIndexCmd(opts: {

As per coding guidelines, all public APIs must have accompanying documentation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/cmd-index.ts` around lines 8 - 14, Add a JSDoc comment for the
exported async function runIndexCmd describing its purpose, parameters, and
return value (matching style used for runShowCmd/runWatchCmd/runImpactCmd);
mention the opts parameter and its fields (root, configFile, stateDir, rest) and
that the function calls bootstrapCodemap and returns a Promise<void>. Place the
JSDoc immediately above the runIndexCmd declaration and follow the existing
project's JSDoc format and tags.
src/cli/bootstrap-codemap.ts (1)

2-3: 💤 Low value

Consider consolidating imports from the same module.

Both imports are from "../application/state-dir" and can be merged into a single import statement.

♻️ Proposed fix
-import { resolveStateDir } from "../application/state-dir";
-import { ensureStateGitignore } from "../application/state-dir";
+import { ensureStateGitignore, resolveStateDir } from "../application/state-dir";
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/cli/bootstrap-codemap.ts` around lines 2 - 3, The two separate imports
from the same module should be consolidated into a single import statement:
replace the duplicate imports of resolveStateDir and ensureStateGitignore with
one combined import that imports both symbols (resolveStateDir,
ensureStateGitignore) from "../application/state-dir" so they are imported
together in a single line.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@templates/agents/skills/codemap/SKILL.md`:
- Around line 44-48: The doc still hardcodes `.codemap/...` as the state
directory; update wording in SKILL.md to reference the configurable state-dir
(e.g. use `<state-dir>/index.db` and `<state-dir>/recipes/` or explicitly state
“default: .codemap/” where appropriate) so references around
`.codemap/index.db`, `.codemap/recipes/`, and related sentences (mentions of
baselines, recipes, and gitignore behavior) reflect the new configurable
state-dir behavior; keep the CLI flag names (`--save-baseline`, `--baseline`,
`--baselines`, `--drop-baseline`, `--recipes-json`) unchanged and ensure any
place that implied “.codemap is not gitignored” or “.codemap/index.db is
gitignored” is updated to say “<state-dir>/index.db (default:
.codemap/index.db)” or similar.

---

Outside diff comments:
In `@src/application/audit-worktree.ts`:
- Line 53: Update the three stale JSDoc references that still say ".codemap.db"
to the new path ".codemap/index.db": change the comment for
PopulatedCacheEntry.dbPath, the doc for PopulateOpts.reindex, and the step in
the populateWorktree docblock to reference ".codemap/index.db" (use the
CACHE_ENTRY_DB_REL constant as the canonical source) so the documentation
matches the new CACHE_ENTRY_DB_REL constant introduced in the file.

In `@src/cli/bootstrap.ts`:
- Around line 8-57: Update printCliUsage(): change the two occurrences of
".codemap.db" to ".codemap/index.db" (the header "Index (default): update
.codemap.db for the project root" and the watch-mode line "keeps .codemap.db
fresh on file edits"); add documentation for --state-dir and CODEMAP_STATE_DIR
in the printed help by adding a new Options bullet for "--state-dir <DIR>  
State directory (overrides CODEMAP_STATE_DIR)" and update the "Environment:"
section to list CODEMAP_STATE_DIR alongside CODEMAP_ROOT so that printCliUsage()
accurately documents the new state-dir flag and environment variable.

In `@src/cli/main.ts`:
- Around line 312-314: The query dispatch for the "listBaselines" path drops the
selected state directory so `codemap query --baselines` uses the default DB;
update the call to runListBaselinesCmd in the branch where parsed.kind ===
"listBaselines" to pass the stateDir the same way other query variants do
(include the stateDir variable alongside root, configFile and json), ensuring
runListBaselinesCmd receives the caller-selected state directory and uses it to
open the correct DB.

In `@src/config.ts`:
- Around line 63-68: The JSDoc for the zod field databasePath (the describe(...)
call on the databasePath schema) is outdated; update its description string to
state the correct default "<stateDir>/index.db" (or similar wording referencing
stateDir) instead of "<root>/.codemap.db" so the describe(...) on databasePath
matches the actual default used elsewhere (e.g., the default used when building
the state directory and index DB).

---

Nitpick comments:
In @.changeset/codemap-dir-consolidation.md:
- Around line 9-19: The markdown fenced code block showing the directory tree
(starting with "<root>/" and ".codemap/") lacks a language specifier; update the
opening fence from ``` to a language-tagged fence such as ```text or
```plaintext so the tree block satisfies markdown linting rules and renders as
plain text.

In `@src/application/state-dir.test.ts`:
- Around line 116-126: The test unnecessarily re-requires mkdirSync; remove the
inline require and use the existing top-level import (mkdirSync) instead — edit
the test in src/application/state-dir.test.ts to delete the "const { mkdirSync }
= require('node:fs')" line and keep the call to mkdirSync(stateDir, { recursive:
true }); so the test continues to call mkdirSync and validate
ensureStateGitignore(stateDir) without duplicate imports.

In `@src/cli/bootstrap-codemap.ts`:
- Around line 2-3: The two separate imports from the same module should be
consolidated into a single import statement: replace the duplicate imports of
resolveStateDir and ensureStateGitignore with one combined import that imports
both symbols (resolveStateDir, ensureStateGitignore) from
"../application/state-dir" so they are imported together in a single line.

In `@src/cli/cmd-index.ts`:
- Around line 8-14: Add a JSDoc comment for the exported async function
runIndexCmd describing its purpose, parameters, and return value (matching style
used for runShowCmd/runWatchCmd/runImpactCmd); mention the opts parameter and
its fields (root, configFile, stateDir, rest) and that the function calls
bootstrapCodemap and returns a Promise<void>. Place the JSDoc immediately above
the runIndexCmd declaration and follow the existing project's JSDoc format and
tags.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b4c2da28-99d1-4bd6-a0af-3bc9caefdfd0

📥 Commits

Reviewing files that changed from the base of the PR and between b62f308 and 5df0e2f.

📒 Files selected for processing (50)
  • .agents/rules/codemap.md
  • .agents/skills/codemap/SKILL.md
  • .changeset/codemap-dir-consolidation.md
  • .codemap/.gitignore
  • .gitignore
  • README.md
  • docs/README.md
  • docs/agents.md
  • docs/architecture.md
  • docs/benchmark.md
  • docs/glossary.md
  • docs/packaging.md
  • docs/plans/codemap-dir-consolidation.md
  • docs/research/competitive-scan-2026-04.md
  • docs/research/fallow.md
  • docs/roadmap.md
  • docs/why-codemap.md
  • fixtures/minimal/.codemap/.gitignore
  • src/agents-init.test.ts
  • src/agents-init.ts
  • src/application/audit-engine.ts
  • src/application/audit-worktree.test.ts
  • src/application/audit-worktree.ts
  • src/application/http-server.ts
  • src/application/mcp-server.ts
  • src/application/state-config.test.ts
  • src/application/state-config.ts
  • src/application/state-dir.test.ts
  • src/application/state-dir.ts
  • src/cli/bootstrap-codemap.ts
  • src/cli/bootstrap.ts
  • src/cli/cmd-audit.ts
  • src/cli/cmd-context.ts
  • src/cli/cmd-impact.ts
  • src/cli/cmd-index.ts
  • src/cli/cmd-mcp.ts
  • src/cli/cmd-query.ts
  • src/cli/cmd-serve.ts
  • src/cli/cmd-show.ts
  • src/cli/cmd-snippet.ts
  • src/cli/cmd-validate.ts
  • src/cli/cmd-watch.ts
  • src/cli/main.ts
  • src/cli/query-output-benchmark.test.ts
  • src/config.test.ts
  • src/config.ts
  • src/runtime.ts
  • src/sqlite-db.ts
  • templates/agents/rules/codemap.md
  • templates/agents/skills/codemap/SKILL.md
💤 Files with no reviewable changes (3)
  • docs/plans/codemap-dir-consolidation.md
  • docs/roadmap.md
  • .gitignore

Comment thread templates/agents/skills/codemap/SKILL.md Outdated
…f + 2 nitpicks)

Real bug:
- main.ts: runListBaselinesCmd was being called without stateDir — `codemap query --baselines` would fall back to the default DB instead of the caller-selected one. Fixed.

Stale doc refs:
- audit-worktree.ts: 3 JSDoc strings still said `.codemap.db` after Tracer 1's CACHE_ENTRY_DB_REL move; bumped to `.codemap/index.db`.
- bootstrap.ts: printCliUsage() had two `.codemap.db` refs + missing --state-dir/CODEMAP_STATE_DIR docs in Environment+Options. Fixed.
- config.ts: Zod databasePath.describe() said default was `<root>/.codemap.db`; corrected to `<state-dir>/index.db`.
- .agents/skills + templates skills: 2 hard-coded `.codemap/` refs reworded to `<state-dir>/` with `(default .codemap/)` callout (state-dir is configurable).

Nitpicks applied:
- state-dir.test.ts: dropped redundant `require('node:fs')` for mkdirSync (already imported).
- bootstrap-codemap.ts: consolidated two single-import lines from state-dir into one statement.

Nitpicks declined:
- changeset code-fence missing 'text' lang — purely cosmetic.
- cmd-index.ts JSDoc on runIndexCmd — 'all public APIs need JSDoc' is a fabricated rule (sibling cmds inconsistent; same hallucination rejected on PR #50).
@SutuSebastian
Copy link
Copy Markdown
Contributor Author

Triaged 1 inline thread + 4 outside-diff comments + 4 nitpicks per `pr-comment-fact-check`. 7 of 9 actionable; 2 declined.

Real bug found by CodeRabbit (🟠 Major):

  • ✅ `main.ts:312-314` — `runListBaselinesCmd` was being called without `stateDir`; `codemap query --baselines` would have fallen back to the default DB instead of the caller-selected one. Fixed in c36ad42 — verified the cmd-query.ts interface already accepts `stateDir`.

Stale doc refs (🟡 Minor — all applied):

  • `audit-worktree.ts` — 3 stale `.codemap.db` JSDoc strings the Tracer 1 `CACHE_ENTRY_DB_REL` move missed.
  • `bootstrap.ts` `printCliUsage()` — 2 stale `.codemap.db` lines + missing `--state-dir` / `CODEMAP_STATE_DIR` docs in Environment + Options.
  • `config.ts` Zod `databasePath.describe()` — said default was `/.codemap.db`, corrected to `/index.db`.
  • Inline T1 (skill files): both `.agents/` + `templates/` now reference `/...` with `(default .codemap/)` callouts.

Nitpicks applied (2):

  • `state-dir.test.ts` — dropped redundant `require('node:fs')` for `mkdirSync`.
  • `bootstrap-codemap.ts` — consolidated two single-import lines from `state-dir` into one.

Nitpicks declined (2):

  • 💭 Changeset code-fence missing `text` lang specifier — purely cosmetic; markdown renders correctly without it.
  • ❌ `cmd-index.ts` JSDoc on `runIndexCmd` — CodeRabbit cited "all public APIs need JSDoc" as a coding guideline. No such rule exists in `.agents/` (verified via grep — same hallucination I rejected on PR feat(impact): codemap impact — symbol/file blast-radius walker (impl of PR #49 plan) #50 nitpick 3); sibling `cmd-*.ts` exports vary on JSDoc presence (consistent convention is to JSDoc the body fns, not the auto-generated CLI dispatch shells).

714 tests still pass. Ready for re-review or merge.

@SutuSebastian SutuSebastian merged commit 1313fc2 into main May 3, 2026
10 checks passed
@SutuSebastian SutuSebastian deleted the feat/codemap-dir branch May 3, 2026 16:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant