feed-the-machine 1.0.0 → 1.1.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.
Files changed (48) hide show
  1. package/bin/install.mjs +34 -3
  2. package/docs/HOOKS.md +243 -0
  3. package/ftm-dashboard/SKILL.md +129 -0
  4. package/ftm-map/SKILL.md +209 -0
  5. package/ftm-map/scripts/db.py +391 -0
  6. package/ftm-map/scripts/index.py +341 -0
  7. package/ftm-map/scripts/parser.py +455 -0
  8. package/ftm-map/scripts/queries/.gitkeep +0 -0
  9. package/ftm-map/scripts/queries/javascript-tags.scm +23 -0
  10. package/ftm-map/scripts/queries/python-tags.scm +17 -0
  11. package/ftm-map/scripts/queries/typescript-tags.scm +29 -0
  12. package/ftm-map/scripts/query.py +149 -0
  13. package/ftm-map/scripts/requirements.txt +2 -0
  14. package/ftm-map/scripts/setup-hooks.sh +27 -0
  15. package/ftm-map/scripts/setup.sh +45 -0
  16. package/ftm-map/scripts/test_db.py +124 -0
  17. package/ftm-map/scripts/test_parser.py +106 -0
  18. package/ftm-map/scripts/test_query.py +66 -0
  19. package/ftm-map/scripts/tests/fixtures/__init__.py +0 -0
  20. package/ftm-map/scripts/tests/fixtures/sample_project/api.ts +16 -0
  21. package/ftm-map/scripts/tests/fixtures/sample_project/auth.py +15 -0
  22. package/ftm-map/scripts/tests/fixtures/sample_project/utils.js +16 -0
  23. package/ftm-map/scripts/views.py +545 -0
  24. package/ftm-researcher/SKILL.md +220 -0
  25. package/ftm-researcher/evals/agent-diversity.yaml +17 -0
  26. package/ftm-researcher/evals/synthesis-quality.yaml +12 -0
  27. package/ftm-researcher/evals/trigger-accuracy.yaml +39 -0
  28. package/ftm-researcher/references/adaptive-search.md +116 -0
  29. package/ftm-researcher/references/agent-prompts.md +193 -0
  30. package/ftm-researcher/references/council-integration.md +193 -0
  31. package/ftm-researcher/references/output-format.md +203 -0
  32. package/ftm-researcher/references/synthesis-pipeline.md +165 -0
  33. package/ftm-researcher/scripts/score_credibility.py +234 -0
  34. package/ftm-researcher/scripts/validate_research.py +92 -0
  35. package/ftm-routine/SKILL.md +134 -0
  36. package/ftm-upgrade/scripts/check-version.sh +1 -1
  37. package/ftm-upgrade/scripts/upgrade.sh +1 -1
  38. package/hooks/ftm-blackboard-enforcer.sh +94 -0
  39. package/hooks/ftm-discovery-reminder.sh +90 -0
  40. package/hooks/ftm-drafts-gate.sh +61 -0
  41. package/hooks/ftm-event-logger.mjs +107 -0
  42. package/hooks/ftm-map-autodetect.sh +79 -0
  43. package/hooks/ftm-pending-sync-check.sh +22 -0
  44. package/hooks/ftm-plan-gate.sh +96 -0
  45. package/hooks/ftm-post-commit-trigger.sh +57 -0
  46. package/hooks/settings-template.json +81 -0
  47. package/install.sh +140 -11
  48. package/package.json +7 -1
package/bin/install.mjs CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * npx ftm-skills — installs ftm skills into ~/.claude/skills/
4
+ * npx feed-the-machine — installs ftm skills into ~/.claude/skills/
5
5
  *
6
6
  * Works by finding the npm package root (where the skill files live)
7
7
  * and symlinking them into the Claude Code skills directory.
8
8
  */
9
9
 
10
- import { existsSync, mkdirSync, readdirSync, lstatSync, readFileSync, writeFileSync, copyFileSync, symlinkSync, unlinkSync } from "fs";
10
+ import { existsSync, mkdirSync, readdirSync, lstatSync, readFileSync, writeFileSync, copyFileSync, symlinkSync, unlinkSync, chmodSync } from "fs";
11
11
  import { join, basename, dirname } from "path";
12
12
  import { homedir } from "os";
13
13
  import { fileURLToPath } from "url";
@@ -19,6 +19,7 @@ const HOME = homedir();
19
19
  const SKILLS_DIR = join(HOME, ".claude", "skills");
20
20
  const STATE_DIR = join(HOME, ".claude", "ftm-state");
21
21
  const CONFIG_DIR = join(HOME, ".claude");
22
+ const HOOKS_DIR = join(HOME, ".claude", "hooks");
22
23
 
23
24
  function log(msg) {
24
25
  console.log(` ${msg}`);
@@ -106,8 +107,38 @@ function main() {
106
107
  log("INIT ftm-config.yml (from default template)");
107
108
  }
108
109
 
110
+ // Install hooks
111
+ const hooksDir = join(REPO_DIR, "hooks");
112
+ let hookCount = 0;
113
+ if (existsSync(hooksDir)) {
114
+ ensureDir(HOOKS_DIR);
115
+ console.log("");
116
+ console.log("Installing hooks...");
117
+
118
+ const hookFiles = readdirSync(hooksDir).filter(
119
+ (f) => f.startsWith("ftm-") && (f.endsWith(".sh") || f.endsWith(".mjs"))
120
+ );
121
+ for (const hook of hookFiles) {
122
+ const src = join(hooksDir, hook);
123
+ const dest = join(HOOKS_DIR, hook);
124
+ const action = existsSync(dest) ? "UPDATE" : "INSTALL";
125
+ copyFileSync(src, dest);
126
+ if (hook.endsWith(".sh")) {
127
+ chmodSync(dest, 0o755);
128
+ }
129
+ log(`${action} ${hook}`);
130
+ hookCount++;
131
+ }
132
+ }
133
+
134
+ console.log("");
135
+ console.log(`Done. ${ymlFiles.length} skills linked, ${hookCount} hooks installed.`);
136
+ console.log("");
137
+ console.log("To activate hooks, add them to ~/.claude/settings.json");
138
+ console.log(" Option A: ./install.sh --setup-hooks (auto-merge)");
139
+ console.log(" Option B: Copy entries from hooks/settings-template.json manually");
140
+ console.log(" See docs/HOOKS.md for details.");
109
141
  console.log("");
110
- console.log(`Done. ${ymlFiles.length} skills linked.`);
111
142
  console.log("Try: /ftm help");
112
143
  }
113
144
 
package/docs/HOOKS.md ADDED
@@ -0,0 +1,243 @@
1
+ # FTM Hooks — Programmatic Guardrails
2
+
3
+ Hooks are shell scripts that run at specific points in Claude Code's lifecycle. Unlike skill instructions (which the model can rationalize past), hooks execute as real programs and can block actions, inject reminders, or enforce workflows.
4
+
5
+ ## Installation
6
+
7
+ Hooks are installed automatically by `install.sh` into `~/.claude/hooks/`. To activate them, you need to add the hook configuration to your `~/.claude/settings.json`.
8
+
9
+ **Option A: Automatic (recommended)**
10
+ ```bash
11
+ ./install.sh --setup-hooks
12
+ ```
13
+ This merges the FTM hook entries into your existing settings.json without overwriting your other configuration.
14
+
15
+ **Option B: Manual**
16
+ Copy the entries from `hooks/settings-template.json` into the `hooks` section of your `~/.claude/settings.json`.
17
+
18
+ ## Hook Lifecycle
19
+
20
+ ```
21
+ User types prompt
22
+ └→ UserPromptSubmit hooks fire
23
+ │ ├─ ftm-discovery-reminder.sh (nudge for external system work)
24
+ │ ├─ ftm-pending-sync-check.sh (detect out-of-session commits)
25
+ │ └─ ftm-map-autodetect.sh (detect unmapped projects)
26
+ └→ Claude processes prompt
27
+ └→ PreToolUse hooks fire before each tool
28
+ │ ├─ ftm-plan-gate.sh (block edits without a plan)
29
+ │ └─ ftm-drafts-gate.sh (block sends without a draft)
30
+ └→ Tool executes
31
+ └→ PostToolUse hooks fire after each tool
32
+ │ ├─ ftm-event-logger.mjs (log tool use for analytics)
33
+ │ └─ ftm-post-commit-trigger.sh (sync map + docs on commit)
34
+ └→ Claude finishes response
35
+ └→ Stop hook fires
36
+ └─ ftm-blackboard-enforcer.sh (enforce experience recording)
37
+ ```
38
+
39
+ ## Hooks Reference
40
+
41
+ ### PreToolUse Hooks
42
+
43
+ These fire **before** a tool executes. They can inject context (nudges) or block the tool call.
44
+
45
+ ---
46
+
47
+ #### ftm-plan-gate.sh
48
+
49
+ **Event:** PreToolUse | **Matcher:** `Edit|Write`
50
+
51
+ Prevents Claude from grinding through file edits without presenting a plan first. Tracks edit count per session — soft reminder on edits 1-2, escalated warning on 3+.
52
+
53
+ **How it works:**
54
+ - Checks for a plan marker at `~/.claude/ftm-state/.plan-presented`
55
+ - If no marker exists and edits are happening, injects context telling Claude to stop and plan
56
+ - Claude creates the marker after presenting a plan to the user
57
+
58
+ **Bypasses (always allowed):**
59
+ - Skill files (`~/.claude/skills/`)
60
+ - FTM state files (`~/.claude/ftm-state/`)
61
+ - Drafts (`.ftm-drafts/`)
62
+ - Documentation files (INTENT.md, ARCHITECTURE.mmd, STYLE.md, DEBUG.md, CLAUDE.md, .gitignore)
63
+
64
+ **State files:**
65
+ - `~/.claude/ftm-state/.plan-presented` — session ID marker
66
+ - `~/.claude/ftm-state/.edit-count` — edit counter per session
67
+
68
+ ---
69
+
70
+ #### ftm-drafts-gate.sh
71
+
72
+ **Event:** PreToolUse | **Matcher:** `mcp__slack__slack_post_message|mcp__slack__slack_reply_to_thread|mcp__gmail__send_email`
73
+
74
+ Hard-blocks outbound messages unless a draft was saved to `.ftm-drafts/` in the last 30 minutes. Creates an audit trail of all messages Claude drafts on your behalf.
75
+
76
+ **How it works:**
77
+ - Checks for `.md` files modified in the last 30 minutes in:
78
+ - `<project>/.ftm-drafts/` (project-level)
79
+ - `~/.claude/ftm-drafts/` (global fallback)
80
+ - If no recent draft found: returns `permissionDecision: deny`
81
+ - If draft exists: allows through
82
+
83
+ **Pairs with:** ftm-mind section 3.5 (draft-before-send protocol)
84
+
85
+ ---
86
+
87
+ ### UserPromptSubmit Hooks
88
+
89
+ These fire when you press Enter on a prompt, **before** Claude sees it. They inject `additionalContext` that influences Claude's response.
90
+
91
+ ---
92
+
93
+ #### ftm-discovery-reminder.sh
94
+
95
+ **Event:** UserPromptSubmit
96
+
97
+ Detects when a prompt involves external systems or stakeholder coordination and injects a reminder about the discovery interview before Claude starts work.
98
+
99
+ **Trigger patterns:**
100
+ - System changes: reroute, migrate, update integration, change endpoint, switch from/to
101
+ - Coordination: draft message, notify about, check with, coordinate with
102
+ - Workflow changes: jira automation, freshservice automation, update workflow
103
+
104
+ **Skip signals (no reminder injected):**
105
+ - "just do it", "no questions", "skip the interview"
106
+ - "here's the slack thread", "per the conversation"
107
+
108
+ **Pairs with:** ftm-mind Orient section 10 (Discovery Interview)
109
+
110
+ ---
111
+
112
+ #### ftm-pending-sync-check.sh
113
+
114
+ **Event:** UserPromptSubmit
115
+
116
+ Checks for commits made outside of Claude sessions (e.g., you pushed from the terminal or another tool). If pending syncs exist, injects a reminder to run ftm-map incremental on those files.
117
+
118
+ **How it works:**
119
+ - Reads `~/.claude/ftm-state/.pending-commit-syncs`
120
+ - If the file exists and has entries, injects context with the list
121
+ - Consumes the file on read — only fires once per batch
122
+
123
+ **State files:**
124
+ - `~/.claude/ftm-state/.pending-commit-syncs` — written by external git hooks or CI
125
+
126
+ ---
127
+
128
+ #### ftm-map-autodetect.sh
129
+
130
+ **Event:** UserPromptSubmit
131
+
132
+ Detects when you invoke any FTM skill in a project that hasn't been indexed by ftm-map yet. Classifies the project and injects bootstrap instructions.
133
+
134
+ **Classification:**
135
+
136
+ | Type | Criteria |
137
+ |---|---|
138
+ | Greenfield | ≤5 source files, ≤3 commits |
139
+ | Small brownfield | ≤50 source files |
140
+ | Medium brownfield | ≤200 source files |
141
+ | Large brownfield | 200+ source files |
142
+
143
+ **One-shot behavior:** Writes `.ftm-map/.offered` so it only fires **once per project**. Delete the marker to re-trigger.
144
+
145
+ **Trigger keywords:** `/ftm`, `ftm-`, `brainstorm`, `research`, `debug this`, `audit`, `deep dive`, `investigate`
146
+
147
+ ---
148
+
149
+ ### PostToolUse Hooks
150
+
151
+ These fire **after** a tool executes. They observe what happened and react.
152
+
153
+ ---
154
+
155
+ #### ftm-event-logger.mjs
156
+
157
+ **Event:** PostToolUse | **Matcher:** (all tools — empty matcher)
158
+
159
+ Logs tool use to `~/.claude/ftm-state/events.log` as structured JSONL. This is the data source for `/ftm-dashboard`.
160
+
161
+ **Performance:**
162
+ - Debounced — only fires every 3rd tool use
163
+ - Auto-rotates logs older than 30 days into `~/.claude/ftm-state/event-archives/`
164
+
165
+ **Requires:** Node.js (runs as `node ~/.claude/hooks/ftm-event-logger.mjs`)
166
+
167
+ ---
168
+
169
+ #### ftm-post-commit-trigger.sh
170
+
171
+ **Event:** PostToolUse | **Matcher:** `Bash|mcp__git__git_commit`
172
+
173
+ Detects git commits and triggers the documentation sync chain. Only fires if the project has been indexed by ftm-map (`.ftm-map/map.db` exists).
174
+
175
+ **Injects instructions to:**
176
+ 1. Run ftm-map incremental on changed files
177
+ 2. Update INTENT.md via ftm-intent
178
+ 3. Update ARCHITECTURE.mmd via ftm-diagram
179
+
180
+ This is what keeps the documentation layer in sync with code changes automatically.
181
+
182
+ ---
183
+
184
+ ### Stop Hooks
185
+
186
+ These fire when Claude finishes responding (before the next user prompt).
187
+
188
+ ---
189
+
190
+ #### ftm-blackboard-enforcer.sh
191
+
192
+ **Event:** Stop
193
+
194
+ Prevents Claude from ending a session without recording what it learned to the blackboard. If meaningful work was done (3+ edits or FTM skills invoked) but no experience was recorded, blocks the stop.
195
+
196
+ **How it works:**
197
+ - Checks edit counter and `context.json` for skills_invoked
198
+ - If meaningful work detected, checks for today's experience files
199
+ - If no experience recorded: blocks stop with instructions to write the blackboard
200
+ - Has infinite-loop guard via `stop_hook_active` check
201
+
202
+ **State files checked:**
203
+ - `~/.claude/ftm-state/.edit-count`
204
+ - `~/.claude/ftm-state/blackboard/context.json`
205
+ - `~/.claude/ftm-state/blackboard/experiences/` (looks for today's files)
206
+
207
+ ---
208
+
209
+ ## Dependencies
210
+
211
+ All shell hooks require `jq` for JSON parsing. The event logger requires Node.js.
212
+
213
+ ```bash
214
+ # macOS
215
+ brew install jq
216
+
217
+ # Ubuntu/Debian
218
+ sudo apt-get install jq
219
+ ```
220
+
221
+ ## Troubleshooting
222
+
223
+ **Hook not firing:**
224
+ - Check it's in `~/.claude/settings.json` under the correct event key
225
+ - Check the script is executable: `chmod +x ~/.claude/hooks/ftm-*.sh`
226
+ - Check the matcher regex matches the tool name exactly
227
+
228
+ **Hook blocking unexpectedly:**
229
+ - Plan gate: `rm ~/.claude/ftm-state/.plan-presented` to reset
230
+ - Map autodetect: `rm .ftm-map/.offered` to re-trigger
231
+ - Blackboard enforcer: has built-in infinite-loop guard
232
+
233
+ **Testing a hook manually:**
234
+ ```bash
235
+ # Test plan gate
236
+ echo '{"tool_name":"Edit","tool_input":{"file_path":"/tmp/test.py"}}' | ~/.claude/hooks/ftm-plan-gate.sh
237
+
238
+ # Test map autodetect
239
+ echo '{"prompt":"/ftm brainstorm auth design"}' | ~/.claude/hooks/ftm-map-autodetect.sh
240
+
241
+ # Test post-commit trigger
242
+ echo '{"tool_name":"Bash","tool_input":{"command":"git commit -m test"}}' | ~/.claude/hooks/ftm-post-commit-trigger.sh
243
+ ```
@@ -0,0 +1,129 @@
1
+ ---
2
+ name: ftm-dashboard
3
+ description: Session and weekly analytics dashboard for the FTM skill ecosystem. Reads events.log and blackboard state to show skills invoked, plans presented, approval rates, experiences recorded, and patterns promoted. Use when user says "dashboard", "analytics", "stats", "ftm-dashboard", "show session stats", or "how's the system doing".
4
+ ---
5
+
6
+ # FTM Dashboard
7
+
8
+ Provides analytics about FTM system usage by reading the event log and blackboard state.
9
+
10
+ ## Commands
11
+
12
+ ### `/ftm-dashboard` (default: current session)
13
+
14
+ Shows stats for the current session:
15
+
16
+ ```
17
+ ━━━━━━━━━━━ FTM Session Dashboard ━━━━━━━━━━━
18
+
19
+ Session started: [timestamp]
20
+ Duration: [hours:minutes]
21
+
22
+ Skills Invoked:
23
+ ftm-mind ████████████ 12
24
+ ftm-debug ████ 4
25
+ ftm-executor ██ 2
26
+ ftm-brainstorm █ 1
27
+
28
+ Plans:
29
+ Presented: 5
30
+ Approved: 4 (80%)
31
+ Modified before approval: 2
32
+ Saved as playbook: 1
33
+
34
+ Experiences Recorded:
35
+ Total: 8
36
+ From LLM: 5 (rich)
37
+ From git hook: 3 (minimal)
38
+
39
+ Patterns:
40
+ Active: 12
41
+ Reinforced this session: 3
42
+ Aging (>30 days): 2
43
+ Decayed: 0
44
+
45
+ Context Budget:
46
+ Orient mode: Full (conversation ~25% used)
47
+
48
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
49
+ ```
50
+
51
+ ### `/ftm-dashboard week`
52
+
53
+ Shows aggregate stats for the past 7 days:
54
+
55
+ ```
56
+ ━━━━━━━━━━ FTM Weekly Dashboard ━━━━━━━━━━━━━
57
+
58
+ Period: [date] — [date]
59
+
60
+ Tasks by Complexity:
61
+ Micro: ██████████████████ 18
62
+ Small: ████████████ 12
63
+ Medium: ██████ 6
64
+ Large: ██ 2
65
+
66
+ Top Skills:
67
+ 1. ftm-mind (45 invocations)
68
+ 2. ftm-executor (12 invocations)
69
+ 3. ftm-debug (8 invocations)
70
+ 4. ftm-brainstorm (6 invocations)
71
+ 5. ftm-audit (4 invocations)
72
+
73
+ Playbooks:
74
+ Created: 2
75
+ Reused: 3
76
+ Parameterized: 0
77
+
78
+ Learning:
79
+ Experiences recorded: 38
80
+ Patterns promoted: 1
81
+ Patterns decayed: 0
82
+ Sizing corrections: 0
83
+
84
+ Approval Rate: 85% (34/40 plans approved on first presentation)
85
+ Average plan modifications: 1.2 per plan
86
+
87
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
88
+ ```
89
+
90
+ ## Data Sources
91
+
92
+ ### events.log (`~/.claude/ftm-state/events.log`)
93
+ - JSONL format, one entry per line
94
+ - Each entry has: timestamp, event_type, tool_name, session_id, skill_context
95
+ - Filter by session_id for current session, by date range for weekly
96
+
97
+ ### Blackboard State
98
+ - `~/.claude/ftm-state/blackboard/context.json` — current session metadata
99
+ - `~/.claude/ftm-state/blackboard/experiences/index.json` — experience counts and types
100
+ - `~/.claude/ftm-state/blackboard/patterns.json` — pattern health
101
+
102
+ ### Playbooks (`~/.ftm/playbooks/`)
103
+ - Count `.yml` files for total playbooks
104
+ - Check `use_count` field for reuse stats
105
+ - Check `parameterized` field for parameterization stats
106
+
107
+ ## Implementation
108
+
109
+ 1. Read the relevant data sources
110
+ 2. Compute aggregates
111
+ 3. Render as markdown tables with ASCII bar charts
112
+ 4. Output directly — no approval gates needed (read-only operation)
113
+
114
+ ## Rendering
115
+
116
+ - Use Unicode block characters for bar charts: █ ▓ ░
117
+ - Tables in markdown format for terminal rendering
118
+ - Keep output concise — one screen max
119
+ - If data sources are empty (fresh install), show: "No data yet. Use FTM for a few sessions and check back."
120
+
121
+ ## Events
122
+
123
+ ### Listens To
124
+ - `task_completed` — for session stats tracking
125
+
126
+ ### Blackboard Read
127
+ - `context.json` — session metadata
128
+ - `experiences/index.json` — experience inventory
129
+ - `patterns.json` — pattern health
@@ -0,0 +1,209 @@
1
+ ---
2
+ name: ftm-map
3
+ description: Persistent code knowledge graph powered by tree-sitter and SQLite with FTS5 full-text search. Builds structural dependency graphs for blast radius analysis, dependency chains, and keyword search. Use when user asks "what breaks if I change X", "blast radius", "what depends on", "where do we handle", "map codebase", "index project", "what calls", "dependency chain", "ftm-map".
4
+ ---
5
+
6
+ # ftm-map
7
+
8
+ Persistent code knowledge graph powered by tree-sitter and SQLite with FTS5 full-text search. Parses the local codebase into a structural dependency graph stored in `.ftm-map/map.db`, then answers structural queries (blast radius, dependency chains, symbol lookup) and keyword searches without re-reading the source tree on every question.
9
+
10
+ ## Events
11
+
12
+ ### Emits
13
+ - `map_updated` — when the graph database has been updated (bootstrap or incremental)
14
+ - Payload: `{ project_path, symbols_count, edges_count, files_parsed, duration_ms, mode }`
15
+ - `task_completed` — when any ftm-map operation finishes
16
+
17
+ ### Listens To
18
+ - `code_committed` — run incremental index on changed files, then emit `map_updated`
19
+ - `task_received` — begin bootstrap or query when ftm-mind routes a mapping/search request
20
+
21
+ ## Config Read
22
+
23
+ Read `~/.claude/ftm-config.yml`:
24
+ - Check `skills.ftm-map.enabled` (default: true)
25
+ - Use `execution` model from active profile for indexing agents
26
+
27
+ ## Blackboard Read
28
+
29
+ On startup, load context from the FTM blackboard:
30
+ 1. Load `~/.claude/ftm-blackboard/context.json`
31
+ 2. Filter experiences by `task_type: "map"`
32
+ 3. Load matching experience files to inform index scope and query routing
33
+ 4. Check for prior bootstrap records to determine if incremental mode is appropriate
34
+
35
+ ## Mode Detection
36
+
37
+ Three modes, detected from request context:
38
+
39
+ ```
40
+ Bootstrap: "map this codebase" / "index this project" / no map.db exists yet
41
+ Full scan of all source files. Builds graph from scratch.
42
+
43
+ Incremental: Triggered by code_committed event or PostToolUse hook
44
+ Parses only changed files and updates their graph entries.
45
+
46
+ Query: Structural or keyword question about existing graph
47
+ Detects query type and runs appropriate script.
48
+ ```
49
+
50
+ If `.ftm-map/map.db` does not exist when a query arrives, fall back to offering bootstrap (see Graceful Degradation below).
51
+
52
+ ## Mode 1: Bootstrap (full scan)
53
+
54
+ Trigger: user says "map this codebase" or "index this project", or `.ftm-map/map.db` does not yet exist.
55
+
56
+ 1. Run `ftm-map/scripts/setup.sh` to ensure virtualenv and tree-sitter dependencies are installed
57
+ 2. Run `ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/index.py --bootstrap <project_root>`
58
+ 3. Capture and report stats from stdout:
59
+ - Files parsed
60
+ - Symbols found
61
+ - Edges created
62
+ - Time elapsed
63
+ 4. Emit `map_updated` with `mode: "bootstrap"`
64
+
65
+ Example invocation:
66
+ ```
67
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/index.py --bootstrap .
68
+ ```
69
+
70
+ ## Mode 2: Incremental (post-commit)
71
+
72
+ Trigger: `code_committed` event fires, or PostToolUse hook detects a write to a source file.
73
+
74
+ 1. Get changed files:
75
+ ```
76
+ git diff --name-only HEAD~1
77
+ ```
78
+ 2. Filter to source files only (skip docs, configs, lockfiles)
79
+ 3. Run incremental index on changed files:
80
+ ```
81
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/index.py --incremental --files <file1> <file2> ...
82
+ ```
83
+ 4. Emit `map_updated` with `mode: "incremental"` and count of updated entries
84
+
85
+ ## Mode 3: Query (answer structural and search questions)
86
+
87
+ Trigger: user asks a structural or keyword question about the codebase.
88
+
89
+ ### Query Type Detection
90
+
91
+ | User says | Query type | Script flag |
92
+ |-----------|-----------|-------------|
93
+ | "what breaks if I change X" | blast radius | `--blast-radius X` |
94
+ | "blast radius of X" | blast radius | `--blast-radius X` |
95
+ | "what depends on X" | dependency chain | `--deps X` |
96
+ | "what calls X" | dependency chain (callers) | `--deps X` |
97
+ | "where do we handle X" | FTS5 keyword search | `--search "X"` |
98
+ | "find X in the codebase" | FTS5 keyword search | `--search "X"` |
99
+ | "tell me about function X" | symbol info | `--info X` |
100
+ | "show dependencies for X" | dependency chain | `--deps X` |
101
+
102
+ ### Execution
103
+
104
+ Run the appropriate query script with the venv python:
105
+ ```
106
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/query.py --blast-radius <symbol>
107
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/query.py --deps <symbol>
108
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/query.py --search "<keywords>"
109
+ ftm-map/scripts/.venv/bin/python3 ftm-map/scripts/query.py --info <symbol>
110
+ ```
111
+
112
+ ### Output Formatting
113
+
114
+ Scripts return JSON. Render as readable markdown:
115
+
116
+ **Blast radius** — tree of affected symbols with file paths and line numbers:
117
+ ```
118
+ Blast radius of `authenticateUser`:
119
+ direct callers (3):
120
+ • loginHandler src/handlers/auth.ts:42
121
+ • refreshSession src/handlers/session.ts:17
122
+ • testAuthFlow src/tests/auth.test.ts:88
123
+ transitive (5):
124
+ • routeMiddleware src/middleware/index.ts:12
125
+ ...
126
+ ```
127
+
128
+ **Dependency chain** — ordered list of dependencies (callee direction):
129
+ ```
130
+ Dependencies of `authenticateUser`:
131
+ 1. validateToken src/auth/tokens.ts:8
132
+ 2. decodeJWT src/auth/jwt.ts:22
133
+ 3. createSession src/auth/session.ts:45
134
+ 4. storeSession src/auth/session.ts:67
135
+ ```
136
+
137
+ **FTS5 search** — BM25-ranked list with file:line references:
138
+ ```
139
+ Results for "rate limit" (6 matches, ranked by relevance):
140
+ 1. applyRateLimit src/middleware/ratelimit.ts:14 score: 0.94
141
+ 2. RateLimitConfig src/config/types.ts:88 score: 0.81
142
+ 3. checkRateLimit src/handlers/base.ts:203 score: 0.77
143
+ ...
144
+ ```
145
+
146
+ **Symbol info** — full details card:
147
+ ```
148
+ Symbol: authenticateUser
149
+ Kind: function
150
+ File: src/auth/index.ts:34
151
+ Signature: authenticateUser(token: string, opts?: AuthOptions) → Promise<Session>
152
+ Callers: 3 direct, 5 transitive
153
+ Callees: validateToken, decodeJWT, createSession
154
+ Dependents: 8 symbols total
155
+ ```
156
+
157
+ ## Graceful Degradation
158
+
159
+ If `.ftm-map/map.db` does not exist when a query is requested:
160
+
161
+ 1. Explain that the graph has not been indexed yet
162
+ 2. Offer to bootstrap: "Run `ftm-map bootstrap` to index this codebase?"
163
+ 3. If user confirms, switch to Bootstrap mode immediately
164
+ 4. Do not attempt to answer structural queries by reading source files directly — the graph is the source of truth for structural questions
165
+
166
+ ## Python Script Interface
167
+
168
+ All heavy lifting is done by Python scripts in `ftm-map/scripts/`. The skill orchestrates: detects mode, runs the right script with venv python, formats the output.
169
+
170
+ | Script | Purpose |
171
+ |--------|---------|
172
+ | `setup.sh` | Creates virtualenv, installs tree-sitter and dependencies |
173
+ | `db.py` | SQLite schema, CRUD operations, graph traversal queries |
174
+ | `parser.py` | tree-sitter parsing and symbol/edge extraction |
175
+ | `index.py` | Full bootstrap scan and incremental file indexing |
176
+ | `query.py` | Blast radius, dependency chain, FTS5 keyword search, symbol info |
177
+ | `views.py` | INTENT.md and .mmd generation from graph data |
178
+
179
+ Always use the venv python — never the system python — to ensure tree-sitter bindings are available:
180
+ ```
181
+ ftm-map/scripts/.venv/bin/python3 <script> <args>
182
+ ```
183
+
184
+ ## Integration Points
185
+
186
+ **ftm-intent** may call ftm-map to retrieve caller/callee relationships when writing the `Relationships` field of INTENT.md entries. ftm-map returns structured JSON that ftm-intent formats into human-readable relationship text.
187
+
188
+ **ftm-diagram** may call ftm-map to retrieve the dependency graph for a module when generating DIAGRAM.mmd files. ftm-map returns edge data that ftm-diagram renders as mermaid nodes and edges.
189
+
190
+ Both integrations use `query.py --deps` and `query.py --info` to retrieve graph data without re-parsing source.
191
+
192
+ ## Blackboard Write
193
+
194
+ After `map_updated` or session end:
195
+ 1. Update `~/.claude/ftm-blackboard/context.json` with map session summary
196
+ 2. Write experience file: `~/.claude/ftm-blackboard/experiences/map-[timestamp].json`
197
+ - Fields: project_path, mode, symbols_count, edges_count, files_parsed, duration_ms
198
+ 3. Update `~/.claude/ftm-blackboard/index.json` with new experience entry
199
+ 4. Emit `task_completed` event
200
+
201
+ ## Rules
202
+
203
+ - NEVER stop to ask for input. Make decisions and keep going.
204
+ - ALWAYS commit after completing with a clear message.
205
+ - ALWAYS review after commit: run `git diff HEAD~1`.
206
+ - Never reference AI/Claude in commit messages.
207
+ - Stay in your worktree.
208
+ - ALWAYS use the venv python (`ftm-map/scripts/.venv/bin/python3`), never the system python.
209
+ - For query mode, ALWAYS run `setup.sh` first if `.venv` does not exist.