@theglitchking/semantic-memory 1.2.1 → 1.5.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 (65) hide show
  1. package/.claude-plugin/marketplace.json +4 -4
  2. package/.claude-plugin/plugin.json +3 -3
  3. package/CHANGELOG.md +144 -0
  4. package/ROADMAP.md +5 -2
  5. package/commands/healthcheck.md +13 -11
  6. package/dist/{chunk-EVAJGOCB.js → chunk-2EELGTLX.js} +49 -5
  7. package/dist/chunk-2EELGTLX.js.map +1 -0
  8. package/dist/chunk-5ZKNO6ZD.js +96 -0
  9. package/dist/chunk-5ZKNO6ZD.js.map +1 -0
  10. package/dist/chunk-7M3JZOYH.js +105 -0
  11. package/dist/chunk-7M3JZOYH.js.map +1 -0
  12. package/dist/chunk-A3KYHKB5.js +176 -0
  13. package/dist/chunk-A3KYHKB5.js.map +1 -0
  14. package/dist/{chunk-CYWPDFNI.js → chunk-CSXZ7QUU.js} +4 -203
  15. package/dist/chunk-CSXZ7QUU.js.map +1 -0
  16. package/dist/chunk-FM26NFTR.js +272 -0
  17. package/dist/chunk-FM26NFTR.js.map +1 -0
  18. package/dist/chunk-NTYYS53O.js +91 -0
  19. package/dist/chunk-NTYYS53O.js.map +1 -0
  20. package/dist/{chunk-E2Z4J4MK.js → chunk-OWZWMB4P.js} +70 -2
  21. package/dist/chunk-OWZWMB4P.js.map +1 -0
  22. package/dist/chunk-S4KW7VH4.js +203 -0
  23. package/dist/chunk-S4KW7VH4.js.map +1 -0
  24. package/dist/{chunk-HODDRXJK.js → chunk-V45NJIHI.js} +4 -2
  25. package/dist/chunk-V45NJIHI.js.map +1 -0
  26. package/dist/chunk-WSU4QIPB.js +311 -0
  27. package/dist/chunk-WSU4QIPB.js.map +1 -0
  28. package/dist/cli/index.js +265 -65
  29. package/dist/cli/index.js.map +1 -1
  30. package/dist/core/index.d.ts +39 -2
  31. package/dist/core/index.js +17 -11
  32. package/dist/decay-ELJUKVQG.js +14 -0
  33. package/dist/dossier-2UG724LB.js +39 -0
  34. package/dist/healthcheck-IMB47LZE.js +19 -0
  35. package/dist/indexer-YW4O3VVM.js +8 -0
  36. package/dist/lexicon-5PXQEMUF.js +26 -0
  37. package/dist/lexicon-5PXQEMUF.js.map +1 -0
  38. package/dist/lint-XUQ7JDYX.js +16 -0
  39. package/dist/lint-XUQ7JDYX.js.map +1 -0
  40. package/dist/mcp/server.js +478 -40
  41. package/dist/mcp/server.js.map +1 -1
  42. package/dist/profile-LXUEF7TX.js +20 -0
  43. package/dist/profile-LXUEF7TX.js.map +1 -0
  44. package/dist/{schema-F3RTY6SQ.js → schema-ATFCLC6Y.js} +2 -2
  45. package/dist/schema-ATFCLC6Y.js.map +1 -0
  46. package/dist/{search-27WYAI24.js → search-AHKEFI2B.js} +2 -2
  47. package/dist/telemetry-GB2TEHVE.js +21 -0
  48. package/dist/telemetry-GB2TEHVE.js.map +1 -0
  49. package/hooks/vault-context.js +296 -12
  50. package/package.json +2 -1
  51. package/skills/vault-first/SKILL.md +18 -0
  52. package/dist/chunk-CAN2GWUG.js +0 -88
  53. package/dist/chunk-CAN2GWUG.js.map +0 -1
  54. package/dist/chunk-CYWPDFNI.js.map +0 -1
  55. package/dist/chunk-E2Z4J4MK.js.map +0 -1
  56. package/dist/chunk-EVAJGOCB.js.map +0 -1
  57. package/dist/chunk-HODDRXJK.js.map +0 -1
  58. package/dist/healthcheck-7YOPNDXN.js +0 -14
  59. package/dist/indexer-KD6UTXZB.js +0 -8
  60. package/dist/lint-GMXQF4RW.js +0 -11
  61. /package/dist/{healthcheck-7YOPNDXN.js.map → decay-ELJUKVQG.js.map} +0 -0
  62. /package/dist/{indexer-KD6UTXZB.js.map → dossier-2UG724LB.js.map} +0 -0
  63. /package/dist/{lint-GMXQF4RW.js.map → healthcheck-IMB47LZE.js.map} +0 -0
  64. /package/dist/{schema-F3RTY6SQ.js.map → indexer-YW4O3VVM.js.map} +0 -0
  65. /package/dist/{search-27WYAI24.js.map → search-AHKEFI2B.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/index.ts","../../src/cli/skills.ts","../../src/cli/migrate-state.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { program } from \"commander\";\nimport { resolve, join, dirname, relative } from \"node:path\";\nimport { existsSync, readFileSync, writeFileSync, rmSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { spawnSync } from \"node:child_process\";\nimport { registerUpdateCommands } from \"@theglitchking/claude-plugin-runtime\";\nimport {\n resolveTarget,\n installSkills,\n uninstallSkills,\n listShippedSkills,\n SKILL_BUNDLER_AGENTS,\n type AgentName,\n type Scope,\n} from \"./skills.js\";\nimport { migrateState } from \"./migrate-state.js\";\n\nconst require_ = createRequire(import.meta.url);\nconst { version } = require_(\"../../package.json\") as { version: string };\n\nconst PKG_NAME = \"@theglitchking/semantic-memory\";\nconst LEGACY_PKG_NAME = \"@theglitchking/semantic-sidekick\";\n\nfunction runRelink(cwd: string) {\n const candidates = [\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-memory\", \"scripts\", \"link-skills.js\"),\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-sidekick\", \"scripts\", \"link-skills.js\"),\n resolve(process.cwd(), \"scripts\", \"link-skills.js\"),\n ];\n const script = candidates.find((p) => existsSync(p));\n if (!script) {\n console.error(\"link-skills.js not found — is the package installed?\");\n return;\n }\n spawnSync(process.execPath, [script], {\n cwd,\n env: { ...process.env, INIT_CWD: cwd },\n stdio: \"inherit\",\n });\n}\n\nfunction findLocalBin(cwd: string): string | null {\n const candidates = [\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-memory\", \"bin\", \"semantic-memory\"),\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-sidekick\", \"bin\", \"semantic-sidekick\"),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction localBinArg(cwd: string): string | null {\n const abs = findLocalBin(cwd);\n if (!abs) return null;\n const rel = relative(cwd, abs);\n return rel.startsWith(\"..\") ? abs : `./${rel}`;\n}\n\nfunction readJsonSafe(path: string): any {\n try {\n const raw = readFileSync(path, \"utf8\");\n return raw.trim() ? JSON.parse(raw) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the fragile npx-form pattern we used to write in pre-0.10.0\n * SessionStart hooks, so normalize-config can detect and rewrite it.\n */\nfunction isNpxForm(entry: any): boolean {\n if (!entry || typeof entry !== \"object\") return false;\n const cmd = entry.command;\n const args = Array.isArray(entry.args) ? entry.args : [];\n return (\n cmd === \"npx\" &&\n args.some(\n (a: unknown) => typeof a === \"string\" && (a.includes(PKG_NAME) || a.includes(LEGACY_PKG_NAME))\n )\n );\n}\n\nfunction isLocalForm(entry: any): boolean {\n if (!entry || typeof entry !== \"object\") return false;\n const cmd = entry.command;\n const args = Array.isArray(entry.args) ? entry.args : [];\n return (\n cmd === \"node\" &&\n args.some(\n (a: unknown) =>\n typeof a === \"string\" &&\n (a.includes(\"node_modules/@theglitchking/semantic-memory\") ||\n a.includes(\"node_modules/@theglitchking/semantic-sidekick\"))\n )\n );\n}\n\nfunction extractNotesPath(entry: any): string | null {\n const args = Array.isArray(entry?.args) ? entry.args : [];\n const i = args.indexOf(\"--notes\");\n if (i === -1 || i + 1 >= args.length) return null;\n return String(args[i + 1]);\n}\n\nfunction extractExtraFlags(entry: any): string[] {\n const args = Array.isArray(entry?.args) ? entry.args : [];\n return args.filter((a: unknown): a is string => typeof a === \"string\" && a.startsWith(\"--\") && a !== \"--notes\");\n}\n\nconst TOOL_HELP: Record<string, { description: string; args: string; examples: string[] }> = {\n // Search\n search_semantic: {\n description: \"Vector similarity search — find notes by meaning, not just keywords\",\n args: '{ \"query\": \"string\", \"limit?\": 10 }',\n examples: [\n '{ \"query\": \"microservices architecture\", \"limit\": 5 }',\n '{ \"query\": \"how to deploy to production\" }',\n ],\n },\n search_text: {\n description: \"Full-text keyword or regex search with optional filters\",\n args: '{ \"pattern\": \"string\", \"regex?\": false, \"caseSensitive?\": false, \"pathGlob?\": \"string\", \"tagFilter?\": [\"string\"], \"limit?\": 20 }',\n examples: [\n '{ \"pattern\": \"RabbitMQ\" }',\n '{ \"pattern\": \"OAuth\\\\\\\\d\", \"regex\": true }',\n '{ \"pattern\": \"deploy\", \"pathGlob\": \"devops/**\", \"tagFilter\": [\"kubernetes\"] }',\n ],\n },\n search_graph: {\n description: \"Graph traversal — find notes connected to a concept via wikilinks and tags\",\n args: '{ \"concept\": \"string\", \"maxDepth?\": 2 }',\n examples: [\n '{ \"concept\": \"microservices\" }',\n '{ \"concept\": \"auth\", \"maxDepth\": 3 }',\n ],\n },\n search_hybrid: {\n description: \"Combined semantic + graph search — vector results re-ranked by graph proximity\",\n args: '{ \"query\": \"string\", \"limit?\": 10 }',\n examples: [\n '{ \"query\": \"event driven architecture\", \"limit\": 5 }',\n ],\n },\n\n // Read\n read_note: {\n description: \"Read the full content of a specific note by path\",\n args: '{ \"path\": \"string\" }',\n examples: [\n '{ \"path\": \"project-overview.md\" }',\n '{ \"path\": \"notes/meeting-2024-01-15.md\" }',\n ],\n },\n read_multiple_notes: {\n description: \"Batch read multiple notes in one call\",\n args: '{ \"paths\": [\"string\"] }',\n examples: [\n '{ \"paths\": [\"overview.md\", \"architecture.md\", \"deployment.md\"] }',\n ],\n },\n list_notes: {\n description: \"List all indexed notes with metadata (title, tags, link count)\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n\n // Write\n create_note: {\n description: \"Create a new markdown note with optional YAML frontmatter\",\n args: '{ \"path\": \"string\", \"content\": \"string\", \"frontmatter?\": {} }',\n examples: [\n '{ \"path\": \"new-guide.md\", \"content\": \"# Guide\\\\n\\\\nContent here.\" }',\n '{ \"path\": \"tagged.md\", \"content\": \"Content.\", \"frontmatter\": { \"title\": \"Tagged Note\", \"tags\": [\"test\"] } }',\n ],\n },\n update_note: {\n description: \"Edit note content — overwrite, append, prepend, or patch by heading\",\n args: '{ \"path\": \"string\", \"content\": \"string\", \"mode\": \"overwrite|append|prepend|patch-by-heading\", \"heading?\": \"string\" }',\n examples: [\n '{ \"path\": \"guide.md\", \"content\": \"New content.\", \"mode\": \"overwrite\" }',\n '{ \"path\": \"guide.md\", \"content\": \"\\\\n## Appendix\\\\nExtra info.\", \"mode\": \"append\" }',\n '{ \"path\": \"guide.md\", \"content\": \"Updated architecture section.\", \"mode\": \"patch-by-heading\", \"heading\": \"Architecture\" }',\n ],\n },\n delete_note: {\n description: \"Delete a note permanently (requires confirm=true)\",\n args: '{ \"path\": \"string\", \"confirm\": true }',\n examples: [\n '{ \"path\": \"old-note.md\", \"confirm\": true }',\n '{ \"path\": \"old-note.md\", \"confirm\": false } // returns warning, does not delete',\n ],\n },\n move_note: {\n description: \"Move or rename a note — automatically updates wikilinks across the vault\",\n args: '{ \"from\": \"string\", \"to\": \"string\" }',\n examples: [\n '{ \"from\": \"user-service.md\", \"to\": \"auth-service.md\" }',\n '{ \"from\": \"old/note.md\", \"to\": \"new/location/note.md\" }',\n ],\n },\n\n // Metadata\n get_frontmatter: {\n description: \"Read parsed YAML frontmatter from a note as JSON\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"project-overview.md\" }'],\n },\n update_frontmatter: {\n description: \"Set or delete YAML frontmatter keys — pass null to delete a key\",\n args: '{ \"path\": \"string\", \"fields\": {} }',\n examples: [\n '{ \"path\": \"note.md\", \"fields\": { \"status\": \"active\", \"priority\": 1 } }',\n '{ \"path\": \"note.md\", \"fields\": { \"deprecated_field\": null } } // deletes the key',\n ],\n },\n manage_tags: {\n description: \"Add, remove, or list tags on a note (frontmatter and inline)\",\n args: '{ \"path\": \"string\", \"action\": \"add|remove|list\", \"tags?\": [\"string\"] }',\n examples: [\n '{ \"path\": \"note.md\", \"action\": \"list\" }',\n '{ \"path\": \"note.md\", \"action\": \"add\", \"tags\": [\"important\", \"reviewed\"] }',\n '{ \"path\": \"note.md\", \"action\": \"remove\", \"tags\": [\"draft\"] }',\n ],\n },\n rename_tag: {\n description: \"Rename a tag across all notes in the vault (frontmatter + inline)\",\n args: '{ \"oldTag\": \"string\", \"newTag\": \"string\" }',\n examples: ['{ \"oldTag\": \"architecture\", \"newTag\": \"arch\" }'],\n },\n\n // Graph\n backlinks: {\n description: \"Find all notes that link TO a given note via [[wikilinks]]\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"microservices.md\" }'],\n },\n forwardlinks: {\n description: \"Find all notes linked FROM a given note\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"project-overview.md\" }'],\n },\n graph_path: {\n description: \"Find the shortest path between two notes in the knowledge graph\",\n args: '{ \"from\": \"string\", \"to\": \"string\" }',\n examples: ['{ \"from\": \"project-overview.md\", \"to\": \"user-service.md\" }'],\n },\n graph_statistics: {\n description: \"Knowledge graph stats — most connected nodes, orphans, density\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n\n // System\n get_stats: {\n description: \"Vault and index statistics — note count, chunks, embeddings, graph density\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n reindex: {\n description: \"Force a full reindex of the vault\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n};\n\nconst TOOL_CATEGORIES: Record<string, string[]> = {\n Search: [\"search_semantic\", \"search_text\", \"search_graph\", \"search_hybrid\"],\n Read: [\"read_note\", \"read_multiple_notes\", \"list_notes\"],\n Write: [\"create_note\", \"update_note\", \"delete_note\", \"move_note\"],\n Metadata: [\"get_frontmatter\", \"update_frontmatter\", \"manage_tags\", \"rename_tag\"],\n Graph: [\"backlinks\", \"forwardlinks\", \"graph_path\", \"graph_statistics\"],\n System: [\"get_stats\", \"reindex\"],\n};\n\nfunction printToolList() {\n console.log(\"\\nSemantic Pages — 21 MCP Tools\\n\");\n console.log(\"Usage: These tools are available via MCP when the server is running.\");\n console.log(\" Run `semantic-memory tools <name>` for details on a specific tool.\\n\");\n\n for (const [category, tools] of Object.entries(TOOL_CATEGORIES)) {\n console.log(` ${category}:`);\n for (const name of tools) {\n const tool = TOOL_HELP[name];\n console.log(` ${name.padEnd(24)} ${tool.description}`);\n }\n console.log();\n }\n\n console.log(\"Run `semantic-memory tools <tool-name>` for arguments and examples.\");\n}\n\nfunction printToolDetail(name: string) {\n const tool = TOOL_HELP[name];\n if (!tool) {\n console.error(`Unknown tool: ${name}`);\n console.error(`Run \\`semantic-memory tools\\` to see all available tools.`);\n process.exit(1);\n }\n\n console.log(`\\n ${name}`);\n console.log(` ${\"─\".repeat(name.length)}`);\n console.log(` ${tool.description}\\n`);\n console.log(` Arguments:`);\n console.log(` ${tool.args}\\n`);\n console.log(` Examples:`);\n for (const ex of tool.examples) {\n console.log(` ${ex}`);\n }\n console.log();\n}\n\nprogram\n .name(\"semantic-memory\")\n .description(\n \"Unified memory-layer MCP server for Claude Code (rebrand of semantic-sidekick at v1.0.0).\\n\" +\n \"The `semantic-sidekick` command is preserved as an alias.\\n\\n\" +\n \" Start MCP server: semantic-memory --notes ./vault\\n\" +\n \" Show vault stats: semantic-memory --notes ./vault --stats\\n\" +\n \" Force reindex: semantic-memory --notes ./vault --reindex\\n\" +\n \" List MCP tools: semantic-memory tools\\n\" +\n \" Tool details: semantic-memory tools search_semantic\"\n )\n .version(version);\n\nprogram\n .command(\"search <query>\")\n .description(\"Run a vault search and print top hits as JSON (used by activation hooks)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--limit <n>\", \"Max results\", (v) => parseInt(v, 10), 8)\n .option(\"--text-only\", \"Skip embedder — keyword-only search (fast path, no model init)\")\n .option(\"--json\", \"Emit raw JSON (default)\", true)\n .action(async (query: string, opts) => {\n const { runSearch } = await import(\"./search.js\");\n try {\n const hits = await runSearch({\n notes: opts.notes,\n query,\n limit: opts.limit,\n textOnly: opts.textOnly,\n });\n process.stdout.write(JSON.stringify(hits, null, 2) + \"\\n\");\n process.exit(0);\n } catch (err: any) {\n console.error(`search failed: ${err.message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"lint\")\n .description(\"Lint the vault against vault.schema.yml (schema violations + missing provenance + stale)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--rule <name>\", \"Limit output to one rule: schema_violations | missing_provenance | stale\")\n .option(\"--json\", \"Emit JSON instead of the human-readable report\")\n .option(\"--strict\", \"Exit non-zero on warnings too (default: exit non-zero only on errors)\")\n .action(async (opts) => {\n const { lintVault, formatLintReport } = await import(\"../core/lint.js\");\n const report = await lintVault(resolve(opts.notes));\n // Use console.log + process.exitCode (not process.exit) so Node flushes\n // stdout fully before the process ends. Early process.exit with a large\n // buffered JSON payload can truncate output.\n if (opts.json) {\n const out = opts.rule ? report.byRule[opts.rule as keyof typeof report.byRule] : report;\n console.log(JSON.stringify(out, null, 2));\n } else {\n console.log(formatLintReport(report, { rule: opts.rule }));\n }\n const bad = opts.strict ? report.counts.errors + report.counts.warnings : report.counts.errors;\n process.exitCode = bad > 0 ? 1 : 0;\n });\n\nprogram\n .command(\"log-event\")\n .description(\"Append a structured event to the vault's log.md (used by hooks and CI scripts — same shape as mcp__semantic-vault__log_event)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .requiredOption(\"--kind <name>\", \"Event category: ingest, synthesis, error, mode_change, etc.\")\n .requiredOption(\"--summary <text>\", \"One-line human summary\")\n .option(\"--payload <json>\", \"Structured payload as JSON string\")\n .action(async (opts) => {\n const { logEvent } = await import(\"../core/log.js\");\n let payload: Record<string, unknown> | undefined;\n if (opts.payload) {\n try {\n payload = JSON.parse(opts.payload);\n } catch (e: any) {\n console.error(`invalid --payload JSON: ${e.message}`);\n process.exitCode = 1;\n return;\n }\n }\n try {\n const entry = await logEvent(resolve(opts.notes), {\n kind: opts.kind,\n summary: opts.summary,\n payload,\n });\n console.log(JSON.stringify(entry));\n } catch (e: any) {\n console.error(`log-event failed: ${e.message}`);\n process.exitCode = 1;\n }\n });\n\nprogram\n .command(\"log-query\")\n .description(\"Read structured log entries from log.md — filters by kind, date range, limit\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--kind <name>\", \"Filter by kind (ingest, synthesis, error, mode_change, etc.)\")\n .option(\"--after <iso>\", \"ISO timestamp — only entries on or after\")\n .option(\"--before <iso>\", \"ISO timestamp — only entries on or before\")\n .option(\"--limit <n>\", \"Max entries (most recent)\", (v) => parseInt(v, 10))\n .action(async (opts) => {\n const { logQuery } = await import(\"../core/log.js\");\n try {\n const entries = await logQuery(resolve(opts.notes), {\n kind: opts.kind,\n after: opts.after,\n before: opts.before,\n limit: opts.limit,\n });\n console.log(JSON.stringify(entries));\n } catch (e: any) {\n console.error(`log-query failed: ${e.message}`);\n process.exitCode = 1;\n }\n });\n\nprogram\n .command(\"install-schema\")\n .description(\"Bootstrap vault.schema.yml in the vault root with the default schema\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--force\", \"Overwrite existing schema file\")\n .action(async (opts) => {\n const { installDefaultSchema } = await import(\"../core/schema.js\");\n const r = await installDefaultSchema(resolve(opts.notes), opts.force);\n console.log(r.written ? `Installed default schema: ${r.path}` : `Schema already exists: ${r.path} (use --force to overwrite)`);\n process.exit(0);\n });\n\nprogram\n .command(\"tools [name]\")\n .description(\"List all MCP tools, or show details for a specific tool\")\n .action((name?: string) => {\n if (name) {\n printToolDetail(name);\n } else {\n printToolList();\n }\n process.exit(0);\n });\n\nprogram\n .command(\"serve\", { isDefault: true })\n .description(\"Start the MCP server (default command)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--reindex\", \"Force full reindex and exit\")\n .option(\"--stats\", \"Show vault statistics and exit\")\n .option(\"--wait-for-ready\", \"Block startup until index is fully built before serving (default: index in background; tools return 'Indexing in progress' until ready)\")\n .option(\"--read-only\", \"Suppress write tools (create_note, update_note, delete_note, move_note, update_frontmatter, manage_tags, rename_tag) — use for shared docs vaults owned by another tool\")\n .option(\"--model <name>\", \"Embedding model to use (default: all-MiniLM-L6-v2, fast; use nomic-ai/nomic-embed-text-v1.5 for higher quality)\")\n .option(\"--workers <n>\", \"Number of worker threads for parallel embedding\", parseInt)\n .option(\"--batch-size <n>\", \"Texts per ONNX forward pass (default: 8)\", parseInt)\n .option(\"--no-quantized\", \"Use full-precision model instead of quantized (slower, slightly higher quality)\")\n .option(\"--no-watch\", \"Disable file watcher\")\n .action(async (opts) => {\n const notesPath = resolve(opts.notes);\n\n if (!existsSync(notesPath)) {\n console.error(`Error: notes directory not found: ${notesPath}`);\n process.exit(1);\n }\n\n if (opts.stats) {\n const { Indexer } = await import(\"../core/indexer.js\");\n const indexer = new Indexer(notesPath);\n const docs = await indexer.indexAll();\n console.log(`Notes: ${docs.length}`);\n console.log(`Chunks: ${docs.reduce((n: number, d: any) => n + d.chunks.length, 0)}`);\n console.log(`Wikilinks: ${docs.reduce((n: number, d: any) => n + d.wikilinks.length, 0)}`);\n console.log(`Tags: ${new Set(docs.flatMap((d: any) => d.tags)).size} unique`);\n process.exit(0);\n }\n\n if (opts.reindex) {\n const { createServer } = await import(\"../mcp/server.js\");\n await createServer(notesPath, {\n watch: false,\n waitForReady: true,\n model: opts.model,\n workers: opts.workers,\n batchSize: opts.batchSize,\n quantized: opts.quantized,\n onProgress: (embedded, total) => {\n process.stderr.write(`\\rEmbedding ${embedded}/${total} chunks...`);\n },\n });\n process.stderr.write(\"\\n\");\n console.log(\"Reindex complete.\");\n process.exit(0);\n }\n\n // Default: start MCP server on stdio\n const { startServer } = await import(\"../mcp/server.js\");\n await startServer(notesPath, {\n watch: opts.watch,\n waitForReady: opts.waitForReady,\n model: opts.model,\n workers: opts.workers,\n batchSize: opts.batchSize,\n quantized: opts.quantized,\n readOnly: opts.readOnly,\n });\n });\n\nregisterUpdateCommands(program, {\n packageName: PKG_NAME,\n pluginName: \"semantic-memory\",\n configFile: \"semantic-memory.json\",\n onAfterUpdate: (cwd) => runRelink(cwd),\n});\n\nprogram\n .command(\"normalize-config\")\n .description(\n \"Rewrite fragile `npx @latest` entries in .mcp.json to the stable node-against-node_modules form (with backup and validation)\",\n )\n .option(\"--dry-run\", \"print the proposed changes but don't write\")\n .action((opts: { dryRun?: boolean }) => {\n const cwd = process.cwd();\n const mcpPath = join(cwd, \".mcp.json\");\n if (!existsSync(mcpPath)) {\n console.log(\"no .mcp.json in current directory — nothing to do\");\n process.exit(0);\n }\n const data = readJsonSafe(mcpPath);\n if (!data || typeof data !== \"object\" || !data.mcpServers || typeof data.mcpServers !== \"object\") {\n console.error(`could not parse ${mcpPath}`);\n process.exit(1);\n }\n const bin = localBinArg(cwd);\n if (!bin) {\n console.error(\n `no local install found at ./node_modules/@theglitchking/semantic-memory/bin/semantic-memory ` +\n `(or the legacy semantic-sidekick path).\\n` +\n `run 'npm install --save @theglitchking/semantic-memory' first, then re-run this command.`,\n );\n process.exit(1);\n }\n const rewritten: string[] = [];\n for (const [key, entry] of Object.entries<any>(data.mcpServers)) {\n if (!isNpxForm(entry)) continue;\n const notes = extractNotesPath(entry) ?? \"./.claude/.vault\";\n const extra = extractExtraFlags(entry);\n data.mcpServers[key] = {\n type: \"stdio\",\n command: \"node\",\n args: [bin, \"--notes\", notes, ...extra],\n };\n rewritten.push(key);\n }\n if (rewritten.length === 0) {\n console.log(\"no npx-form entries found — .mcp.json is already in the stable form.\");\n process.exit(0);\n }\n console.log(`Rewriting ${rewritten.length} entr${rewritten.length === 1 ? \"y\" : \"ies\"}: ${rewritten.join(\", \")}`);\n if (opts.dryRun) {\n console.log(\"--- proposed .mcp.json:\");\n console.log(JSON.stringify(data, null, 2));\n console.log(\"--- (dry-run; no changes written)\");\n process.exit(0);\n }\n // Back up\n const bakPath = join(dirname(mcpPath), \".mcp.json.bak\");\n try {\n writeFileSync(bakPath, readFileSync(mcpPath, \"utf8\"));\n console.log(`backup written: ${bakPath}`);\n } catch (err: any) {\n console.error(`could not write backup: ${err.message}`);\n process.exit(1);\n }\n writeFileSync(mcpPath, JSON.stringify(data, null, 2) + \"\\n\");\n\n // Verify the local bin starts cleanly. We just run --version — fast and\n // enough to catch ERR_MODULE_NOT_FOUND type failures.\n const verify = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (verify.status !== 0) {\n console.error(`verification failed (exit ${verify.status}):\\n${verify.stderr?.toString() || \"\"}`);\n console.error(`rolling back from ${bakPath}`);\n writeFileSync(mcpPath, readFileSync(bakPath, \"utf8\"));\n process.exit(1);\n }\n console.log(`✓ .mcp.json normalized and verified. Toggle the MCPs in /mcp to reconnect.`);\n process.exit(0);\n });\n\nprogram\n .command(\"healthcheck\")\n .description(\n \"Verify the local install starts cleanly + run drift detection. Self-heals common npx-cache corruption (ERR_MODULE_NOT_FOUND). With --fast, skips the slow tier (full vault lint).\",\n )\n .option(\"--fast\", \"Run only the fast-tier drift checks (file-system probes). Skips the slow tier (full vault lint).\", false)\n .option(\"--json\", \"Emit structured JSON output instead of human-readable text.\", false)\n .action(async (opts) => {\n const cwd = process.cwd();\n const bin = findLocalBin(cwd);\n if (!bin) {\n console.error(`no local install at ./node_modules/@theglitchking/semantic-memory/bin/semantic-memory (or legacy semantic-sidekick path)`);\n console.error(`run 'npm install --save @theglitchking/semantic-memory' to install.`);\n process.exit(1);\n }\n\n // 1. Warn if .mcp.json uses the fragile form.\n const mcpPath = join(cwd, \".mcp.json\");\n if (existsSync(mcpPath)) {\n const data = readJsonSafe(mcpPath);\n const entries = data?.mcpServers && typeof data.mcpServers === \"object\" ? Object.entries<any>(data.mcpServers) : [];\n const fragile = entries.filter(([, e]) => isNpxForm(e)).map(([k]) => k);\n if (fragile.length > 0) {\n console.warn(\n `⚠️ .mcp.json uses the fragile npx-@latest form for: ${fragile.join(\", \")}`,\n );\n console.warn(` Rewrite to the stable form:`);\n console.warn(` npx --no @theglitchking/semantic-memory normalize-config`);\n }\n }\n\n // 2. Smoke-test the local bin.\n const r = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (r.status === 0) {\n console.log(`✓ local install starts cleanly (v${r.stdout?.toString().trim()})`);\n process.exit(0);\n }\n\n const stderr = r.stderr?.toString() ?? \"\";\n\n // 3. Self-heal ERR_MODULE_NOT_FOUND in npx cache (rare but the classic\n // failure mode that triggered 0.10.0). Extract the offending npx cache\n // dir from the error message, rm -rf it, retry once.\n if (stderr.includes(\"ERR_MODULE_NOT_FOUND\")) {\n const match = stderr.match(/([\\/~][^'\"\\s]*\\/_npx\\/[^\\/'\"\\s]+)/);\n if (match) {\n const bad = match[1];\n console.warn(`detected broken npx cache at ${bad} — clearing and retrying...`);\n try { rmSync(bad, { recursive: true, force: true }); } catch {}\n const r2 = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (r2.status === 0) {\n console.log(`✓ cleared npx cache and verified (v${r2.stdout?.toString().trim()})`);\n process.exit(0);\n }\n console.error(`retry still failed:\\n${r2.stderr?.toString() || \"\"}`);\n } else {\n console.error(`ERR_MODULE_NOT_FOUND but could not locate offending cache path in the error.`);\n }\n }\n\n if (stderr) console.error(stderr);\n if (r.status !== 0) {\n console.error(`local install failed (exit ${r.status})`);\n process.exit(1);\n }\n });\n\n// Append drift detection to the healthcheck handler (Phase 8). Wraps the original\n// handler — the function above runs first (npx-cache self-heal), then drift detection\n// runs and prints additional findings. --fast skips the slow tier (full vault lint).\nconst driftHealthcheckActionPostprocess = async (opts: { fast?: boolean; json?: boolean }) => {\n try {\n const { runHealthcheck, formatDriftBanner } = await import(\"../core/healthcheck.js\");\n const projectRoot = process.cwd();\n // For the auto-derived vault path, prefer .claude/.vault if present\n const vaultCandidate = join(projectRoot, \".claude\", \".vault\");\n const vaultPath = existsSync(vaultCandidate) ? vaultCandidate : undefined;\n const result = await runHealthcheck({\n projectRoot,\n vaultPath,\n tier: opts.fast ? \"fast\" : \"all\",\n force: true,\n });\n if (opts.json) {\n console.log(JSON.stringify(result, null, 2));\n return;\n }\n const banner = formatDriftBanner(result);\n if (banner) {\n console.log(\"\");\n console.log(banner);\n } else {\n console.log(\"\");\n console.log(`✓ no drift detected (${result.findings.length} checks ran in ${result.duration_ms}ms)`);\n }\n } catch (err: any) {\n console.error(`drift check threw: ${err?.message ?? err}`);\n }\n};\n\n// Wire the drift-detection postprocess. We do this by attaching to the existing\n// healthcheck command's postAction hook so the original handler still runs first.\nconst healthcheckCmd = program.commands.find((c) => c.name() === \"healthcheck\");\nif (healthcheckCmd) {\n healthcheckCmd.hook(\"postAction\", async (thisCmd) => {\n const opts = thisCmd.opts();\n await driftHealthcheckActionPostprocess({ fast: !!opts.fast, json: !!opts.json });\n });\n}\n\n// --- Skill bundler (Phase 6) ---\n\nfunction parseAgent(input: string): AgentName {\n const a = input.toLowerCase();\n if (!SKILL_BUNDLER_AGENTS.includes(a as AgentName)) {\n console.error(`Unknown agent: ${input}. Supported: ${SKILL_BUNDLER_AGENTS.join(\", \")}.`);\n process.exit(2);\n }\n return a as AgentName;\n}\n\nfunction parseScope(input: string): Scope {\n if (input !== \"global\" && input !== \"local\") {\n console.error(`Unknown scope: ${input}. Use 'global' or 'local'.`);\n process.exit(2);\n }\n return input;\n}\n\nfunction findSourceRoot(): string {\n // 1. Installed: <cwd>/node_modules/@theglitchking/semantic-sidekick or semantic-memory\n for (const pkg of [\"semantic-memory\", \"semantic-sidekick\"]) {\n const installed = join(process.cwd(), \"node_modules\", \"@theglitchking\", pkg);\n if (existsSync(installed)) return installed;\n }\n // 2. Dev: derive from the bin location (this file lives at <root>/dist/cli/index.js)\n const dev = resolve(new URL(\"../../\", import.meta.url).pathname);\n return dev;\n}\n\nconst skillsCmd = program.command(\"skills\").description(\"Install, target, or uninstall skill bundles for non-Claude agents (codex, copilot, pi). Claude installs continue to use the npm postinstall flow.\");\n\nskillsCmd\n .command(\"targets\")\n .description(\"Preview where skill bundles would be installed for one or more agents.\")\n .option(\"--agent <name...>\", \"One or more agents (default: all). Repeatable.\", undefined as any)\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .action((opts) => {\n const scope = parseScope(opts.scope);\n const agents: AgentName[] = (opts.agent && opts.agent.length > 0 ? opts.agent : SKILL_BUNDLER_AGENTS).map(parseAgent);\n const out = agents.map((a) => resolveTarget(a, scope, opts.project));\n console.log(JSON.stringify(out, null, 2));\n });\n\nskillsCmd\n .command(\"install\")\n .description(\"Install skill bundles into an agent's skill directory. Non-destructive by default; --force to overwrite.\")\n .requiredOption(\"--agent <name>\", \"Agent runtime (claude, codex, copilot, pi)\")\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .option(\"--only <names...>\", \"Restrict to specific skill names (default: all shipped)\")\n .option(\"--force\", \"Overwrite even if drift is detected against an existing manifest\", false)\n .action(async (opts) => {\n const agent = parseAgent(opts.agent);\n const scope = parseScope(opts.scope);\n if (agent === \"claude\") {\n console.error(\n \"Claude skill installs are handled by the npm postinstall (claude-plugin-runtime). \" +\n \"Run `npm install @theglitchking/semantic-memory` instead — that flow symlinks \" +\n \"skills into ~/.claude/skills/ or .claude/skills/ automatically. The skills CLI \" +\n \"is intended for non-Claude agents (codex, copilot, pi) which do not have that \" +\n \"postinstall integration.\"\n );\n process.exit(2);\n }\n const sourceRoot = findSourceRoot();\n const result = await installSkills({\n agent,\n scope,\n sourceRoot,\n projectRoot: opts.project,\n version,\n only: opts.only,\n force: opts.force === true,\n });\n console.log(JSON.stringify(result, null, 2));\n if (result.installed.length === 0 && result.reason) process.exit(1);\n });\n\nskillsCmd\n .command(\"uninstall\")\n .description(\"Remove skill bundles tracked by the semantic-memory manifest. User-written skills outside the manifest are left untouched.\")\n .requiredOption(\"--agent <name>\", \"Agent runtime (claude, codex, copilot, pi)\")\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .action(async (opts) => {\n const agent = parseAgent(opts.agent);\n const scope = parseScope(opts.scope);\n if (agent === \"claude\") {\n console.error(\"Claude skill uninstalls go through the npm uninstall flow. The skills CLI is for non-Claude agents.\");\n process.exit(2);\n }\n const result = await uninstallSkills({ agent, scope, projectRoot: opts.project });\n console.log(JSON.stringify(result, null, 2));\n });\n\nskillsCmd\n .command(\"list\")\n .description(\"List the skill bundles shipped with this plugin version.\")\n .action(async () => {\n const sourceRoot = findSourceRoot();\n const shipped = await listShippedSkills(sourceRoot);\n console.log(JSON.stringify(shipped.map((s) => s.name), null, 2));\n });\n\n// --- State migration (Phase 3, v1.2) ---\n\nprogram\n .command(\"migrate-state\")\n .description(\n \"Move legacy .claude/.sidekick-* state files to .claude/.semantic-memory/. Idempotent. \" +\n \"Conflicts (both paths exist) require --force. Pass --dry-run to preview without changes.\",\n )\n .option(\"--dry-run\", \"Print the planned migration without renaming any files.\", false)\n .option(\n \"--force\",\n \"When both old and new paths exist, prefer the new path and delete the old one.\",\n false,\n )\n .option(\"--project <path>\", \"Project root (default: cwd)\", process.cwd())\n .action((opts) => {\n const result = migrateState({\n projectRoot: opts.project,\n dryRun: opts.dryRun === true,\n force: opts.force === true,\n });\n console.log(JSON.stringify(result, null, 2));\n if (result.conflicts.length > 0 && !opts.force && !opts.dryRun) {\n console.error(\n `\\n${result.conflicts.length} conflict${result.conflicts.length === 1 ? \"\" : \"s\"} detected. Re-run with --force to resolve (keeps new path, deletes old).`,\n );\n process.exit(1);\n }\n });\n\nprogram.parse();\n","import { mkdir, readFile, writeFile, copyFile, readdir, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, basename, resolve } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { createHash } from \"node:crypto\";\n\nexport type AgentName = \"claude\" | \"codex\" | \"copilot\" | \"pi\";\nexport type Scope = \"global\" | \"local\";\n\nexport interface AgentTargetSpec {\n agent: AgentName;\n scope: Scope;\n /** Absolute resolved path where the skill bundles will land. */\n path: string;\n}\n\nexport interface SkillManifest {\n package: string;\n version: string;\n agent: AgentName;\n scope: Scope;\n installed_at: string;\n skills: { name: string; sha256: string }[];\n}\n\nexport interface InstallResult {\n agent: AgentName;\n scope: Scope;\n target_path: string;\n installed: string[];\n skipped: string[];\n reason?: string;\n manifest_path?: string;\n}\n\nconst MANIFEST_FILE = \".semantic-memory-skill-manifest.json\";\n\n/**\n * Resolve where a given (agent, scope) tuple should land. Project root is required for local\n * scope (to anchor relative paths); for global scope it's not used.\n */\nexport function resolveTarget(agent: AgentName, scope: Scope, projectRoot: string): AgentTargetSpec {\n const root = resolve(projectRoot);\n const home = homedir();\n const map: Record<AgentName, { global: string; local: string }> = {\n claude: { global: join(home, \".claude\", \"skills\"), local: join(root, \".claude\", \"skills\") },\n codex: { global: join(home, \".codex\", \"skills\"), local: join(root, \".codex\", \"skills\") },\n copilot: { global: join(home, \".copilot\", \"skills\"), local: join(root, \".github\", \"skills\") },\n pi: { global: join(home, \".pi\", \"agent\", \"skills\"), local: join(root, \".pi\", \"skills\") },\n };\n return { agent, scope, path: map[agent][scope] };\n}\n\n/**\n * Enumerate the canonical skill bundles shipped by this plugin. Each bundle is a directory\n * under `<sourceRoot>/skills/` containing at least a SKILL.md file. Entries without\n * SKILL.md are silently skipped (allows future non-skill files like `/skills/.gitkeep`).\n */\nexport async function listShippedSkills(sourceRoot: string): Promise<{ name: string; dir: string }[]> {\n const skillsDir = join(sourceRoot, \"skills\");\n if (!existsSync(skillsDir)) return [];\n const entries = await readdir(skillsDir, { withFileTypes: true });\n const out: { name: string; dir: string }[] = [];\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const dir = join(skillsDir, e.name);\n const skillFile = join(dir, \"SKILL.md\");\n if (!existsSync(skillFile)) continue;\n out.push({ name: e.name, dir });\n }\n return out;\n}\n\nasync function sha256OfFile(path: string): Promise<string> {\n const buf = await readFile(path);\n return createHash(\"sha256\").update(buf).digest(\"hex\");\n}\n\n/**\n * Copy a single skill bundle (SKILL.md plus any sibling files in the same directory) into\n * the target directory, overlaying it with the agent name. Returns the list of files written.\n *\n * The target layout is `<targetPath>/<skillName>/SKILL.md` plus mirrored siblings, so each\n * bundle is namespaced and easy to remove later.\n */\nasync function copyBundle(srcDir: string, destDir: string): Promise<string[]> {\n await mkdir(destDir, { recursive: true });\n const entries = await readdir(srcDir, { withFileTypes: true });\n const written: string[] = [];\n for (const e of entries) {\n const src = join(srcDir, e.name);\n const dest = join(destDir, e.name);\n if (e.isDirectory()) {\n const childWritten = await copyBundle(src, dest);\n written.push(...childWritten);\n continue;\n }\n if (!e.isFile()) continue;\n await copyFile(src, dest);\n written.push(dest);\n }\n return written;\n}\n\nexport interface InstallOptions {\n agent: AgentName;\n scope: Scope;\n /** Path to the package's source root (usually the repo root, where `skills/` lives). */\n sourceRoot: string;\n /** Used to anchor local-scope target paths. */\n projectRoot: string;\n /** Plugin version, recorded in the manifest. */\n version: string;\n /** Specific skills to install. When omitted, all shipped skills are installed. */\n only?: string[];\n /**\n * When false, refuse to overwrite an existing install (manifest present + sha mismatch\n * indicates upstream drift). When true, overwrite. Default false.\n */\n force?: boolean;\n}\n\n/**\n * Install all (or selected) skill bundles into an agent's skill directory.\n *\n * Behavior:\n * - Resolves the destination via resolveTarget.\n * - Reads any existing manifest. If a manifest exists, version differs from `version`,\n * AND any skill sha256 differs from the source: this is a drift event. Without\n * `force: true`, returns a refusal with reason \"drift detected\". With force, proceeds\n * and overwrites.\n * - For each shipped skill (or each in `only`), copies the bundle into\n * <target>/<skillName>/, overwriting any existing files in that subdirectory.\n * - Writes a fresh manifest at <target>/<MANIFEST_FILE> recording sha256 of each\n * SKILL.md installed, the plugin version, agent, and scope.\n */\nexport async function installSkills(opts: InstallOptions): Promise<InstallResult> {\n const target = resolveTarget(opts.agent, opts.scope, opts.projectRoot);\n const shipped = await listShippedSkills(opts.sourceRoot);\n const filter = opts.only && opts.only.length > 0 ? new Set(opts.only) : null;\n const toInstall = filter ? shipped.filter((s) => filter.has(s.name)) : shipped;\n\n if (toInstall.length === 0) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed: [],\n skipped: [],\n reason: filter ? `No matching skills found (only=${[...filter].join(\",\")}).` : \"No shipped skills found at sourceRoot/skills/.\",\n };\n }\n\n const manifestPath = join(target.path, MANIFEST_FILE);\n const existing = await readManifest(manifestPath);\n\n if (existing && !opts.force) {\n const drift = await detectDrift(existing, toInstall);\n if (drift.length > 0) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed: [],\n skipped: toInstall.map((s) => s.name),\n reason: `Drift detected on ${drift.length} skill(s): ${drift.join(\", \")}. Pass --force to overwrite.`,\n manifest_path: manifestPath,\n };\n }\n }\n\n await mkdir(target.path, { recursive: true });\n const installed: string[] = [];\n const skillEntries: { name: string; sha256: string }[] = [];\n for (const skill of toInstall) {\n const destDir = join(target.path, skill.name);\n await copyBundle(skill.dir, destDir);\n const skillFile = join(skill.dir, \"SKILL.md\");\n skillEntries.push({ name: skill.name, sha256: await sha256OfFile(skillFile) });\n installed.push(skill.name);\n }\n\n const manifest: SkillManifest = {\n package: \"@theglitchking/semantic-memory\",\n version: opts.version,\n agent: opts.agent,\n scope: opts.scope,\n installed_at: new Date().toISOString(),\n skills: skillEntries,\n };\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2), \"utf-8\");\n\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed,\n skipped: [],\n manifest_path: manifestPath,\n };\n}\n\nexport interface UninstallOptions {\n agent: AgentName;\n scope: Scope;\n projectRoot: string;\n}\n\nexport interface UninstallResult {\n agent: AgentName;\n scope: Scope;\n target_path: string;\n removed: string[];\n manifest_present: boolean;\n reason?: string;\n}\n\n/**\n * Remove only the skill bundles tracked in the manifest. User-written skills outside\n * the manifest are left untouched.\n */\nexport async function uninstallSkills(opts: UninstallOptions): Promise<UninstallResult> {\n const target = resolveTarget(opts.agent, opts.scope, opts.projectRoot);\n const manifestPath = join(target.path, MANIFEST_FILE);\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n removed: [],\n manifest_present: false,\n reason: \"No semantic-memory manifest found — nothing to uninstall.\",\n };\n }\n const removed: string[] = [];\n for (const skill of manifest.skills) {\n const dir = join(target.path, skill.name);\n if (existsSync(dir)) {\n await rm(dir, { recursive: true, force: true });\n removed.push(skill.name);\n }\n }\n await rm(manifestPath, { force: true });\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n removed,\n manifest_present: true,\n };\n}\n\nasync function readManifest(path: string): Promise<SkillManifest | null> {\n if (!existsSync(path)) return null;\n try {\n const raw = await readFile(path, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (typeof parsed?.package !== \"string\") return null;\n return parsed as SkillManifest;\n } catch {\n return null;\n }\n}\n\nasync function detectDrift(\n existing: SkillManifest,\n toInstall: { name: string; dir: string }[]\n): Promise<string[]> {\n const driftNames: string[] = [];\n const existingByName = new Map(existing.skills.map((s) => [s.name, s.sha256]));\n for (const skill of toInstall) {\n const sourceSha = await sha256OfFile(join(skill.dir, \"SKILL.md\"));\n const existingSha = existingByName.get(skill.name);\n if (existingSha !== undefined && existingSha !== sourceSha) {\n driftNames.push(skill.name);\n }\n }\n return driftNames;\n}\n\nexport const SKILL_BUNDLER_AGENTS: AgentName[] = [\"claude\", \"codex\", \"copilot\", \"pi\"];\n","import { existsSync, mkdirSync, statSync, renameSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * State files that moved/renamed in v1.2.\n *\n * Each entry: legacy path (relative to <projectRoot>/.claude) → new path (relative to\n * <projectRoot>/.claude). Reads in v1.x check new first, fall back to old; writes always\n * go to new. This command does the explicit move so the legacy files stop existing.\n *\n * Order matters only for human-readable output; the migrations themselves are independent.\n */\nconst STATE_MIGRATIONS: { name: string; old: string; new: string }[] = [\n { name: \"mode\", old: \".sidekick-mode\", new: \".semantic-memory/mode\" },\n { name: \"fingerprints\", old: \".sidekick-fingerprints.json\", new: \".semantic-memory/fingerprints.json\" },\n { name: \"capture-pending\", old: \".sidekick-capture-pending.json\", new: \".semantic-memory/capture-pending.json\" },\n];\n\nexport type MigrationStatus = \"migrated\" | \"skipped-no-source\" | \"skipped-already-migrated\" | \"conflict\" | \"resolved-by-force\";\n\nexport interface MigrationFinding {\n name: string;\n status: MigrationStatus;\n oldPath: string;\n newPath: string;\n detail?: string;\n}\n\nexport interface MigrateStateOptions {\n projectRoot: string;\n dryRun?: boolean;\n force?: boolean;\n}\n\nexport interface MigrateStateResult {\n migrated: MigrationFinding[];\n skipped: MigrationFinding[];\n conflicts: MigrationFinding[];\n}\n\n/**\n * Move legacy `.claude/.sidekick-*` state files to the canonical\n * `.claude/.semantic-memory/<name>` paths.\n *\n * Behavior per file:\n * - old exists, new does not → MIGRATE: rename old to new\n * - old does not exist → SKIP (skipped-no-source)\n * - old does not exist, new exists → SKIP (skipped-already-migrated)\n * - both old and new exist → CONFLICT (refused without --force)\n * With --force: prefer new, delete old\n *\n * Idempotent: a second run after a successful migration is all-no-ops.\n */\nexport function migrateState(opts: MigrateStateOptions): MigrateStateResult {\n const result: MigrateStateResult = {\n migrated: [],\n skipped: [],\n conflicts: [],\n };\n\n const stateDir = join(opts.projectRoot, \".claude\", \".semantic-memory\");\n if (!opts.dryRun && !existsSync(stateDir)) {\n mkdirSync(stateDir, { recursive: true });\n }\n\n for (const m of STATE_MIGRATIONS) {\n const oldPath = join(opts.projectRoot, \".claude\", m.old);\n const newPath = join(opts.projectRoot, \".claude\", m.new);\n const oldExists = existsSync(oldPath);\n const newExists = existsSync(newPath);\n\n if (!oldExists && !newExists) {\n result.skipped.push({ name: m.name, status: \"skipped-no-source\", oldPath, newPath, detail: \"neither path exists\" });\n continue;\n }\n if (!oldExists && newExists) {\n result.skipped.push({ name: m.name, status: \"skipped-already-migrated\", oldPath, newPath, detail: \"already at new path\" });\n continue;\n }\n if (oldExists && newExists) {\n if (!opts.force) {\n const oldMtime = safeMtime(oldPath);\n const newMtime = safeMtime(newPath);\n result.conflicts.push({\n name: m.name,\n status: \"conflict\",\n oldPath,\n newPath,\n detail: `both paths exist (old: ${oldMtime}, new: ${newMtime}); pass --force to keep new and delete old`,\n });\n continue;\n }\n // --force: prefer new, delete old\n if (!opts.dryRun) {\n try { unlinkSync(oldPath); } catch (e: any) {\n result.conflicts.push({ name: m.name, status: \"conflict\", oldPath, newPath, detail: `force-delete of old failed: ${e?.message ?? e}` });\n continue;\n }\n }\n result.migrated.push({\n name: m.name,\n status: \"resolved-by-force\",\n oldPath,\n newPath,\n detail: opts.dryRun ? \"dry-run: would delete old\" : \"old deleted; new preserved\",\n });\n continue;\n }\n // oldExists && !newExists → migrate\n if (!opts.dryRun) {\n try { renameSync(oldPath, newPath); } catch (e: any) {\n // Cross-device rename failure is theoretically possible; for state files all\n // under .claude/, both paths are the same filesystem in practice.\n result.conflicts.push({ name: m.name, status: \"conflict\", oldPath, newPath, detail: `rename failed: ${e?.message ?? e}` });\n continue;\n }\n }\n result.migrated.push({\n name: m.name,\n status: \"migrated\",\n oldPath,\n newPath,\n detail: opts.dryRun ? \"dry-run: would rename old to new\" : \"renamed\",\n });\n }\n\n return result;\n}\n\nfunction safeMtime(path: string): string {\n try {\n return statSync(path).mtime.toISOString();\n } catch {\n return \"unknown\";\n }\n}\n"],"mappings":";;;;AAEA,SAAS,eAAe;AACxB,SAAS,WAAAA,UAAS,QAAAC,OAAM,SAAS,gBAAgB;AACjD,SAAS,cAAAC,aAAY,cAAc,eAAe,cAAc;AAChE,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,8BAA8B;;;ACPvC,SAAS,OAAO,UAAU,WAAW,UAAU,SAAS,UAAU;AAClE,SAAS,kBAAkB;AAC3B,SAAS,MAAgB,eAAe;AACxC,SAAS,eAAe;AACxB,SAAS,kBAAkB;AA+B3B,IAAM,gBAAgB;AAMf,SAAS,cAAc,OAAkB,OAAc,aAAsC;AAClG,QAAM,OAAO,QAAQ,WAAW;AAChC,QAAM,OAAO,QAAQ;A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QAAM,SAAS,aAAa;AAAA,IAC1B,aAAa,KAAK;AAAA,IAClB,QAAQ,KAAK,WAAW;AAAA,IACxB,OAAO,KAAK,UAAU;AAAA,EACxB,CAAC;AACD,UAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC3C,MAAI,OAAO,UAAU,SAAS,KAAK,CAAC,KAAK,SAAS,CAAC,KAAK,QAAQ;AAC9D,YAAQ;AAAA,MACN;AAAA,EAAK,OAAO,UAAU,MAAM,YAAY,OAAO,UAAU,WAAW,IAAI,KAAK,GAAG;AAAA,IAClF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;","names":["resolve","join","existsSync","existsSync","join","join","resolve","existsSync","resolve","existsSync","join"]}
1
+ {"version":3,"sources":["../../src/cli/index.ts","../../src/core/healthcheck-fix.ts","../../src/cli/skills.ts","../../src/cli/migrate-state.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { program } from \"commander\";\nimport { resolve, join, dirname, relative } from \"node:path\";\nimport { existsSync, readFileSync, writeFileSync, rmSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { spawnSync } from \"node:child_process\";\nimport { pathToFileURL } from \"node:url\";\nimport { planFixes, type PlannedFix } from \"../core/healthcheck-fix.js\";\nimport { registerUpdateCommands } from \"@theglitchking/claude-plugin-runtime\";\nimport {\n resolveTarget,\n installSkills,\n uninstallSkills,\n listShippedSkills,\n SKILL_BUNDLER_AGENTS,\n type AgentName,\n type Scope,\n} from \"./skills.js\";\nimport { migrateState } from \"./migrate-state.js\";\n\nconst require_ = createRequire(import.meta.url);\nconst { version } = require_(\"../../package.json\") as { version: string };\n\nconst PKG_NAME = \"@theglitchking/semantic-memory\";\nconst LEGACY_PKG_NAME = \"@theglitchking/semantic-sidekick\";\n\nfunction runRelink(cwd: string) {\n const candidates = [\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-memory\", \"scripts\", \"link-skills.js\"),\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-sidekick\", \"scripts\", \"link-skills.js\"),\n resolve(process.cwd(), \"scripts\", \"link-skills.js\"),\n ];\n const script = candidates.find((p) => existsSync(p));\n if (!script) {\n console.error(\"link-skills.js not found — is the package installed?\");\n return;\n }\n spawnSync(process.execPath, [script], {\n cwd,\n env: { ...process.env, INIT_CWD: cwd },\n stdio: \"inherit\",\n });\n}\n\ninterface FixOutcome {\n check: string;\n action: string;\n status: \"fixed\" | \"failed\";\n detail: string;\n}\n\n/**\n * Execute a `--fix` plan. Actions are de-duplicated (running skill-link once\n * covers every skill-link finding) and each is best-effort: a failure is captured\n * as an outcome, never thrown. Returns one outcome per distinct action attempted.\n */\nasync function executeFixes(cwd: string, fixes: PlannedFix[]): Promise<FixOutcome[]> {\n const outcomes: FixOutcome[] = [];\n const actions = [...new Set(fixes.map((f) => f.action))];\n for (const action of actions) {\n const checks = fixes.filter((f) => f.action === action).map((f) => f.check).join(\", \");\n try {\n switch (action) {\n case \"skill-link\": {\n runRelink(cwd);\n outcomes.push({ check: checks, action, status: \"fixed\", detail: \"re-linked skills\" });\n break;\n }\n case \"state-migrate\": {\n const r = migrateState({ projectRoot: cwd, force: true });\n outcomes.push({\n check: checks,\n action,\n status: \"fixed\",\n detail: `migrated ${r.migrated.length} file(s), resolved ${r.conflicts.length} conflict(s)`,\n });\n break;\n }\n case \"mcp-reconcile\": {\n const reconcilePath = join(findSourceRoot(), \"hooks\", \"reconcile.js\");\n if (!existsSync(reconcilePath)) {\n outcomes.push({ check: checks, action, status: \"failed\", detail: \"reconcile.js not found\" });\n break;\n }\n const mod = await import(pathToFileURL(reconcilePath).href);\n mod.reconcile(cwd);\n outcomes.push({ check: checks, action, status: \"fixed\", detail: \"reconciled .mcp.json\" });\n break;\n }\n case \"reindex\": {\n const bin = findLocalBin(cwd);\n if (!bin) {\n outcomes.push({ check: checks, action, status: \"failed\", detail: \"no local bin to run reindex\" });\n break;\n }\n const vault = join(cwd, \".claude\", \".vault\");\n const r = spawnSync(\"node\", [bin, \"--notes\", vault, \"--reindex\"], { cwd, stdio: \"pipe\", timeout: 120_000 });\n if (r.status === 0) {\n outcomes.push({ check: checks, action, status: \"fixed\", detail: \"reindexed vault\" });\n } else {\n outcomes.push({ check: checks, action, status: \"failed\", detail: (r.stderr?.toString() || \"reindex failed\").slice(0, 200) });\n }\n break;\n }\n }\n } catch (err: any) {\n outcomes.push({ check: checks, action, status: \"failed\", detail: err?.message ?? String(err) });\n }\n }\n return outcomes;\n}\n\nfunction findLocalBin(cwd: string): string | null {\n const candidates = [\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-memory\", \"bin\", \"semantic-memory\"),\n join(cwd, \"node_modules\", \"@theglitchking\", \"semantic-sidekick\", \"bin\", \"semantic-sidekick\"),\n ];\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction localBinArg(cwd: string): string | null {\n const abs = findLocalBin(cwd);\n if (!abs) return null;\n const rel = relative(cwd, abs);\n return rel.startsWith(\"..\") ? abs : `./${rel}`;\n}\n\nfunction readJsonSafe(path: string): any {\n try {\n const raw = readFileSync(path, \"utf8\");\n return raw.trim() ? JSON.parse(raw) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the fragile npx-form pattern we used to write in pre-0.10.0\n * SessionStart hooks, so normalize-config can detect and rewrite it.\n */\nfunction isNpxForm(entry: any): boolean {\n if (!entry || typeof entry !== \"object\") return false;\n const cmd = entry.command;\n const args = Array.isArray(entry.args) ? entry.args : [];\n return (\n cmd === \"npx\" &&\n args.some(\n (a: unknown) => typeof a === \"string\" && (a.includes(PKG_NAME) || a.includes(LEGACY_PKG_NAME))\n )\n );\n}\n\nfunction isLocalForm(entry: any): boolean {\n if (!entry || typeof entry !== \"object\") return false;\n const cmd = entry.command;\n const args = Array.isArray(entry.args) ? entry.args : [];\n return (\n cmd === \"node\" &&\n args.some(\n (a: unknown) =>\n typeof a === \"string\" &&\n (a.includes(\"node_modules/@theglitchking/semantic-memory\") ||\n a.includes(\"node_modules/@theglitchking/semantic-sidekick\"))\n )\n );\n}\n\nfunction extractNotesPath(entry: any): string | null {\n const args = Array.isArray(entry?.args) ? entry.args : [];\n const i = args.indexOf(\"--notes\");\n if (i === -1 || i + 1 >= args.length) return null;\n return String(args[i + 1]);\n}\n\nfunction extractExtraFlags(entry: any): string[] {\n const args = Array.isArray(entry?.args) ? entry.args : [];\n return args.filter((a: unknown): a is string => typeof a === \"string\" && a.startsWith(\"--\") && a !== \"--notes\");\n}\n\nconst TOOL_HELP: Record<string, { description: string; args: string; examples: string[] }> = {\n // Search\n search_semantic: {\n description: \"Vector similarity search — find notes by meaning, not just keywords\",\n args: '{ \"query\": \"string\", \"limit?\": 10 }',\n examples: [\n '{ \"query\": \"microservices architecture\", \"limit\": 5 }',\n '{ \"query\": \"how to deploy to production\" }',\n ],\n },\n search_text: {\n description: \"Full-text keyword or regex search with optional filters\",\n args: '{ \"pattern\": \"string\", \"regex?\": false, \"caseSensitive?\": false, \"pathGlob?\": \"string\", \"tagFilter?\": [\"string\"], \"limit?\": 20 }',\n examples: [\n '{ \"pattern\": \"RabbitMQ\" }',\n '{ \"pattern\": \"OAuth\\\\\\\\d\", \"regex\": true }',\n '{ \"pattern\": \"deploy\", \"pathGlob\": \"devops/**\", \"tagFilter\": [\"kubernetes\"] }',\n ],\n },\n search_graph: {\n description: \"Graph traversal — find notes connected to a concept via wikilinks and tags\",\n args: '{ \"concept\": \"string\", \"maxDepth?\": 2 }',\n examples: [\n '{ \"concept\": \"microservices\" }',\n '{ \"concept\": \"auth\", \"maxDepth\": 3 }',\n ],\n },\n search_hybrid: {\n description: \"Combined semantic + graph search — vector results re-ranked by graph proximity\",\n args: '{ \"query\": \"string\", \"limit?\": 10 }',\n examples: [\n '{ \"query\": \"event driven architecture\", \"limit\": 5 }',\n ],\n },\n\n // Read\n read_note: {\n description: \"Read the full content of a specific note by path\",\n args: '{ \"path\": \"string\" }',\n examples: [\n '{ \"path\": \"project-overview.md\" }',\n '{ \"path\": \"notes/meeting-2024-01-15.md\" }',\n ],\n },\n read_multiple_notes: {\n description: \"Batch read multiple notes in one call\",\n args: '{ \"paths\": [\"string\"] }',\n examples: [\n '{ \"paths\": [\"overview.md\", \"architecture.md\", \"deployment.md\"] }',\n ],\n },\n list_notes: {\n description: \"List all indexed notes with metadata (title, tags, link count)\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n\n // Write\n create_note: {\n description: \"Create a new markdown note with optional YAML frontmatter\",\n args: '{ \"path\": \"string\", \"content\": \"string\", \"frontmatter?\": {} }',\n examples: [\n '{ \"path\": \"new-guide.md\", \"content\": \"# Guide\\\\n\\\\nContent here.\" }',\n '{ \"path\": \"tagged.md\", \"content\": \"Content.\", \"frontmatter\": { \"title\": \"Tagged Note\", \"tags\": [\"test\"] } }',\n ],\n },\n update_note: {\n description: \"Edit note content — overwrite, append, prepend, or patch by heading\",\n args: '{ \"path\": \"string\", \"content\": \"string\", \"mode\": \"overwrite|append|prepend|patch-by-heading\", \"heading?\": \"string\" }',\n examples: [\n '{ \"path\": \"guide.md\", \"content\": \"New content.\", \"mode\": \"overwrite\" }',\n '{ \"path\": \"guide.md\", \"content\": \"\\\\n## Appendix\\\\nExtra info.\", \"mode\": \"append\" }',\n '{ \"path\": \"guide.md\", \"content\": \"Updated architecture section.\", \"mode\": \"patch-by-heading\", \"heading\": \"Architecture\" }',\n ],\n },\n delete_note: {\n description: \"Delete a note permanently (requires confirm=true)\",\n args: '{ \"path\": \"string\", \"confirm\": true }',\n examples: [\n '{ \"path\": \"old-note.md\", \"confirm\": true }',\n '{ \"path\": \"old-note.md\", \"confirm\": false } // returns warning, does not delete',\n ],\n },\n move_note: {\n description: \"Move or rename a note — automatically updates wikilinks across the vault\",\n args: '{ \"from\": \"string\", \"to\": \"string\" }',\n examples: [\n '{ \"from\": \"user-service.md\", \"to\": \"auth-service.md\" }',\n '{ \"from\": \"old/note.md\", \"to\": \"new/location/note.md\" }',\n ],\n },\n\n // Metadata\n get_frontmatter: {\n description: \"Read parsed YAML frontmatter from a note as JSON\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"project-overview.md\" }'],\n },\n update_frontmatter: {\n description: \"Set or delete YAML frontmatter keys — pass null to delete a key\",\n args: '{ \"path\": \"string\", \"fields\": {} }',\n examples: [\n '{ \"path\": \"note.md\", \"fields\": { \"status\": \"active\", \"priority\": 1 } }',\n '{ \"path\": \"note.md\", \"fields\": { \"deprecated_field\": null } } // deletes the key',\n ],\n },\n manage_tags: {\n description: \"Add, remove, or list tags on a note (frontmatter and inline)\",\n args: '{ \"path\": \"string\", \"action\": \"add|remove|list\", \"tags?\": [\"string\"] }',\n examples: [\n '{ \"path\": \"note.md\", \"action\": \"list\" }',\n '{ \"path\": \"note.md\", \"action\": \"add\", \"tags\": [\"important\", \"reviewed\"] }',\n '{ \"path\": \"note.md\", \"action\": \"remove\", \"tags\": [\"draft\"] }',\n ],\n },\n rename_tag: {\n description: \"Rename a tag across all notes in the vault (frontmatter + inline)\",\n args: '{ \"oldTag\": \"string\", \"newTag\": \"string\" }',\n examples: ['{ \"oldTag\": \"architecture\", \"newTag\": \"arch\" }'],\n },\n\n // Graph\n backlinks: {\n description: \"Find all notes that link TO a given note via [[wikilinks]]\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"microservices.md\" }'],\n },\n forwardlinks: {\n description: \"Find all notes linked FROM a given note\",\n args: '{ \"path\": \"string\" }',\n examples: ['{ \"path\": \"project-overview.md\" }'],\n },\n graph_path: {\n description: \"Find the shortest path between two notes in the knowledge graph\",\n args: '{ \"from\": \"string\", \"to\": \"string\" }',\n examples: ['{ \"from\": \"project-overview.md\", \"to\": \"user-service.md\" }'],\n },\n graph_statistics: {\n description: \"Knowledge graph stats — most connected nodes, orphans, density\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n\n // System\n get_stats: {\n description: \"Vault and index statistics — note count, chunks, embeddings, graph density\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n reindex: {\n description: \"Force a full reindex of the vault\",\n args: \"{}\",\n examples: [\"{}\"],\n },\n};\n\nconst TOOL_CATEGORIES: Record<string, string[]> = {\n Search: [\"search_semantic\", \"search_text\", \"search_graph\", \"search_hybrid\"],\n Read: [\"read_note\", \"read_multiple_notes\", \"list_notes\"],\n Write: [\"create_note\", \"update_note\", \"delete_note\", \"move_note\"],\n Metadata: [\"get_frontmatter\", \"update_frontmatter\", \"manage_tags\", \"rename_tag\"],\n Graph: [\"backlinks\", \"forwardlinks\", \"graph_path\", \"graph_statistics\"],\n System: [\"get_stats\", \"reindex\"],\n};\n\nfunction printToolList() {\n console.log(\"\\nSemantic Pages — 21 MCP Tools\\n\");\n console.log(\"Usage: These tools are available via MCP when the server is running.\");\n console.log(\" Run `semantic-memory tools <name>` for details on a specific tool.\\n\");\n\n for (const [category, tools] of Object.entries(TOOL_CATEGORIES)) {\n console.log(` ${category}:`);\n for (const name of tools) {\n const tool = TOOL_HELP[name];\n console.log(` ${name.padEnd(24)} ${tool.description}`);\n }\n console.log();\n }\n\n console.log(\"Run `semantic-memory tools <tool-name>` for arguments and examples.\");\n}\n\nfunction printToolDetail(name: string) {\n const tool = TOOL_HELP[name];\n if (!tool) {\n console.error(`Unknown tool: ${name}`);\n console.error(`Run \\`semantic-memory tools\\` to see all available tools.`);\n process.exit(1);\n }\n\n console.log(`\\n ${name}`);\n console.log(` ${\"─\".repeat(name.length)}`);\n console.log(` ${tool.description}\\n`);\n console.log(` Arguments:`);\n console.log(` ${tool.args}\\n`);\n console.log(` Examples:`);\n for (const ex of tool.examples) {\n console.log(` ${ex}`);\n }\n console.log();\n}\n\nprogram\n .name(\"semantic-memory\")\n .description(\n \"Unified memory-layer MCP server for Claude Code (rebrand of semantic-sidekick at v1.0.0).\\n\" +\n \"The `semantic-sidekick` command is preserved as an alias.\\n\\n\" +\n \" Start MCP server: semantic-memory --notes ./vault\\n\" +\n \" Show vault stats: semantic-memory --notes ./vault --stats\\n\" +\n \" Force reindex: semantic-memory --notes ./vault --reindex\\n\" +\n \" List MCP tools: semantic-memory tools\\n\" +\n \" Tool details: semantic-memory tools search_semantic\"\n )\n .version(version);\n\nprogram\n .command(\"search <query>\")\n .description(\"Run a vault search and print top hits as JSON (used by activation hooks)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--limit <n>\", \"Max results\", (v) => parseInt(v, 10), 8)\n .option(\"--text-only\", \"Skip embedder — keyword-only search (fast path, no model init)\")\n .option(\"--json\", \"Emit raw JSON (default)\", true)\n .action(async (query: string, opts) => {\n const { runSearch } = await import(\"./search.js\");\n try {\n const hits = await runSearch({\n notes: opts.notes,\n query,\n limit: opts.limit,\n textOnly: opts.textOnly,\n });\n process.stdout.write(JSON.stringify(hits, null, 2) + \"\\n\");\n process.exit(0);\n } catch (err: any) {\n console.error(`search failed: ${err.message}`);\n process.exit(1);\n }\n });\n\nprogram\n .command(\"lint\")\n .description(\"Lint the vault against vault.schema.yml (schema violations + missing provenance + stale)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--rule <name>\", \"Limit output to one rule: schema_violations | missing_provenance | stale\")\n .option(\"--json\", \"Emit JSON instead of the human-readable report\")\n .option(\"--strict\", \"Exit non-zero on warnings too (default: exit non-zero only on errors)\")\n .action(async (opts) => {\n const { lintVault, formatLintReport } = await import(\"../core/lint.js\");\n const report = await lintVault(resolve(opts.notes));\n // Use console.log + process.exitCode (not process.exit) so Node flushes\n // stdout fully before the process ends. Early process.exit with a large\n // buffered JSON payload can truncate output.\n if (opts.json) {\n const out = opts.rule ? report.byRule[opts.rule as keyof typeof report.byRule] : report;\n console.log(JSON.stringify(out, null, 2));\n } else {\n console.log(formatLintReport(report, { rule: opts.rule }));\n }\n const bad = opts.strict ? report.counts.errors + report.counts.warnings : report.counts.errors;\n process.exitCode = bad > 0 ? 1 : 0;\n });\n\nprogram\n .command(\"log-event\")\n .description(\"Append a structured event to the vault's log.md (used by hooks and CI scripts — same shape as mcp__semantic-vault__log_event)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .requiredOption(\"--kind <name>\", \"Event category: ingest, synthesis, error, mode_change, etc.\")\n .requiredOption(\"--summary <text>\", \"One-line human summary\")\n .option(\"--payload <json>\", \"Structured payload as JSON string\")\n .action(async (opts) => {\n const { logEvent } = await import(\"../core/log.js\");\n let payload: Record<string, unknown> | undefined;\n if (opts.payload) {\n try {\n payload = JSON.parse(opts.payload);\n } catch (e: any) {\n console.error(`invalid --payload JSON: ${e.message}`);\n process.exitCode = 1;\n return;\n }\n }\n try {\n const entry = await logEvent(resolve(opts.notes), {\n kind: opts.kind,\n summary: opts.summary,\n payload,\n });\n console.log(JSON.stringify(entry));\n } catch (e: any) {\n console.error(`log-event failed: ${e.message}`);\n process.exitCode = 1;\n }\n });\n\nprogram\n .command(\"log-query\")\n .description(\"Read structured log entries from log.md — filters by kind, date range, limit\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--kind <name>\", \"Filter by kind (ingest, synthesis, error, mode_change, etc.)\")\n .option(\"--after <iso>\", \"ISO timestamp — only entries on or after\")\n .option(\"--before <iso>\", \"ISO timestamp — only entries on or before\")\n .option(\"--limit <n>\", \"Max entries (most recent)\", (v) => parseInt(v, 10))\n .action(async (opts) => {\n const { logQuery } = await import(\"../core/log.js\");\n try {\n const entries = await logQuery(resolve(opts.notes), {\n kind: opts.kind,\n after: opts.after,\n before: opts.before,\n limit: opts.limit,\n });\n console.log(JSON.stringify(entries));\n } catch (e: any) {\n console.error(`log-query failed: ${e.message}`);\n process.exitCode = 1;\n }\n });\n\nprogram\n .command(\"install-schema\")\n .description(\"Bootstrap vault.schema.yml in the vault root with the default schema\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--force\", \"Overwrite existing schema file\")\n .action(async (opts) => {\n const { installDefaultSchema } = await import(\"../core/schema.js\");\n const r = await installDefaultSchema(resolve(opts.notes), opts.force);\n console.log(r.written ? `Installed default schema: ${r.path}` : `Schema already exists: ${r.path} (use --force to overwrite)`);\n process.exit(0);\n });\n\nprogram\n .command(\"tools [name]\")\n .description(\"List all MCP tools, or show details for a specific tool\")\n .action((name?: string) => {\n if (name) {\n printToolDetail(name);\n } else {\n printToolList();\n }\n process.exit(0);\n });\n\nprogram\n .command(\"serve\", { isDefault: true })\n .description(\"Start the MCP server (default command)\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--reindex\", \"Force full reindex and exit\")\n .option(\"--stats\", \"Show vault statistics and exit\")\n .option(\"--wait-for-ready\", \"Block startup until index is fully built before serving (default: index in background; tools return 'Indexing in progress' until ready)\")\n .option(\"--read-only\", \"Suppress write tools (create_note, update_note, delete_note, move_note, update_frontmatter, manage_tags, rename_tag) — use for shared docs vaults owned by another tool\")\n .option(\"--model <name>\", \"Embedding model to use (default: all-MiniLM-L6-v2, fast; use nomic-ai/nomic-embed-text-v1.5 for higher quality)\")\n .option(\"--workers <n>\", \"Number of worker threads for parallel embedding\", parseInt)\n .option(\"--batch-size <n>\", \"Texts per ONNX forward pass (default: 8)\", parseInt)\n .option(\"--no-quantized\", \"Use full-precision model instead of quantized (slower, slightly higher quality)\")\n .option(\"--no-watch\", \"Disable file watcher\")\n .action(async (opts) => {\n const notesPath = resolve(opts.notes);\n\n if (!existsSync(notesPath)) {\n console.error(`Error: notes directory not found: ${notesPath}`);\n process.exit(1);\n }\n\n if (opts.stats) {\n const { Indexer } = await import(\"../core/indexer.js\");\n const indexer = new Indexer(notesPath);\n const docs = await indexer.indexAll();\n console.log(`Notes: ${docs.length}`);\n console.log(`Chunks: ${docs.reduce((n: number, d: any) => n + d.chunks.length, 0)}`);\n console.log(`Wikilinks: ${docs.reduce((n: number, d: any) => n + d.wikilinks.length, 0)}`);\n console.log(`Tags: ${new Set(docs.flatMap((d: any) => d.tags)).size} unique`);\n process.exit(0);\n }\n\n if (opts.reindex) {\n const { createServer } = await import(\"../mcp/server.js\");\n await createServer(notesPath, {\n watch: false,\n waitForReady: true,\n model: opts.model,\n workers: opts.workers,\n batchSize: opts.batchSize,\n quantized: opts.quantized,\n onProgress: (embedded, total) => {\n process.stderr.write(`\\rEmbedding ${embedded}/${total} chunks...`);\n },\n });\n process.stderr.write(\"\\n\");\n console.log(\"Reindex complete.\");\n process.exit(0);\n }\n\n // Default: start MCP server on stdio\n const { startServer } = await import(\"../mcp/server.js\");\n await startServer(notesPath, {\n watch: opts.watch,\n waitForReady: opts.waitForReady,\n model: opts.model,\n workers: opts.workers,\n batchSize: opts.batchSize,\n quantized: opts.quantized,\n readOnly: opts.readOnly,\n });\n });\n\nregisterUpdateCommands(program, {\n packageName: PKG_NAME,\n pluginName: \"semantic-memory\",\n configFile: \"semantic-memory.json\",\n onAfterUpdate: (cwd) => runRelink(cwd),\n});\n\nprogram\n .command(\"normalize-config\")\n .description(\n \"Rewrite fragile `npx @latest` entries in .mcp.json to the stable node-against-node_modules form (with backup and validation)\",\n )\n .option(\"--dry-run\", \"print the proposed changes but don't write\")\n .action((opts: { dryRun?: boolean }) => {\n const cwd = process.cwd();\n const mcpPath = join(cwd, \".mcp.json\");\n if (!existsSync(mcpPath)) {\n console.log(\"no .mcp.json in current directory — nothing to do\");\n process.exit(0);\n }\n const data = readJsonSafe(mcpPath);\n if (!data || typeof data !== \"object\" || !data.mcpServers || typeof data.mcpServers !== \"object\") {\n console.error(`could not parse ${mcpPath}`);\n process.exit(1);\n }\n const bin = localBinArg(cwd);\n if (!bin) {\n console.error(\n `no local install found at ./node_modules/@theglitchking/semantic-memory/bin/semantic-memory ` +\n `(or the legacy semantic-sidekick path).\\n` +\n `run 'npm install --save @theglitchking/semantic-memory' first, then re-run this command.`,\n );\n process.exit(1);\n }\n const rewritten: string[] = [];\n for (const [key, entry] of Object.entries<any>(data.mcpServers)) {\n if (!isNpxForm(entry)) continue;\n const notes = extractNotesPath(entry) ?? \"./.claude/.vault\";\n const extra = extractExtraFlags(entry);\n data.mcpServers[key] = {\n type: \"stdio\",\n command: \"node\",\n args: [bin, \"--notes\", notes, ...extra],\n };\n rewritten.push(key);\n }\n if (rewritten.length === 0) {\n console.log(\"no npx-form entries found — .mcp.json is already in the stable form.\");\n process.exit(0);\n }\n console.log(`Rewriting ${rewritten.length} entr${rewritten.length === 1 ? \"y\" : \"ies\"}: ${rewritten.join(\", \")}`);\n if (opts.dryRun) {\n console.log(\"--- proposed .mcp.json:\");\n console.log(JSON.stringify(data, null, 2));\n console.log(\"--- (dry-run; no changes written)\");\n process.exit(0);\n }\n // Back up\n const bakPath = join(dirname(mcpPath), \".mcp.json.bak\");\n try {\n writeFileSync(bakPath, readFileSync(mcpPath, \"utf8\"));\n console.log(`backup written: ${bakPath}`);\n } catch (err: any) {\n console.error(`could not write backup: ${err.message}`);\n process.exit(1);\n }\n writeFileSync(mcpPath, JSON.stringify(data, null, 2) + \"\\n\");\n\n // Verify the local bin starts cleanly. We just run --version — fast and\n // enough to catch ERR_MODULE_NOT_FOUND type failures.\n const verify = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (verify.status !== 0) {\n console.error(`verification failed (exit ${verify.status}):\\n${verify.stderr?.toString() || \"\"}`);\n console.error(`rolling back from ${bakPath}`);\n writeFileSync(mcpPath, readFileSync(bakPath, \"utf8\"));\n process.exit(1);\n }\n console.log(`✓ .mcp.json normalized and verified. Toggle the MCPs in /mcp to reconnect.`);\n process.exit(0);\n });\n\nprogram\n .command(\"healthcheck\")\n .description(\n \"Verify the local install starts cleanly + run drift detection. Self-heals common npx-cache corruption (ERR_MODULE_NOT_FOUND). With --fast, skips the slow tier (full vault lint). With --fix, auto-applies safe fixes for fixable findings.\",\n )\n .option(\"--fast\", \"Run only the fast-tier drift checks (file-system probes). Skips the slow tier (full vault lint).\", false)\n .option(\"--json\", \"Emit structured JSON output instead of human-readable text.\", false)\n .option(\"--fix\", \"Auto-apply safe fixes for fixable drift findings (re-link skills, reconcile .mcp.json, reindex, migrate state). Findings that need human review are reported, not touched.\", false)\n .action(async (opts) => {\n const cwd = process.cwd();\n const bin = findLocalBin(cwd);\n if (!bin) {\n console.error(`no local install at ./node_modules/@theglitchking/semantic-memory/bin/semantic-memory (or legacy semantic-sidekick path)`);\n console.error(`run 'npm install --save @theglitchking/semantic-memory' to install.`);\n process.exit(1);\n }\n\n // 1. Warn if .mcp.json uses the fragile form.\n const mcpPath = join(cwd, \".mcp.json\");\n if (existsSync(mcpPath) && !opts.json) {\n const data = readJsonSafe(mcpPath);\n const entries = data?.mcpServers && typeof data.mcpServers === \"object\" ? Object.entries<any>(data.mcpServers) : [];\n const fragile = entries.filter(([, e]) => isNpxForm(e)).map(([k]) => k);\n if (fragile.length > 0) {\n console.warn(`⚠️ .mcp.json uses the fragile npx-@latest form for: ${fragile.join(\", \")}`);\n console.warn(` Rewrite to the stable form:`);\n console.warn(` npx --no @theglitchking/semantic-memory normalize-config`);\n }\n }\n\n // 2. Smoke-test the local bin (with npx-cache self-heal on ERR_MODULE_NOT_FOUND).\n // Unlike prior versions, this does NOT exit early — drift detection and\n // --fix always run afterwards.\n let smokeOk = false;\n let smokeVersion = \"\";\n {\n const r = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (r.status === 0) {\n smokeOk = true;\n smokeVersion = r.stdout?.toString().trim() ?? \"\";\n } else {\n const stderr = r.stderr?.toString() ?? \"\";\n if (stderr.includes(\"ERR_MODULE_NOT_FOUND\")) {\n const match = stderr.match(/([\\/~][^'\"\\s]*\\/_npx\\/[^\\/'\"\\s]+)/);\n if (match) {\n const bad = match[1];\n if (!opts.json) console.warn(`detected broken npx cache at ${bad} — clearing and retrying...`);\n try { rmSync(bad, { recursive: true, force: true }); } catch {}\n const r2 = spawnSync(\"node\", [bin, \"--version\"], { cwd, stdio: \"pipe\", timeout: 15_000 });\n if (r2.status === 0) {\n smokeOk = true;\n smokeVersion = r2.stdout?.toString().trim() ?? \"\";\n } else if (!opts.json) {\n console.error(`retry still failed:\\n${r2.stderr?.toString() || \"\"}`);\n }\n }\n }\n if (!smokeOk && !opts.json && stderr) console.error(stderr);\n }\n }\n if (smokeOk && !opts.json) console.log(`✓ local install starts cleanly (v${smokeVersion})`);\n\n // 3. Run drift detection.\n const { runHealthcheck, formatDriftBanner, filterToDrift } = await import(\"../core/healthcheck.js\");\n const vaultCandidate = join(cwd, \".claude\", \".vault\");\n const vaultPath = existsSync(vaultCandidate) ? vaultCandidate : undefined;\n let result = await runHealthcheck({ projectRoot: cwd, vaultPath, tier: opts.fast ? \"fast\" : \"all\", force: true });\n\n // 4. Apply fixes if requested.\n let fixOutcomes: FixOutcome[] = [];\n let plan = { fixes: [] as PlannedFix[], skipped: [] as { check: string; reason: string }[] };\n if (opts.fix) {\n plan = planFixes(filterToDrift(result));\n if (plan.fixes.length > 0) {\n fixOutcomes = await executeFixes(cwd, plan.fixes);\n // Re-run fast-tier drift to reflect the post-fix state.\n result = await runHealthcheck({ projectRoot: cwd, vaultPath, tier: opts.fast ? \"fast\" : \"all\", force: true });\n }\n }\n\n // 5. Emit.\n if (opts.json) {\n console.log(JSON.stringify({ smoke: { ok: smokeOk, version: smokeVersion }, result, fix: opts.fix ? { plan, outcomes: fixOutcomes } : undefined }, null, 2));\n } else {\n if (opts.fix) {\n if (fixOutcomes.length === 0 && plan.skipped.length === 0) {\n console.log(`\\n✓ nothing to fix`);\n } else {\n console.log(`\\n--fix applied ${fixOutcomes.filter((o) => o.status === \"fixed\").length}/${fixOutcomes.length} action(s):`);\n for (const o of fixOutcomes) console.log(` ${o.status === \"fixed\" ? \"✓\" : \"✗\"} ${o.action} (${o.check}) — ${o.detail}`);\n for (const s of plan.skipped) console.log(` • skipped ${s.check} — ${s.reason}`);\n }\n }\n const banner = formatDriftBanner(result);\n if (banner) {\n console.log(\"\");\n console.log(banner);\n } else {\n console.log(`\\n✓ no drift detected (${result.findings.length} checks ran in ${result.duration_ms}ms)`);\n }\n }\n\n process.exit(smokeOk ? 0 : 1);\n });\n\n// --- Skill bundler (Phase 6) ---\n\nfunction parseAgent(input: string): AgentName {\n const a = input.toLowerCase();\n if (!SKILL_BUNDLER_AGENTS.includes(a as AgentName)) {\n console.error(`Unknown agent: ${input}. Supported: ${SKILL_BUNDLER_AGENTS.join(\", \")}.`);\n process.exit(2);\n }\n return a as AgentName;\n}\n\nfunction parseScope(input: string): Scope {\n if (input !== \"global\" && input !== \"local\") {\n console.error(`Unknown scope: ${input}. Use 'global' or 'local'.`);\n process.exit(2);\n }\n return input;\n}\n\nfunction findSourceRoot(): string {\n // 1. Installed: <cwd>/node_modules/@theglitchking/semantic-sidekick or semantic-memory\n for (const pkg of [\"semantic-memory\", \"semantic-sidekick\"]) {\n const installed = join(process.cwd(), \"node_modules\", \"@theglitchking\", pkg);\n if (existsSync(installed)) return installed;\n }\n // 2. Dev: derive from the bin location (this file lives at <root>/dist/cli/index.js)\n const dev = resolve(new URL(\"../../\", import.meta.url).pathname);\n return dev;\n}\n\nconst skillsCmd = program.command(\"skills\").description(\"Install, target, or uninstall skill bundles for non-Claude agents (codex, copilot, pi). Claude installs continue to use the npm postinstall flow.\");\n\nskillsCmd\n .command(\"targets\")\n .description(\"Preview where skill bundles would be installed for one or more agents.\")\n .option(\"--agent <name...>\", \"One or more agents (default: all). Repeatable.\", undefined as any)\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .action((opts) => {\n const scope = parseScope(opts.scope);\n const agents: AgentName[] = (opts.agent && opts.agent.length > 0 ? opts.agent : SKILL_BUNDLER_AGENTS).map(parseAgent);\n const out = agents.map((a) => resolveTarget(a, scope, opts.project));\n console.log(JSON.stringify(out, null, 2));\n });\n\nskillsCmd\n .command(\"install\")\n .description(\"Install skill bundles into an agent's skill directory. Non-destructive by default; --force to overwrite.\")\n .requiredOption(\"--agent <name>\", \"Agent runtime (claude, codex, copilot, pi)\")\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .option(\"--only <names...>\", \"Restrict to specific skill names (default: all shipped)\")\n .option(\"--force\", \"Overwrite even if drift is detected against an existing manifest\", false)\n .action(async (opts) => {\n const agent = parseAgent(opts.agent);\n const scope = parseScope(opts.scope);\n if (agent === \"claude\") {\n console.error(\n \"Claude skill installs are handled by the npm postinstall (claude-plugin-runtime). \" +\n \"Run `npm install @theglitchking/semantic-memory` instead — that flow symlinks \" +\n \"skills into ~/.claude/skills/ or .claude/skills/ automatically. The skills CLI \" +\n \"is intended for non-Claude agents (codex, copilot, pi) which do not have that \" +\n \"postinstall integration.\"\n );\n process.exit(2);\n }\n const sourceRoot = findSourceRoot();\n const result = await installSkills({\n agent,\n scope,\n sourceRoot,\n projectRoot: opts.project,\n version,\n only: opts.only,\n force: opts.force === true,\n });\n console.log(JSON.stringify(result, null, 2));\n if (result.installed.length === 0 && result.reason) process.exit(1);\n });\n\nskillsCmd\n .command(\"uninstall\")\n .description(\"Remove skill bundles tracked by the semantic-memory manifest. User-written skills outside the manifest are left untouched.\")\n .requiredOption(\"--agent <name>\", \"Agent runtime (claude, codex, copilot, pi)\")\n .option(\"--scope <scope>\", \"global or local (default: local)\", \"local\")\n .option(\"--project <path>\", \"Project root for local-scope paths (default: cwd)\", process.cwd())\n .action(async (opts) => {\n const agent = parseAgent(opts.agent);\n const scope = parseScope(opts.scope);\n if (agent === \"claude\") {\n console.error(\"Claude skill uninstalls go through the npm uninstall flow. The skills CLI is for non-Claude agents.\");\n process.exit(2);\n }\n const result = await uninstallSkills({ agent, scope, projectRoot: opts.project });\n console.log(JSON.stringify(result, null, 2));\n });\n\nskillsCmd\n .command(\"list\")\n .description(\"List the skill bundles shipped with this plugin version.\")\n .action(async () => {\n const sourceRoot = findSourceRoot();\n const shipped = await listShippedSkills(sourceRoot);\n console.log(JSON.stringify(shipped.map((s) => s.name), null, 2));\n });\n\n// --- State migration (Phase 3, v1.2) ---\n\nprogram\n .command(\"migrate-state\")\n .description(\n \"Move legacy .claude/.sidekick-* state files to .claude/.semantic-memory/. Idempotent. \" +\n \"Conflicts (both paths exist) require --force. Pass --dry-run to preview without changes.\",\n )\n .option(\"--dry-run\", \"Print the planned migration without renaming any files.\", false)\n .option(\n \"--force\",\n \"When both old and new paths exist, prefer the new path and delete the old one.\",\n false,\n )\n .option(\"--project <path>\", \"Project root (default: cwd)\", process.cwd())\n .action((opts) => {\n const result = migrateState({\n projectRoot: opts.project,\n dryRun: opts.dryRun === true,\n force: opts.force === true,\n });\n console.log(JSON.stringify(result, null, 2));\n if (result.conflicts.length > 0 && !opts.force && !opts.dryRun) {\n console.error(\n `\\n${result.conflicts.length} conflict${result.conflicts.length === 1 ? \"\" : \"s\"} detected. Re-run with --force to resolve (keeps new path, deletes old).`,\n );\n process.exit(1);\n }\n });\n\n// --- Confidence decay introspection (v1.3) ---\n\nprogram\n .command(\"decay-config\")\n .description(\"Print the active confidence-decay config (shipped defaults + any vault.schema.yml override).\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { loadDecayConfig, DEFAULT_DECAY_CONFIG } = await import(\"../core/decay.js\");\n const cfg = loadDecayConfig(resolve(opts.notes));\n const source = JSON.stringify(cfg) === JSON.stringify(DEFAULT_DECAY_CONFIG) ? \"defaults\" : \"vault.schema.yml (overridden)\";\n console.log(JSON.stringify({ source, config: cfg }, null, 2));\n process.exit(0);\n });\n\nprogram\n .command(\"decay-trace <notePath>\")\n .description(\"Show the decay calculation for one note: type, last_verified, age, half-life, evergreen, multiplier.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (notePath: string, opts) => {\n const { loadDecayConfig, computeDecay, normalizeVerifiedDate } = await import(\"../core/decay.js\");\n const matter = (await import(\"gray-matter\")).default;\n const abs = resolve(opts.notes, notePath);\n if (!existsSync(abs)) {\n console.error(`note not found: ${abs}`);\n process.exit(1);\n }\n const { data: fm } = matter(readFileSync(abs, \"utf8\"));\n const lastVerified = normalizeVerifiedDate(fm.last_verified);\n const d = computeDecay({\n type: typeof fm.type === \"string\" ? fm.type : undefined,\n last_verified: lastVerified,\n evergreen: fm.evergreen === true,\n config: loadDecayConfig(resolve(opts.notes)),\n });\n console.log(\n JSON.stringify(\n {\n path: notePath,\n type: fm.type ?? null,\n last_verified: lastVerified ?? null,\n evergreen: fm.evergreen === true,\n multiplier: d.multiplier,\n age_days: Math.round(d.age_days),\n effective_half_life: d.effective_half_life,\n reason: d.reason,\n },\n null,\n 2\n )\n );\n process.exit(0);\n });\n\n// --- Lexicon (v1.4) ---\n\nconst lexiconCmd = program.command(\"lexicon\").description(\"Manage the learned human→artifact lexicon (aliases).\");\n\nlexiconCmd\n .command(\"list\")\n .description(\"List all aliases in the lexicon.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { loadLexiconCache } = await import(\"../core/lexicon.js\");\n console.log(JSON.stringify(await loadLexiconCache(resolve(opts.notes)), null, 2));\n process.exit(0);\n });\n\nlexiconCmd\n .command(\"compile\")\n .description(\"Rebuild the derived lexicon cache from the lexicon/ notes.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { compileLexicon } = await import(\"../core/lexicon.js\");\n const entries = await compileLexicon(resolve(opts.notes));\n console.log(`compiled ${entries.length} alias(es)`);\n process.exit(0);\n });\n\nlexiconCmd\n .command(\"add <canonical> <phrases...>\")\n .description(\"Upsert an alias: a canonical target and the human phrases that refer to it.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--authored\", \"Mark as human-authored (default: learned)\")\n .action(async (canonical: string, phrases: string[], opts) => {\n const { addAlias } = await import(\"../core/lexicon.js\");\n const r = await addAlias(resolve(opts.notes), { canonical, phrases, source: opts.authored ? \"authored\" : \"learned\" });\n console.log(JSON.stringify(r, null, 2));\n process.exit(0);\n });\n\n// --- Entity dossiers (v1.5 Phase 8) ---\n\nconst dossierCmd = program.command(\"dossier\").description(\"Manage entity dossiers — per-component living notes (purpose / failure modes / knobs / incident log / current state).\");\n\ndossierCmd\n .command(\"init <entity>\")\n .description(\"Scaffold a dossier for an entity (no-op if one already exists). Optionally seed aliases and provenance.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--alias <phrase...>\", \"Human phrase(s) for this entity — fed to the lexicon compiler\")\n .option(\"--seeded-from <ref>\", \"Provenance of the scaffold (e.g. a babel-fish project-map entry)\")\n .action(async (entity: string, opts) => {\n const { initDossier } = await import(\"../core/dossier.js\");\n const r = await initDossier(resolve(opts.notes), entity, { aliases: opts.alias, seeded_from: opts.seededFrom });\n console.log(JSON.stringify(r, null, 2));\n process.exit(0);\n });\n\ndossierCmd\n .command(\"list\")\n .description(\"List all dossiers with their entity, aliases, and current state.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { listDossiers } = await import(\"../core/dossier.js\");\n console.log(JSON.stringify(await listDossiers(resolve(opts.notes)), null, 2));\n process.exit(0);\n });\n\n// --- Speaker profile (v1.5 Phase 11) ---\n\nconst profileCmd = program.command(\"profile\").description(\"Manage the speaker profile — how THIS human communicates (severity calibration, chronic omissions, verbosity, shorthand).\");\n\nprofileCmd\n .command(\"init\")\n .description(\"Scaffold profile/speaker.md with the fixed sections (no-op if it exists).\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { initSpeakerProfile } = await import(\"../core/profile.js\");\n const r = await initSpeakerProfile(resolve(opts.notes));\n console.log(JSON.stringify(r, null, 2));\n process.exit(0);\n });\n\nprofileCmd\n .command(\"show\")\n .description(\"Print the speaker profile's injection head (the capped, placeholder-stripped view).\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .action(async (opts) => {\n const { readSpeakerProfile } = await import(\"../core/profile.js\");\n const p = await readSpeakerProfile(resolve(opts.notes));\n console.log(p ? p.head || \"(profile is empty — only placeholders)\" : \"(no speaker profile — run `profile init`)\");\n process.exit(0);\n });\n\n// --- Selection-logging telemetry introspection (v1.3.1) ---\n\nprogram\n .command(\"selection-stats\")\n .description(\"Summarize the local selection log: searches, selections, most-cited notes, and retrieved-but-never-cited notes.\")\n .requiredOption(\"--notes <path>\", \"Path to markdown notes directory\")\n .option(\"--json\", \"Emit raw JSON instead of a human summary\")\n .action(async (opts) => {\n const { computeSelectionStats, selectionLogPath } = await import(\"../core/telemetry.js\");\n const stats = await computeSelectionStats(resolve(opts.notes));\n if (opts.json) {\n console.log(JSON.stringify(stats, null, 2));\n process.exit(0);\n }\n console.log(`Selection log: ${selectionLogPath(resolve(opts.notes))}`);\n console.log(` searches: ${stats.searches}`);\n console.log(` selections: ${stats.selections}`);\n const topCited = Object.entries(stats.citedPaths).sort((a, b) => b[1] - a[1]).slice(0, 10);\n if (topCited.length) {\n console.log(` most cited:`);\n for (const [p, n] of topCited) console.log(` ${n}× ${p}`);\n }\n if (stats.retrievedNeverCited.length) {\n console.log(` retrieved but never cited (${stats.retrievedNeverCited.length}): ${stats.retrievedNeverCited.slice(0, 10).join(\", \")}${stats.retrievedNeverCited.length > 10 ? \" …\" : \"\"}`);\n }\n process.exit(0);\n });\n\nprogram.parse();\n","import type { DriftFinding } from \"./healthcheck.js\";\n\n/**\n * The `--fix` planner. Pure, side-effect-free: it maps drift findings onto safe\n * auto-fix actions, or explains why a finding needs a human. The CLI executes the\n * plan; keeping the decision logic here makes it unit-testable without spawning.\n *\n * \"Safe\" means: idempotent, non-destructive, and derivable from the install itself\n * (re-link skills, reconcile .mcp.json, rebuild the derived index, migrate state).\n * Anything that touches user-authored content (stale notes, broken wikilinks,\n * hand-edited AGENTS.md) is deliberately NOT auto-fixed — it drops to `skipped`\n * with a pointer to the manual remedy.\n */\n\nexport type FixAction = \"skill-link\" | \"mcp-reconcile\" | \"reindex\" | \"state-migrate\";\n\nexport interface PlannedFix {\n check: string;\n action: FixAction;\n summary: string;\n}\n\nexport interface SkippedFinding {\n check: string;\n reason: string;\n}\n\nexport interface FixPlan {\n fixes: PlannedFix[];\n skipped: SkippedFinding[];\n}\n\n/** Human-readable reason a finding is not auto-fixable. */\nconst MANUAL_REASON: Record<string, string> = {\n \"regenerate-contract\":\n \"AGENTS.md needs a human decision — run `/contract` (regenerate_contract), or move custom content into a Local Notes section outside the managed block.\",\n lint_vault:\n \"Vault lint findings (stale notes, broken wikilinks, schema violations) require human review — run `lint_vault` for the full report.\",\n session_staleness:\n \"Resume the session (session_run / session_finish) or remove .claude/.semantic-memory/session.json to abandon it.\",\n};\n\n/**\n * Build the fix plan from a set of drift findings. Only findings with\n * severity !== \"ok\" are considered.\n */\nexport function planFixes(findings: DriftFinding[]): FixPlan {\n const fixes: PlannedFix[] = [];\n const skipped: SkippedFinding[] = [];\n\n for (const f of findings) {\n if (f.severity === \"ok\") continue;\n\n switch (f.fixable_via) {\n case \"skill-link\":\n fixes.push({ check: f.check, action: \"skill-link\", summary: f.summary });\n break;\n case \"mcp-reconcile\":\n fixes.push({ check: f.check, action: \"mcp-reconcile\", summary: f.summary });\n break;\n case \"reindex\":\n fixes.push({ check: f.check, action: \"reindex\", summary: f.summary });\n break;\n case \"state-migrate\":\n fixes.push({ check: f.check, action: \"state-migrate\", summary: f.summary });\n break;\n case \"regenerate-contract\":\n // The only case this fires is a custom AGENTS.md without managed markers,\n // where regeneration would refuse anyway. Treat as human-review.\n skipped.push({ check: f.check, reason: MANUAL_REASON[\"regenerate-contract\"] });\n break;\n default:\n skipped.push({\n check: f.check,\n reason: MANUAL_REASON[f.check] ?? \"No automatic fix available — needs human review.\",\n });\n }\n }\n\n return { fixes, skipped };\n}\n","import { mkdir, readFile, writeFile, copyFile, readdir, rm } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, basename, resolve } from \"node:path\";\nimport { homedir } from \"node:os\";\nimport { createHash } from \"node:crypto\";\n\nexport type AgentName = \"claude\" | \"codex\" | \"copilot\" | \"pi\";\nexport type Scope = \"global\" | \"local\";\n\nexport interface AgentTargetSpec {\n agent: AgentName;\n scope: Scope;\n /** Absolute resolved path where the skill bundles will land. */\n path: string;\n}\n\nexport interface SkillManifest {\n package: string;\n version: string;\n agent: AgentName;\n scope: Scope;\n installed_at: string;\n skills: { name: string; sha256: string }[];\n}\n\nexport interface InstallResult {\n agent: AgentName;\n scope: Scope;\n target_path: string;\n installed: string[];\n skipped: string[];\n reason?: string;\n manifest_path?: string;\n}\n\nconst MANIFEST_FILE = \".semantic-memory-skill-manifest.json\";\n\n/**\n * Resolve where a given (agent, scope) tuple should land. Project root is required for local\n * scope (to anchor relative paths); for global scope it's not used.\n */\nexport function resolveTarget(agent: AgentName, scope: Scope, projectRoot: string): AgentTargetSpec {\n const root = resolve(projectRoot);\n const home = homedir();\n const map: Record<AgentName, { global: string; local: string }> = {\n claude: { global: join(home, \".claude\", \"skills\"), local: join(root, \".claude\", \"skills\") },\n codex: { global: join(home, \".codex\", \"skills\"), local: join(root, \".codex\", \"skills\") },\n copilot: { global: join(home, \".copilot\", \"skills\"), local: join(root, \".github\", \"skills\") },\n pi: { global: join(home, \".pi\", \"agent\", \"skills\"), local: join(root, \".pi\", \"skills\") },\n };\n return { agent, scope, path: map[agent][scope] };\n}\n\n/**\n * Enumerate the canonical skill bundles shipped by this plugin. Each bundle is a directory\n * under `<sourceRoot>/skills/` containing at least a SKILL.md file. Entries without\n * SKILL.md are silently skipped (allows future non-skill files like `/skills/.gitkeep`).\n */\nexport async function listShippedSkills(sourceRoot: string): Promise<{ name: string; dir: string }[]> {\n const skillsDir = join(sourceRoot, \"skills\");\n if (!existsSync(skillsDir)) return [];\n const entries = await readdir(skillsDir, { withFileTypes: true });\n const out: { name: string; dir: string }[] = [];\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const dir = join(skillsDir, e.name);\n const skillFile = join(dir, \"SKILL.md\");\n if (!existsSync(skillFile)) continue;\n out.push({ name: e.name, dir });\n }\n return out;\n}\n\nasync function sha256OfFile(path: string): Promise<string> {\n const buf = await readFile(path);\n return createHash(\"sha256\").update(buf).digest(\"hex\");\n}\n\n/**\n * Copy a single skill bundle (SKILL.md plus any sibling files in the same directory) into\n * the target directory, overlaying it with the agent name. Returns the list of files written.\n *\n * The target layout is `<targetPath>/<skillName>/SKILL.md` plus mirrored siblings, so each\n * bundle is namespaced and easy to remove later.\n */\nasync function copyBundle(srcDir: string, destDir: string): Promise<string[]> {\n await mkdir(destDir, { recursive: true });\n const entries = await readdir(srcDir, { withFileTypes: true });\n const written: string[] = [];\n for (const e of entries) {\n const src = join(srcDir, e.name);\n const dest = join(destDir, e.name);\n if (e.isDirectory()) {\n const childWritten = await copyBundle(src, dest);\n written.push(...childWritten);\n continue;\n }\n if (!e.isFile()) continue;\n await copyFile(src, dest);\n written.push(dest);\n }\n return written;\n}\n\nexport interface InstallOptions {\n agent: AgentName;\n scope: Scope;\n /** Path to the package's source root (usually the repo root, where `skills/` lives). */\n sourceRoot: string;\n /** Used to anchor local-scope target paths. */\n projectRoot: string;\n /** Plugin version, recorded in the manifest. */\n version: string;\n /** Specific skills to install. When omitted, all shipped skills are installed. */\n only?: string[];\n /**\n * When false, refuse to overwrite an existing install (manifest present + sha mismatch\n * indicates upstream drift). When true, overwrite. Default false.\n */\n force?: boolean;\n}\n\n/**\n * Install all (or selected) skill bundles into an agent's skill directory.\n *\n * Behavior:\n * - Resolves the destination via resolveTarget.\n * - Reads any existing manifest. If a manifest exists, version differs from `version`,\n * AND any skill sha256 differs from the source: this is a drift event. Without\n * `force: true`, returns a refusal with reason \"drift detected\". With force, proceeds\n * and overwrites.\n * - For each shipped skill (or each in `only`), copies the bundle into\n * <target>/<skillName>/, overwriting any existing files in that subdirectory.\n * - Writes a fresh manifest at <target>/<MANIFEST_FILE> recording sha256 of each\n * SKILL.md installed, the plugin version, agent, and scope.\n */\nexport async function installSkills(opts: InstallOptions): Promise<InstallResult> {\n const target = resolveTarget(opts.agent, opts.scope, opts.projectRoot);\n const shipped = await listShippedSkills(opts.sourceRoot);\n const filter = opts.only && opts.only.length > 0 ? new Set(opts.only) : null;\n const toInstall = filter ? shipped.filter((s) => filter.has(s.name)) : shipped;\n\n if (toInstall.length === 0) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed: [],\n skipped: [],\n reason: filter ? `No matching skills found (only=${[...filter].join(\",\")}).` : \"No shipped skills found at sourceRoot/skills/.\",\n };\n }\n\n const manifestPath = join(target.path, MANIFEST_FILE);\n const existing = await readManifest(manifestPath);\n\n if (existing && !opts.force) {\n const drift = await detectDrift(existing, toInstall);\n if (drift.length > 0) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed: [],\n skipped: toInstall.map((s) => s.name),\n reason: `Drift detected on ${drift.length} skill(s): ${drift.join(\", \")}. Pass --force to overwrite.`,\n manifest_path: manifestPath,\n };\n }\n }\n\n await mkdir(target.path, { recursive: true });\n const installed: string[] = [];\n const skillEntries: { name: string; sha256: string }[] = [];\n for (const skill of toInstall) {\n const destDir = join(target.path, skill.name);\n await copyBundle(skill.dir, destDir);\n const skillFile = join(skill.dir, \"SKILL.md\");\n skillEntries.push({ name: skill.name, sha256: await sha256OfFile(skillFile) });\n installed.push(skill.name);\n }\n\n const manifest: SkillManifest = {\n package: \"@theglitchking/semantic-memory\",\n version: opts.version,\n agent: opts.agent,\n scope: opts.scope,\n installed_at: new Date().toISOString(),\n skills: skillEntries,\n };\n await writeFile(manifestPath, JSON.stringify(manifest, null, 2), \"utf-8\");\n\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n installed,\n skipped: [],\n manifest_path: manifestPath,\n };\n}\n\nexport interface UninstallOptions {\n agent: AgentName;\n scope: Scope;\n projectRoot: string;\n}\n\nexport interface UninstallResult {\n agent: AgentName;\n scope: Scope;\n target_path: string;\n removed: string[];\n manifest_present: boolean;\n reason?: string;\n}\n\n/**\n * Remove only the skill bundles tracked in the manifest. User-written skills outside\n * the manifest are left untouched.\n */\nexport async function uninstallSkills(opts: UninstallOptions): Promise<UninstallResult> {\n const target = resolveTarget(opts.agent, opts.scope, opts.projectRoot);\n const manifestPath = join(target.path, MANIFEST_FILE);\n const manifest = await readManifest(manifestPath);\n if (!manifest) {\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n removed: [],\n manifest_present: false,\n reason: \"No semantic-memory manifest found — nothing to uninstall.\",\n };\n }\n const removed: string[] = [];\n for (const skill of manifest.skills) {\n const dir = join(target.path, skill.name);\n if (existsSync(dir)) {\n await rm(dir, { recursive: true, force: true });\n removed.push(skill.name);\n }\n }\n await rm(manifestPath, { force: true });\n return {\n agent: opts.agent,\n scope: opts.scope,\n target_path: target.path,\n removed,\n manifest_present: true,\n };\n}\n\nasync function readManifest(path: string): Promise<SkillManifest | null> {\n if (!existsSync(path)) return null;\n try {\n const raw = await readFile(path, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (typeof parsed?.package !== \"string\") return null;\n return parsed as SkillManifest;\n } catch {\n return null;\n }\n}\n\nasync function detectDrift(\n existing: SkillManifest,\n toInstall: { name: string; dir: string }[]\n): Promise<string[]> {\n const driftNames: string[] = [];\n const existingByName = new Map(existing.skills.map((s) => [s.name, s.sha256]));\n for (const skill of toInstall) {\n const sourceSha = await sha256OfFile(join(skill.dir, \"SKILL.md\"));\n const existingSha = existingByName.get(skill.name);\n if (existingSha !== undefined && existingSha !== sourceSha) {\n driftNames.push(skill.name);\n }\n }\n return driftNames;\n}\n\nexport const SKILL_BUNDLER_AGENTS: AgentName[] = [\"claude\", \"codex\", \"copilot\", \"pi\"];\n","import { existsSync, mkdirSync, statSync, renameSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * State files that moved/renamed in v1.2.\n *\n * Each entry: legacy path (relative to <projectRoot>/.claude) → new path (relative to\n * <projectRoot>/.claude). Reads in v1.x check new first, fall back to old; writes always\n * go to new. This command does the explicit move so the legacy files stop existing.\n *\n * Order matters only for human-readable output; the migrations themselves are independent.\n */\nconst STATE_MIGRATIONS: { name: string; old: string; new: string }[] = [\n { name: \"mode\", old: \".sidekick-mode\", new: \".semantic-memory/mode\" },\n { name: \"fingerprints\", old: \".sidekick-fingerprints.json\", new: \".semantic-memory/fingerprints.json\" },\n { name: \"capture-pending\", old: \".sidekick-capture-pending.json\", new: \".semantic-memory/capture-pending.json\" },\n];\n\nexport type MigrationStatus = \"migrated\" | \"skipped-no-source\" | \"skipped-already-migrated\" | \"conflict\" | \"resolved-by-force\";\n\nexport interface MigrationFinding {\n name: string;\n status: MigrationStatus;\n oldPath: string;\n newPath: string;\n detail?: string;\n}\n\nexport interface MigrateStateOptions {\n projectRoot: string;\n dryRun?: boolean;\n force?: boolean;\n}\n\nexport interface MigrateStateResult {\n migrated: MigrationFinding[];\n skipped: MigrationFinding[];\n conflicts: MigrationFinding[];\n}\n\n/**\n * Move legacy `.claude/.sidekick-*` state files to the canonical\n * `.claude/.semantic-memory/<name>` paths.\n *\n * Behavior per file:\n * - old exists, new does not → MIGRATE: rename old to new\n * - old does not exist → SKIP (skipped-no-source)\n * - old does not exist, new exists → SKIP (skipped-already-migrated)\n * - both old and new exist → CONFLICT (refused without --force)\n * With --force: prefer new, delete old\n *\n * Idempotent: a second run after a successful migration is all-no-ops.\n */\nexport function migrateState(opts: MigrateStateOptions): MigrateStateResult {\n const result: MigrateStateResult = {\n migrated: [],\n skipped: [],\n conflicts: [],\n };\n\n const stateDir = join(opts.projectRoot, \".claude\", \".semantic-memory\");\n if (!opts.dryRun && !existsSync(stateDir)) {\n mkdirSync(stateDir, { recursive: true });\n }\n\n for (const m of STATE_MIGRATIONS) {\n const oldPath = join(opts.projectRoot, \".claude\", m.old);\n const newPath = join(opts.projectRoot, \".claude\", m.new);\n const oldExists = existsSync(oldPath);\n const newExists = existsSync(newPath);\n\n if (!oldExists && !newExists) {\n result.skipped.push({ name: m.name, status: \"skipped-no-source\", oldPath, newPath, detail: \"neither path exists\" });\n continue;\n }\n if (!oldExists && newExists) {\n result.skipped.push({ name: m.name, status: \"skipped-already-migrated\", oldPath, newPath, detail: \"already at new path\" });\n continue;\n }\n if (oldExists && newExists) {\n if (!opts.force) {\n const oldMtime = safeMtime(oldPath);\n const newMtime = safeMtime(newPath);\n result.conflicts.push({\n name: m.name,\n status: \"conflict\",\n oldPath,\n newPath,\n detail: `both paths exist (old: ${oldMtime}, new: ${newMtime}); pass --force to keep new and delete old`,\n });\n continue;\n }\n // --force: prefer new, delete old\n if (!opts.dryRun) {\n try { unlinkSync(oldPath); } catch (e: any) {\n result.conflicts.push({ name: m.name, status: \"conflict\", oldPath, newPath, detail: `force-delete of old failed: ${e?.message ?? e}` });\n continue;\n }\n }\n result.migrated.push({\n name: m.name,\n status: \"resolved-by-force\",\n oldPath,\n newPath,\n detail: opts.dryRun ? \"dry-run: would delete old\" : \"old deleted; new preserved\",\n });\n continue;\n }\n // oldExists && !newExists → migrate\n if (!opts.dryRun) {\n try { renameSync(oldPath, newPath); } catch (e: any) {\n // Cross-device rename failure is theoretically possible; for state files all\n // under .claude/, both paths are the same filesystem in practice.\n result.conflicts.push({ name: m.name, status: \"conflict\", oldPath, newPath, detail: `rename failed: ${e?.message ?? e}` });\n continue;\n }\n }\n result.migrated.push({\n name: m.name,\n status: \"migrated\",\n oldPath,\n newPath,\n detail: opts.dryRun ? \"dry-run: would rename old to new\" : \"renamed\",\n });\n }\n\n return result;\n}\n\nfunction safeMtime(path: string): string {\n try {\n return statSync(path).mtime.toISOString();\n } catch {\n return \"unknown\";\n }\n}\n"],"mappings":";;;;AAEA,SAAS,eAAe;AACxB,SAAS,WAAAA,UAAS,QAAAC,OAAM,SAAS,gBAAgB;AACjD,SAAS,cAAAC,aAAY,cAAc,eAAe,cAAc;AAChE,SAAS,qBAAqB;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;;;AC0B9B,IAAM,gBAAwC;AAAA,EAC5C,uBACE;AAAA,EACF,YACE;AAAA,EACF,mBACE;AACJ;AAMO,SAAS,UAA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K,SAAU,SAAQ,IAAI,OAAO,CAAC,SAAM,CAAC,EAAE;AAAA,EAC9D;AACA,MAAI,MAAM,oBAAoB,QAAQ;AACpC,YAAQ,IAAI,gCAAgC,MAAM,oBAAoB,MAAM,MAAM,MAAM,oBAAoB,MAAM,GAAG,EAAE,EAAE,KAAK,IAAI,CAAC,GAAG,MAAM,oBAAoB,SAAS,KAAK,YAAO,EAAE,EAAE;AAAA,EAC3L;AACA,UAAQ,KAAK,CAAC;AAChB,CAAC;AAEH,QAAQ,MAAM;","names":["resolve","join","existsSync","existsSync","join","join","resolve","existsSync","resolve","existsSync","join"]}
@@ -252,7 +252,7 @@ interface VaultSchema {
252
252
  type Severity$1 = "warn" | "error";
253
253
  interface LintFinding {
254
254
  path: string;
255
- rule: "missing_provenance" | "stale" | "schema_violations" | "broken_links";
255
+ rule: "missing_provenance" | "stale" | "schema_violations" | "broken_links" | "code_symbols" | "decay_candidates" | "alias_conflicts" | "decoys";
256
256
  severity: Severity$1;
257
257
  message: string;
258
258
  }
@@ -443,6 +443,8 @@ interface SynthesizeNoteInput {
443
443
  decision_maker?: string;
444
444
  decided_on?: string;
445
445
  severity?: string;
446
+ /** Verbatim symptom phrases (the user's own words) — symptom-keyed for retrieval. */
447
+ symptoms?: string[];
446
448
  extra_frontmatter?: Record<string, unknown>;
447
449
  /**
448
450
  * When true, the resulting note is filed under `proposals/<date>-<slug>.md` with
@@ -524,6 +526,10 @@ interface LintReport {
524
526
  missing_provenance: LintFinding[];
525
527
  stale: LintFinding[];
526
528
  broken_links: LintFinding[];
529
+ code_symbols: LintFinding[];
530
+ decay_candidates: LintFinding[];
531
+ alias_conflicts: LintFinding[];
532
+ decoys: LintFinding[];
527
533
  };
528
534
  counts: {
529
535
  errors: number;
@@ -535,6 +541,37 @@ declare function lintVault(notesPath: string, opts?: {
535
541
  pathGlob?: string;
536
542
  schemaOverride?: VaultSchema;
537
543
  todayIso?: string;
544
+ /**
545
+ * When true, run the code-symbol drift check: flag inline-code file-path
546
+ * references in notes that no longer exist under the project root. Opt-in
547
+ * (off by default) so the standard report and the healthcheck slow tier stay
548
+ * quiet and byte-stable. Fails open when the project root is not a code repo.
549
+ */
550
+ checkCodeSymbols?: boolean;
551
+ /** Override the project root for code-symbol resolution (default: derived from notesPath). */
552
+ projectRoot?: string;
553
+ /**
554
+ * When true, run the decay-candidates check: cross-reference the selection
555
+ * log (notes that appeared in recent search results) against each note's
556
+ * current decay multiplier, and flag notes that are frequently retrieved yet
557
+ * heavily decayed ("relevant but going stale — verify or revise"). Opt-in;
558
+ * a silent no-op when no selection log exists.
559
+ */
560
+ checkDecayCandidates?: boolean;
561
+ /**
562
+ * When true, run the alias-conflict check: flag lexicon phrases that map to
563
+ * more than one canonical target (a wrong binding misroutes queries). Opt-in;
564
+ * no-op when the vault has no lexicon.
565
+ */
566
+ checkAliasConflicts?: boolean;
567
+ /**
568
+ * When true, run the decoys check: flag notes that were retrieved often (per
569
+ * the selection log) but NEVER cited in an answer. Surfaced for a human to
570
+ * judge — a decoy might be genuine noise OR a note the answers were wrong to
571
+ * skip; usage-feedback ranking (v1.5) never auto-down-ranks on this ambiguous
572
+ * signal (decision Q5). Opt-in; a no-op with no selection log.
573
+ */
574
+ checkDecoys?: boolean;
538
575
  }): Promise<LintReport>;
539
576
  declare function formatLintReport(report: LintReport, opts?: {
540
577
  rule?: keyof LintReport["byRule"];
@@ -704,7 +741,7 @@ interface DriftFinding {
704
741
  severity: Severity;
705
742
  summary: string;
706
743
  detail?: string;
707
- fixable_via?: "skill-link" | "mcp-reconcile" | "regenerate-contract" | "reindex" | "none";
744
+ fixable_via?: "skill-link" | "mcp-reconcile" | "regenerate-contract" | "reindex" | "state-migrate" | "none";
708
745
  }
709
746
  interface HealthcheckResult {
710
747
  tier_run: Tier;
@@ -2,26 +2,35 @@ import {
2
2
  filterToDrift,
3
3
  formatDriftBanner,
4
4
  runHealthcheck
5
- } from "../chunk-EVAJGOCB.js";
5
+ } from "../chunk-2EELGTLX.js";
6
6
  import {
7
7
  FrontmatterManager,
8
8
  INDEX_FILE,
9
9
  INDEX_OVERFLOW_THRESHOLD,
10
10
  NoteCrud,
11
- SessionManager,
12
11
  TagManager,
13
12
  Watcher,
14
13
  applyPatch,
15
14
  buildIngestChangeSet,
16
15
  buildPromoteChangeSet,
17
16
  buildSynthesizeChangeSet,
18
- deriveProjectRoot,
19
- deriveSessionDir,
20
17
  inspectAgentsContract,
21
18
  regenDirectoryIndex,
22
19
  regenIndexesForPaths,
23
20
  regenerateAgentsContract
24
- } from "../chunk-CYWPDFNI.js";
21
+ } from "../chunk-CSXZ7QUU.js";
22
+ import {
23
+ formatLintReport,
24
+ lintVault
25
+ } from "../chunk-FM26NFTR.js";
26
+ import "../chunk-NTYYS53O.js";
27
+ import "../chunk-A3KYHKB5.js";
28
+ import "../chunk-WSU4QIPB.js";
29
+ import {
30
+ SessionManager,
31
+ deriveProjectRoot,
32
+ deriveSessionDir
33
+ } from "../chunk-S4KW7VH4.js";
25
34
  import {
26
35
  Embedder,
27
36
  GraphBuilder,
@@ -30,20 +39,17 @@ import {
30
39
  } from "../chunk-25EIQWXL.js";
31
40
  import {
32
41
  Indexer
33
- } from "../chunk-HODDRXJK.js";
42
+ } from "../chunk-V45NJIHI.js";
34
43
  import {
35
44
  logEvent,
36
45
  logQuery
37
46
  } from "../chunk-JPQHNG3R.js";
38
- import {
39
- formatLintReport,
40
- lintVault
41
- } from "../chunk-CAN2GWUG.js";
42
47
  import {
43
48
  installDefaultSchema,
44
49
  loadSchema,
45
50
  validateNote
46
- } from "../chunk-E2Z4J4MK.js";
51
+ } from "../chunk-OWZWMB4P.js";
52
+ import "../chunk-5ZKNO6ZD.js";
47
53
  import "../chunk-PZ5AY32C.js";
48
54
  export {
49
55
  Embedder,
@@ -0,0 +1,14 @@
1
+ import {
2
+ DEFAULT_DECAY_CONFIG,
3
+ computeDecay,
4
+ loadDecayConfig,
5
+ normalizeVerifiedDate
6
+ } from "./chunk-5ZKNO6ZD.js";
7
+ import "./chunk-PZ5AY32C.js";
8
+ export {
9
+ DEFAULT_DECAY_CONFIG,
10
+ computeDecay,
11
+ loadDecayConfig,
12
+ normalizeVerifiedDate
13
+ };
14
+ //# sourceMappingURL=decay-ELJUKVQG.js.map
@@ -0,0 +1,39 @@
1
+ import {
2
+ DOSSIER_DIR,
3
+ DOSSIER_SECTIONS,
4
+ appendIncident,
5
+ appendToSection,
6
+ compileDossiers,
7
+ dossierTemplate,
8
+ findDossier,
9
+ initDossier,
10
+ listDossiers,
11
+ loadDossierCache,
12
+ normalizeEntity,
13
+ replaceSectionBody,
14
+ resolveDossierForQuery,
15
+ resolveDossierPath,
16
+ setCurrentState,
17
+ slugifyEntity
18
+ } from "./chunk-WSU4QIPB.js";
19
+ import "./chunk-S4KW7VH4.js";
20
+ import "./chunk-PZ5AY32C.js";
21
+ export {
22
+ DOSSIER_DIR,
23
+ DOSSIER_SECTIONS,
24
+ appendIncident,
25
+ appendToSection,
26
+ compileDossiers,
27
+ dossierTemplate,
28
+ findDossier,
29
+ initDossier,
30
+ listDossiers,
31
+ loadDossierCache,
32
+ normalizeEntity,
33
+ replaceSectionBody,
34
+ resolveDossierForQuery,
35
+ resolveDossierPath,
36
+ setCurrentState,
37
+ slugifyEntity
38
+ };
39
+ //# sourceMappingURL=dossier-2UG724LB.js.map