feed-the-machine 1.0.0 → 1.2.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 (136) hide show
  1. package/bin/generate-manifest.mjs +253 -0
  2. package/bin/install.mjs +134 -4
  3. package/docs/HOOKS.md +243 -0
  4. package/docs/INBOX.md +233 -0
  5. package/ftm/SKILL.md +34 -0
  6. package/ftm-audit/SKILL.md +69 -0
  7. package/ftm-brainstorm/SKILL.md +51 -0
  8. package/ftm-browse/SKILL.md +39 -0
  9. package/ftm-capture/SKILL.md +370 -0
  10. package/ftm-capture.yml +4 -0
  11. package/ftm-codex-gate/SKILL.md +59 -0
  12. package/ftm-config/SKILL.md +35 -0
  13. package/ftm-council/SKILL.md +56 -0
  14. package/ftm-dashboard/SKILL.md +163 -0
  15. package/ftm-debug/SKILL.md +84 -0
  16. package/ftm-diagram/SKILL.md +44 -0
  17. package/ftm-executor/SKILL.md +97 -0
  18. package/ftm-git/SKILL.md +60 -0
  19. package/ftm-inbox/backend/__init__.py +0 -0
  20. package/ftm-inbox/backend/__pycache__/main.cpython-314.pyc +0 -0
  21. package/ftm-inbox/backend/adapters/__init__.py +0 -0
  22. package/ftm-inbox/backend/adapters/_retry.py +64 -0
  23. package/ftm-inbox/backend/adapters/base.py +230 -0
  24. package/ftm-inbox/backend/adapters/freshservice.py +104 -0
  25. package/ftm-inbox/backend/adapters/gmail.py +125 -0
  26. package/ftm-inbox/backend/adapters/jira.py +136 -0
  27. package/ftm-inbox/backend/adapters/registry.py +192 -0
  28. package/ftm-inbox/backend/adapters/slack.py +110 -0
  29. package/ftm-inbox/backend/db/__init__.py +0 -0
  30. package/ftm-inbox/backend/db/connection.py +54 -0
  31. package/ftm-inbox/backend/db/schema.py +78 -0
  32. package/ftm-inbox/backend/executor/__init__.py +7 -0
  33. package/ftm-inbox/backend/executor/engine.py +149 -0
  34. package/ftm-inbox/backend/executor/step_runner.py +98 -0
  35. package/ftm-inbox/backend/main.py +103 -0
  36. package/ftm-inbox/backend/models/__init__.py +1 -0
  37. package/ftm-inbox/backend/models/unified_task.py +36 -0
  38. package/ftm-inbox/backend/planner/__init__.py +6 -0
  39. package/ftm-inbox/backend/planner/__pycache__/__init__.cpython-314.pyc +0 -0
  40. package/ftm-inbox/backend/planner/__pycache__/generator.cpython-314.pyc +0 -0
  41. package/ftm-inbox/backend/planner/__pycache__/schema.cpython-314.pyc +0 -0
  42. package/ftm-inbox/backend/planner/generator.py +127 -0
  43. package/ftm-inbox/backend/planner/schema.py +34 -0
  44. package/ftm-inbox/backend/requirements.txt +5 -0
  45. package/ftm-inbox/backend/routes/__init__.py +0 -0
  46. package/ftm-inbox/backend/routes/__pycache__/plan.cpython-314.pyc +0 -0
  47. package/ftm-inbox/backend/routes/execute.py +186 -0
  48. package/ftm-inbox/backend/routes/health.py +52 -0
  49. package/ftm-inbox/backend/routes/inbox.py +68 -0
  50. package/ftm-inbox/backend/routes/plan.py +271 -0
  51. package/ftm-inbox/bin/launchagent.mjs +91 -0
  52. package/ftm-inbox/bin/setup.mjs +188 -0
  53. package/ftm-inbox/bin/start.sh +10 -0
  54. package/ftm-inbox/bin/status.sh +17 -0
  55. package/ftm-inbox/bin/stop.sh +8 -0
  56. package/ftm-inbox/config.example.yml +55 -0
  57. package/ftm-inbox/package-lock.json +2898 -0
  58. package/ftm-inbox/package.json +26 -0
  59. package/ftm-inbox/postcss.config.js +6 -0
  60. package/ftm-inbox/src/app.css +199 -0
  61. package/ftm-inbox/src/app.html +18 -0
  62. package/ftm-inbox/src/lib/api.ts +166 -0
  63. package/ftm-inbox/src/lib/components/ExecutionLog.svelte +81 -0
  64. package/ftm-inbox/src/lib/components/InboxFeed.svelte +143 -0
  65. package/ftm-inbox/src/lib/components/PlanStep.svelte +271 -0
  66. package/ftm-inbox/src/lib/components/PlanView.svelte +206 -0
  67. package/ftm-inbox/src/lib/components/StreamPanel.svelte +99 -0
  68. package/ftm-inbox/src/lib/components/TaskCard.svelte +190 -0
  69. package/ftm-inbox/src/lib/components/ui/EmptyState.svelte +63 -0
  70. package/ftm-inbox/src/lib/components/ui/KawaiiCard.svelte +86 -0
  71. package/ftm-inbox/src/lib/components/ui/PillButton.svelte +106 -0
  72. package/ftm-inbox/src/lib/components/ui/StatusBadge.svelte +67 -0
  73. package/ftm-inbox/src/lib/components/ui/StreamDrawer.svelte +149 -0
  74. package/ftm-inbox/src/lib/components/ui/ThemeToggle.svelte +80 -0
  75. package/ftm-inbox/src/lib/theme.ts +47 -0
  76. package/ftm-inbox/src/routes/+layout.svelte +76 -0
  77. package/ftm-inbox/src/routes/+page.svelte +401 -0
  78. package/ftm-inbox/static/favicon.png +0 -0
  79. package/ftm-inbox/svelte.config.js +12 -0
  80. package/ftm-inbox/tailwind.config.ts +63 -0
  81. package/ftm-inbox/tsconfig.json +13 -0
  82. package/ftm-inbox/vite.config.ts +6 -0
  83. package/ftm-intent/SKILL.md +44 -0
  84. package/ftm-manifest.json +3794 -0
  85. package/ftm-map/SKILL.md +259 -0
  86. package/ftm-map/scripts/db.py +391 -0
  87. package/ftm-map/scripts/index.py +341 -0
  88. package/ftm-map/scripts/parser.py +455 -0
  89. package/ftm-map/scripts/queries/.gitkeep +0 -0
  90. package/ftm-map/scripts/queries/javascript-tags.scm +23 -0
  91. package/ftm-map/scripts/queries/python-tags.scm +17 -0
  92. package/ftm-map/scripts/queries/typescript-tags.scm +29 -0
  93. package/ftm-map/scripts/query.py +149 -0
  94. package/ftm-map/scripts/requirements.txt +2 -0
  95. package/ftm-map/scripts/setup-hooks.sh +27 -0
  96. package/ftm-map/scripts/setup.sh +45 -0
  97. package/ftm-map/scripts/test_db.py +124 -0
  98. package/ftm-map/scripts/test_parser.py +106 -0
  99. package/ftm-map/scripts/test_query.py +66 -0
  100. package/ftm-map/scripts/tests/fixtures/__init__.py +0 -0
  101. package/ftm-map/scripts/tests/fixtures/sample_project/api.ts +16 -0
  102. package/ftm-map/scripts/tests/fixtures/sample_project/auth.py +15 -0
  103. package/ftm-map/scripts/tests/fixtures/sample_project/utils.js +16 -0
  104. package/ftm-map/scripts/views.py +545 -0
  105. package/ftm-mind/SKILL.md +173 -66
  106. package/ftm-pause/SKILL.md +43 -0
  107. package/ftm-researcher/SKILL.md +275 -0
  108. package/ftm-researcher/evals/agent-diversity.yaml +17 -0
  109. package/ftm-researcher/evals/synthesis-quality.yaml +12 -0
  110. package/ftm-researcher/evals/trigger-accuracy.yaml +39 -0
  111. package/ftm-researcher/references/adaptive-search.md +116 -0
  112. package/ftm-researcher/references/agent-prompts.md +193 -0
  113. package/ftm-researcher/references/council-integration.md +193 -0
  114. package/ftm-researcher/references/output-format.md +203 -0
  115. package/ftm-researcher/references/synthesis-pipeline.md +165 -0
  116. package/ftm-researcher/scripts/score_credibility.py +234 -0
  117. package/ftm-researcher/scripts/validate_research.py +92 -0
  118. package/ftm-resume/SKILL.md +47 -0
  119. package/ftm-retro/SKILL.md +54 -0
  120. package/ftm-routine/SKILL.md +170 -0
  121. package/ftm-state/blackboard/capabilities.json +5 -0
  122. package/ftm-state/blackboard/capabilities.schema.json +27 -0
  123. package/ftm-upgrade/SKILL.md +41 -0
  124. package/ftm-upgrade/scripts/check-version.sh +1 -1
  125. package/ftm-upgrade/scripts/upgrade.sh +1 -1
  126. package/hooks/ftm-blackboard-enforcer.sh +94 -0
  127. package/hooks/ftm-discovery-reminder.sh +90 -0
  128. package/hooks/ftm-drafts-gate.sh +61 -0
  129. package/hooks/ftm-event-logger.mjs +107 -0
  130. package/hooks/ftm-map-autodetect.sh +79 -0
  131. package/hooks/ftm-pending-sync-check.sh +22 -0
  132. package/hooks/ftm-plan-gate.sh +96 -0
  133. package/hooks/ftm-post-commit-trigger.sh +57 -0
  134. package/hooks/settings-template.json +81 -0
  135. package/install.sh +140 -11
  136. package/package.json +12 -2
@@ -131,10 +131,214 @@ function extractBlackboardPaths(lines) {
131
131
  return paths;
132
132
  }
133
133
 
134
+ // ---------------------------------------------------------------------------
135
+ // New section parsers for the 6 structured YAML contracts
136
+ // ---------------------------------------------------------------------------
137
+
138
+ /**
139
+ * Parses the ## Requirements section.
140
+ * Format: - type: `name` | required|optional | description
141
+ * Returns: Array of { type, name, required, description }
142
+ */
143
+ function parseRequirements(lines) {
144
+ const requirements = [];
145
+ // Match lines like: - tool: `knip` | required | static analysis engine
146
+ // or: - config: `knip.config.ts` | optional | custom knip config
147
+ const reqRegex = /^-\s+(tool|config|reference|env):\s+`([^`]+)`\s*\|\s*(required|optional)\s*\|\s*(.+)/;
148
+
149
+ for (const line of lines) {
150
+ const match = line.match(reqRegex);
151
+ if (match) {
152
+ requirements.push({
153
+ type: match[1],
154
+ name: match[2],
155
+ required: match[3] === 'required',
156
+ description: match[4].trim(),
157
+ });
158
+ }
159
+ }
160
+
161
+ return requirements;
162
+ }
163
+
164
+ /**
165
+ * Parses the ## Risk section.
166
+ * Format:
167
+ * - level: read_only | low_write | medium_write | high_write | destructive
168
+ * - scope: description
169
+ * - rollback: description
170
+ * Returns: { level, scope, rollback }
171
+ */
172
+ function parseRisk(lines) {
173
+ let level = null;
174
+ let scope = null;
175
+ let rollback = null;
176
+
177
+ for (const line of lines) {
178
+ const levelMatch = line.match(/^-\s+level:\s+(.+)/);
179
+ const scopeMatch = line.match(/^-\s+scope:\s+(.+)/);
180
+ const rollbackMatch = line.match(/^-\s+rollback:\s+(.+)/);
181
+
182
+ if (levelMatch) level = levelMatch[1].trim();
183
+ if (scopeMatch) scope = scopeMatch[1].trim();
184
+ if (rollbackMatch) rollback = rollbackMatch[1].trim();
185
+ }
186
+
187
+ return { level, scope, rollback };
188
+ }
189
+
190
+ /**
191
+ * Parses the ## Approval Gates section.
192
+ * Format:
193
+ * - trigger: condition | action: what happens
194
+ * - complexity_routing: micro → auto | small → auto | ...
195
+ * Returns: { gates: Array<{ trigger, action }>, complexity_routing: object }
196
+ */
197
+ function parseApprovalGates(lines) {
198
+ const gates = [];
199
+ let complexity_routing = null;
200
+
201
+ for (const line of lines) {
202
+ // complexity_routing line
203
+ const crMatch = line.match(/^-\s+complexity_routing:\s+(.+)/);
204
+ if (crMatch) {
205
+ // Parse: micro → auto | small → auto | medium → plan_first | ...
206
+ const routing = {};
207
+ const parts = crMatch[1].split('|').map(s => s.trim());
208
+ for (const part of parts) {
209
+ const arrowMatch = part.match(/^(\w+)\s+[→>-]+\s+(.+)/);
210
+ if (arrowMatch) {
211
+ routing[arrowMatch[1].trim()] = arrowMatch[2].trim();
212
+ }
213
+ }
214
+ complexity_routing = routing;
215
+ continue;
216
+ }
217
+
218
+ // trigger/action line
219
+ const triggerMatch = line.match(/^-\s+trigger:\s+(.+?)\s*\|\s*action:\s+(.+)/);
220
+ if (triggerMatch) {
221
+ gates.push({
222
+ trigger: triggerMatch[1].trim(),
223
+ action: triggerMatch[2].trim(),
224
+ });
225
+ }
226
+ }
227
+
228
+ return { gates, complexity_routing };
229
+ }
230
+
231
+ /**
232
+ * Parses the ## Fallbacks section.
233
+ * Format: - condition: description | action: what happens
234
+ * Returns: Array of { condition, action }
235
+ */
236
+ function parseFallbacks(lines) {
237
+ const fallbacks = [];
238
+ const fallbackRegex = /^-\s+condition:\s+(.+?)\s*\|\s*action:\s+(.+)/;
239
+
240
+ for (const line of lines) {
241
+ const match = line.match(fallbackRegex);
242
+ if (match) {
243
+ fallbacks.push({
244
+ condition: match[1].trim(),
245
+ action: match[2].trim(),
246
+ });
247
+ }
248
+ }
249
+
250
+ return fallbacks;
251
+ }
252
+
253
+ /**
254
+ * Parses the ## Capabilities section.
255
+ * Format: - mcp|cli|env: `name` | required|optional | description
256
+ * Returns: Array of { type, name, required, description }
257
+ */
258
+ function parseCapabilities(lines) {
259
+ const capabilities = [];
260
+ const capRegex = /^-\s+(mcp|cli|env):\s+`([^`]+)`\s*\|\s*(required|optional)\s*\|\s*(.+)/;
261
+
262
+ for (const line of lines) {
263
+ const match = line.match(capRegex);
264
+ if (match) {
265
+ capabilities.push({
266
+ type: match[1],
267
+ name: match[2],
268
+ required: match[3] === 'required',
269
+ description: match[4].trim(),
270
+ });
271
+ }
272
+ }
273
+
274
+ return capabilities;
275
+ }
276
+
277
+ /**
278
+ * Parses the ## Event Payloads section.
279
+ * Format:
280
+ * ### event_name
281
+ * - field: type — description
282
+ * Returns: object mapping event_name -> Array<{ field, type, description }>
283
+ */
284
+ function parseEventPayloads(content) {
285
+ const payloads = {};
286
+
287
+ // We need to parse ### sub-sections within ## Event Payloads.
288
+ // Find the section start, then extract up to the next ## heading or end of string.
289
+ // Using manual indexing is more reliable than regex for the "last section" case.
290
+ const sectionStart = content.indexOf('\n## Event Payloads\n');
291
+ if (sectionStart < 0) return payloads;
292
+
293
+ const afterHeading = content.substring(sectionStart + '\n## Event Payloads\n'.length);
294
+ const nextH2 = afterHeading.indexOf('\n## ');
295
+ const sectionContent = nextH2 >= 0 ? afterHeading.substring(0, nextH2) : afterHeading;
296
+ const lines = sectionContent.split('\n');
297
+
298
+ let currentEvent = null;
299
+
300
+ for (const line of lines) {
301
+ // ### event_name header
302
+ const h3Match = line.match(/^###\s+(.+)/);
303
+ if (h3Match) {
304
+ currentEvent = h3Match[1].trim();
305
+ payloads[currentEvent] = [];
306
+ continue;
307
+ }
308
+
309
+ if (!currentEvent) continue;
310
+
311
+ // - field: type — description
312
+ const fieldMatch = line.match(/^-\s+(\w+):\s+([\w\[\]|]+)\s+[—-]+\s+(.+)/);
313
+ if (fieldMatch) {
314
+ payloads[currentEvent].push({
315
+ field: fieldMatch[1],
316
+ type: fieldMatch[2],
317
+ description: fieldMatch[3].trim(),
318
+ });
319
+ }
320
+ }
321
+
322
+ return payloads;
323
+ }
324
+
134
325
  // ---------------------------------------------------------------------------
135
326
  // Per-skill metadata extraction
136
327
  // ---------------------------------------------------------------------------
137
328
 
329
+ /**
330
+ * Required sections for the structured YAML contract.
331
+ * Used to generate warnings when sections are missing.
332
+ */
333
+ const REQUIRED_CONTRACT_SECTIONS = [
334
+ 'Requirements',
335
+ 'Risk',
336
+ 'Approval Gates',
337
+ 'Fallbacks',
338
+ 'Capabilities',
339
+ 'Event Payloads',
340
+ ];
341
+
138
342
  function processSkill({ skillFile, skillDir, triggerFile }) {
139
343
  const raw = fs.readFileSync(skillFile, 'utf8');
140
344
  const stat = fs.statSync(skillFile);
@@ -151,6 +355,24 @@ function processSkill({ skillFile, skillDir, triggerFile }) {
151
355
  const blackboardReads = extractBlackboardPaths(sections['Blackboard Read'] || []);
152
356
  const blackboardWrites = extractBlackboardPaths(sections['Blackboard Write'] || []);
153
357
 
358
+ // New structured contract sections
359
+ const requirements = parseRequirements(sections['Requirements'] || []);
360
+ const risk = parseRisk(sections['Risk'] || []);
361
+ const { gates: approval_gates, complexity_routing } = parseApprovalGates(
362
+ sections['Approval Gates'] || []
363
+ );
364
+ const fallbacks = parseFallbacks(sections['Fallbacks'] || []);
365
+ const capabilities = parseCapabilities(sections['Capabilities'] || []);
366
+ const event_payloads = parseEventPayloads(parsed.content);
367
+
368
+ // Warnings — flag any missing required contract sections
369
+ const warnings = [];
370
+ for (const section of REQUIRED_CONTRACT_SECTIONS) {
371
+ if (!sections[section]) {
372
+ warnings.push(`Missing required section: ## ${section}`);
373
+ }
374
+ }
375
+
154
376
  // References directory
155
377
  const referencesDir = path.join(ROOT, skillDir, 'references');
156
378
  let references = [];
@@ -178,8 +400,16 @@ function processSkill({ skillFile, skillDir, triggerFile }) {
178
400
  events_listens: eventsListens,
179
401
  blackboard_reads: blackboardReads,
180
402
  blackboard_writes: blackboardWrites,
403
+ requirements,
404
+ risk,
405
+ approval_gates,
406
+ complexity_routing,
407
+ fallbacks,
408
+ capabilities,
409
+ event_payloads,
181
410
  references,
182
411
  has_evals: hasEvals,
412
+ warnings,
183
413
  size_bytes: stat.size,
184
414
  enabled: true,
185
415
  };
@@ -196,15 +426,38 @@ function main() {
196
426
  // Sort alphabetically by name
197
427
  skills.sort((a, b) => a.name.localeCompare(b.name));
198
428
 
429
+ // Collect manifest-level warnings for skills with missing sections
430
+ const manifestWarnings = [];
431
+ for (const skill of skills) {
432
+ if (skill.warnings && skill.warnings.length > 0) {
433
+ manifestWarnings.push({
434
+ skill: skill.name,
435
+ warnings: skill.warnings,
436
+ });
437
+ }
438
+ }
439
+
199
440
  const manifest = {
200
441
  generated_at: new Date().toISOString(),
201
442
  skills,
443
+ warnings: manifestWarnings,
202
444
  };
203
445
 
204
446
  const outputPath = path.join(ROOT, 'ftm-manifest.json');
205
447
  fs.writeFileSync(outputPath, JSON.stringify(manifest, null, 2) + '\n', 'utf8');
206
448
 
207
449
  process.stderr.write(`Generated manifest for ${skills.length} skills\n`);
450
+
451
+ if (manifestWarnings.length > 0) {
452
+ process.stderr.write(
453
+ `Warnings: ${manifestWarnings.length} skill(s) missing required contract sections\n`
454
+ );
455
+ for (const w of manifestWarnings) {
456
+ process.stderr.write(` ${w.skill}: ${w.warnings.join(', ')}\n`);
457
+ }
458
+ } else {
459
+ process.stderr.write(`All ${skills.length} skills have complete contract sections\n`);
460
+ }
208
461
  }
209
462
 
210
463
  main();
package/bin/install.mjs CHANGED
@@ -1,16 +1,17 @@
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, cpSync } from "fs";
11
11
  import { join, basename, dirname } from "path";
12
- import { homedir } from "os";
12
+ import { homedir, platform } from "os";
13
13
  import { fileURLToPath } from "url";
14
+ import { execSync, spawnSync } from "child_process";
14
15
 
15
16
  const __filename = fileURLToPath(import.meta.url);
16
17
  const __dirname = dirname(__filename);
@@ -19,6 +20,11 @@ const HOME = homedir();
19
20
  const SKILLS_DIR = join(HOME, ".claude", "skills");
20
21
  const STATE_DIR = join(HOME, ".claude", "ftm-state");
21
22
  const CONFIG_DIR = join(HOME, ".claude");
23
+ const HOOKS_DIR = join(HOME, ".claude", "hooks");
24
+ const INBOX_INSTALL_DIR = join(HOME, ".claude", "ftm-inbox");
25
+
26
+ const ARGS = process.argv.slice(2);
27
+ const WITH_INBOX = ARGS.includes("--with-inbox");
22
28
 
23
29
  function log(msg) {
24
30
  console.log(` ${msg}`);
@@ -106,8 +112,132 @@ function main() {
106
112
  log("INIT ftm-config.yml (from default template)");
107
113
  }
108
114
 
115
+ // Install hooks
116
+ const hooksDir = join(REPO_DIR, "hooks");
117
+ let hookCount = 0;
118
+ if (existsSync(hooksDir)) {
119
+ ensureDir(HOOKS_DIR);
120
+ console.log("");
121
+ console.log("Installing hooks...");
122
+
123
+ const hookFiles = readdirSync(hooksDir).filter(
124
+ (f) => f.startsWith("ftm-") && (f.endsWith(".sh") || f.endsWith(".mjs"))
125
+ );
126
+ for (const hook of hookFiles) {
127
+ const src = join(hooksDir, hook);
128
+ const dest = join(HOOKS_DIR, hook);
129
+ const action = existsSync(dest) ? "UPDATE" : "INSTALL";
130
+ copyFileSync(src, dest);
131
+ if (hook.endsWith(".sh")) {
132
+ chmodSync(dest, 0o755);
133
+ }
134
+ log(`${action} ${hook}`);
135
+ hookCount++;
136
+ }
137
+ }
138
+
139
+ console.log("");
140
+ console.log(`Done. ${ymlFiles.length} skills linked, ${hookCount} hooks installed.`);
141
+ console.log("");
142
+ console.log("To activate hooks, add them to ~/.claude/settings.json");
143
+ console.log(" Option A: ./install.sh --setup-hooks (auto-merge)");
144
+ console.log(" Option B: Copy entries from hooks/settings-template.json manually");
145
+ console.log(" See docs/HOOKS.md for details.");
146
+ console.log("");
147
+
148
+ if (WITH_INBOX) {
149
+ installInbox();
150
+ } else {
151
+ console.log("Try: /ftm help");
152
+ console.log(" To also install the inbox service: npx feed-the-machine --with-inbox");
153
+ }
154
+ }
155
+
156
+ function installInbox() {
157
+ const inboxSrc = join(REPO_DIR, "ftm-inbox");
158
+ if (!existsSync(inboxSrc)) {
159
+ console.error("ERROR: ftm-inbox/ not found in package. Cannot install inbox service.");
160
+ process.exit(1);
161
+ }
162
+
163
+ console.log("Installing ftm-inbox service...");
164
+ console.log(` Source: ${inboxSrc}`);
165
+ console.log(` Destination: ${INBOX_INSTALL_DIR}`);
166
+ console.log("");
167
+
168
+ // Copy ftm-inbox/ to ~/.claude/ftm-inbox/
169
+ ensureDir(INBOX_INSTALL_DIR);
170
+ cpSync(inboxSrc, INBOX_INSTALL_DIR, { recursive: true });
171
+ log("COPY ftm-inbox → ~/.claude/ftm-inbox/");
172
+
173
+ // Make shell scripts executable
174
+ const binDir = join(INBOX_INSTALL_DIR, "bin");
175
+ const scripts = ["start.sh", "stop.sh", "status.sh"];
176
+ for (const script of scripts) {
177
+ const scriptPath = join(binDir, script);
178
+ if (existsSync(scriptPath)) {
179
+ chmodSync(scriptPath, 0o755);
180
+ log(`CHMOD +x bin/${script}`);
181
+ }
182
+ }
183
+
184
+ // Install Node deps if package.json exists
185
+ const pkgJson = join(INBOX_INSTALL_DIR, "package.json");
186
+ if (existsSync(pkgJson)) {
187
+ console.log("");
188
+ console.log("Installing Node.js dependencies...");
189
+ const npmResult = spawnSync("npm", ["install", "--prefix", INBOX_INSTALL_DIR], {
190
+ stdio: "inherit",
191
+ cwd: INBOX_INSTALL_DIR,
192
+ });
193
+ if (npmResult.status !== 0) {
194
+ console.warn("WARNING: npm install failed. Check Node.js version and try manually.");
195
+ }
196
+ }
197
+
198
+ // Install Python deps if requirements.txt exists
199
+ const reqTxt = join(INBOX_INSTALL_DIR, "requirements.txt");
200
+ if (existsSync(reqTxt)) {
201
+ console.log("");
202
+ console.log("Installing Python dependencies...");
203
+ const pipResult = spawnSync("pip3", ["install", "-r", reqTxt], {
204
+ stdio: "inherit",
205
+ cwd: INBOX_INSTALL_DIR,
206
+ });
207
+ if (pipResult.status !== 0) {
208
+ console.warn("WARNING: pip3 install failed. Check Python 3 and try manually:");
209
+ console.warn(` pip3 install -r ${reqTxt}`);
210
+ }
211
+ }
212
+
213
+ // Run setup wizard
214
+ console.log("");
215
+ console.log("Running setup wizard...");
216
+ const setupScript = join(binDir, "setup.mjs");
217
+ if (existsSync(setupScript)) {
218
+ const setupResult = spawnSync("node", [setupScript], { stdio: "inherit" });
219
+ if (setupResult.status !== 0) {
220
+ console.warn("WARNING: Setup wizard exited with errors.");
221
+ console.warn(`Re-run manually: node ${setupScript}`);
222
+ }
223
+ } else {
224
+ console.warn("WARNING: setup.mjs not found. Run setup manually.");
225
+ }
226
+
227
+ // Offer LaunchAgent (macOS only)
228
+ if (platform() === "darwin") {
229
+ console.log("");
230
+ console.log("macOS detected. To auto-start ftm-inbox on login, run:");
231
+ console.log(` node ${join(binDir, "launchagent.mjs")}`);
232
+ }
233
+
234
+ console.log("");
235
+ console.log("ftm-inbox installed.");
236
+ console.log(` Start: ${join(binDir, "start.sh")}`);
237
+ console.log(` Stop: ${join(binDir, "stop.sh")}`);
238
+ console.log(` Status: ${join(binDir, "status.sh")}`);
109
239
  console.log("");
110
- console.log(`Done. ${ymlFiles.length} skills linked.`);
240
+ console.log("See docs/INBOX.md for full documentation.");
111
241
  console.log("Try: /ftm help");
112
242
  }
113
243
 
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
+ ```