sensemaking 0.5.0 → 0.7.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 (108) hide show
  1. package/README.md +13 -6
  2. package/dist/cjs/cli.js +8 -1
  3. package/dist/cjs/cli.js.map +1 -1
  4. package/dist/cjs/commands/check.d.cts +3 -0
  5. package/dist/cjs/commands/check.d.ts +3 -0
  6. package/dist/cjs/commands/check.js +130 -0
  7. package/dist/cjs/commands/check.js.map +1 -0
  8. package/dist/cjs/commands/find.js +173 -10
  9. package/dist/cjs/commands/find.js.map +1 -1
  10. package/dist/cjs/commands/index.js +5 -0
  11. package/dist/cjs/commands/index.js.map +1 -1
  12. package/dist/cjs/commands/map.js +1 -1
  13. package/dist/cjs/commands/map.js.map +1 -1
  14. package/dist/cjs/commands/peek.js +1 -1
  15. package/dist/cjs/commands/peek.js.map +1 -1
  16. package/dist/cjs/commands/shared.d.cts +1 -1
  17. package/dist/cjs/commands/shared.d.ts +1 -1
  18. package/dist/cjs/commands/shared.js +166 -8
  19. package/dist/cjs/commands/shared.js.map +1 -1
  20. package/dist/cjs/commands/status.js +72 -5
  21. package/dist/cjs/commands/status.js.map +1 -1
  22. package/dist/cjs/commands/types.d.cts +1 -0
  23. package/dist/cjs/commands/types.d.ts +1 -0
  24. package/dist/cjs/config.d.cts +32 -2
  25. package/dist/cjs/config.d.ts +32 -2
  26. package/dist/cjs/config.js +199 -11
  27. package/dist/cjs/config.js.map +1 -1
  28. package/dist/cjs/db.d.cts +1 -1
  29. package/dist/cjs/db.d.ts +1 -1
  30. package/dist/cjs/db.js +47 -17
  31. package/dist/cjs/db.js.map +1 -1
  32. package/dist/cjs/errors.d.cts +1 -1
  33. package/dist/cjs/errors.d.ts +1 -1
  34. package/dist/cjs/errors.js.map +1 -1
  35. package/dist/cjs/features/embed.d.cts +15 -0
  36. package/dist/cjs/features/embed.d.ts +15 -0
  37. package/dist/cjs/features/embed.js +844 -0
  38. package/dist/cjs/features/embed.js.map +1 -0
  39. package/dist/cjs/features/index.js +3 -1
  40. package/dist/cjs/features/index.js.map +1 -1
  41. package/dist/cjs/features/types.d.cts +4 -1
  42. package/dist/cjs/features/types.d.ts +4 -1
  43. package/dist/cjs/index.d.cts +1 -1
  44. package/dist/cjs/index.d.ts +1 -1
  45. package/dist/cjs/index.js.map +1 -1
  46. package/dist/cjs/output.d.cts +5 -0
  47. package/dist/cjs/output.d.ts +5 -0
  48. package/dist/cjs/output.js +48 -9
  49. package/dist/cjs/output.js.map +1 -1
  50. package/dist/cjs/scan.d.cts +1 -1
  51. package/dist/cjs/scan.d.ts +1 -1
  52. package/dist/cjs/scan.js +17 -10
  53. package/dist/cjs/scan.js.map +1 -1
  54. package/dist/cjs/verbs.d.cts +8 -2
  55. package/dist/cjs/verbs.d.ts +8 -2
  56. package/dist/cjs/verbs.js +308 -81
  57. package/dist/cjs/verbs.js.map +1 -1
  58. package/dist/esm/cli.js +8 -1
  59. package/dist/esm/cli.js.map +1 -1
  60. package/dist/esm/commands/check.d.ts +3 -0
  61. package/dist/esm/commands/check.js +56 -0
  62. package/dist/esm/commands/check.js.map +1 -0
  63. package/dist/esm/commands/find.js +5 -4
  64. package/dist/esm/commands/find.js.map +1 -1
  65. package/dist/esm/commands/index.js +1 -0
  66. package/dist/esm/commands/index.js.map +1 -1
  67. package/dist/esm/commands/map.js +1 -3
  68. package/dist/esm/commands/map.js.map +1 -1
  69. package/dist/esm/commands/peek.js +1 -1
  70. package/dist/esm/commands/peek.js.map +1 -1
  71. package/dist/esm/commands/shared.d.ts +1 -1
  72. package/dist/esm/commands/shared.js +2 -2
  73. package/dist/esm/commands/shared.js.map +1 -1
  74. package/dist/esm/commands/status.js +43 -5
  75. package/dist/esm/commands/status.js.map +1 -1
  76. package/dist/esm/commands/types.d.ts +1 -0
  77. package/dist/esm/commands/types.js.map +1 -1
  78. package/dist/esm/config.d.ts +32 -2
  79. package/dist/esm/config.js +98 -9
  80. package/dist/esm/config.js.map +1 -1
  81. package/dist/esm/db.d.ts +1 -1
  82. package/dist/esm/db.js +20 -11
  83. package/dist/esm/db.js.map +1 -1
  84. package/dist/esm/errors.d.ts +1 -1
  85. package/dist/esm/errors.js.map +1 -1
  86. package/dist/esm/features/embed.d.ts +15 -0
  87. package/dist/esm/features/embed.js +299 -0
  88. package/dist/esm/features/embed.js.map +1 -0
  89. package/dist/esm/features/index.js +3 -1
  90. package/dist/esm/features/index.js.map +1 -1
  91. package/dist/esm/features/types.d.ts +4 -1
  92. package/dist/esm/features/types.js.map +1 -1
  93. package/dist/esm/index.d.ts +1 -1
  94. package/dist/esm/index.js.map +1 -1
  95. package/dist/esm/output.d.ts +5 -0
  96. package/dist/esm/output.js +40 -8
  97. package/dist/esm/output.js.map +1 -1
  98. package/dist/esm/scan.d.ts +1 -1
  99. package/dist/esm/scan.js +17 -10
  100. package/dist/esm/scan.js.map +1 -1
  101. package/dist/esm/verbs.d.ts +8 -2
  102. package/dist/esm/verbs.js +92 -18
  103. package/dist/esm/verbs.js.map +1 -1
  104. package/package.json +2 -1
  105. package/schema.json +35 -1
  106. package/skills/sense/EXAMPLES.md +16 -0
  107. package/skills/sense/SKILL.md +60 -20
  108. package/skills/sense-setup/SKILL.md +91 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/verbs.ts"],"sourcesContent":["import posix from 'node:path/posix';\nimport type { DatabaseSync } from 'node:sqlite';\nimport type { Config } from './config.ts';\nimport { featureEnabled } from './config.ts';\nimport { SenseError } from './errors.ts';\nimport { linkEdges } from './features/index.ts';\nimport { personalizedRank } from './graph.ts';\nimport type { Row } from './output.ts';\n\n// The three layer verbs: mapTree (orient), find (locate), peek (structure).\n// Each returns data; cli.ts renders. All of them degrade when a feature is off.\n\nconst WEIGHTED_BM25 = 'bm25(content, 10.0, 5.0, 1.0)';\nconst RRF_K = 60;\n\nexport interface FindOptions {\n k?: number;\n where?: string; // SQL fragment against frontmatter alias `f`, e.g. \"f.status = 'active'\"\n}\n\n// Layer 1: BM25 + link-graph expansion, fused by reciprocal rank. `via` says which\n// signal produced each row so the agent knows what evidence it is trusting.\nexport function find(db: DatabaseSync, cfg: Config, terms: string, opts: FindOptions = {}): Row[] {\n const k = opts.k ?? 10;\n const fetch = Math.max(k * 3, 30);\n\n // Terms pass verbatim to FTS5 MATCH: bare words AND-join, operators are the caller's.\n // Invalid syntax propagates as an error, zero matches return zero -- no silent rewrites.\n // --where applies inside the candidate query (a post-filter over the top-N would drop\n // matches ranked past the pool) and again on the final select for link-derived rows.\n const whereJoin = opts.where ? `JOIN frontmatter f ON f.\"path\" = content.path` : '';\n const whereCond = opts.where ? `AND (${opts.where})` : '';\n const matchSql = `SELECT content.path AS path, snippet(content, -1, '«', '»', '…', 10) AS hit FROM content ${whereJoin} WHERE content MATCH ? ${whereCond} ORDER BY ${WEIGHTED_BM25} LIMIT ${fetch}`;\n const matchRows = db.prepare(matchSql).all(terms) as Array<{ path: string; hit: string }>;\n\n const hits = new Map(matchRows.map((r) => [r.path, r.hit]));\n const candidates = new Map<string, { score: number; via: string }>();\n matchRows.forEach((r, i) => {\n candidates.set(r.path, { score: 1 / (RRF_K + i), via: 'match' });\n });\n\n if (featureEnabled(cfg, 'links') && matchRows.length > 0) {\n const nodes = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n const seeds = new Map(matchRows.map((r, i) => [r.path, 1 / (i + 1)]));\n const ranked = [...personalizedRank(nodes, linkEdges(db), seeds)]\n .filter(([, score]) => score > 1e-9)\n .sort((a, b) => b[1] - a[1])\n .slice(0, fetch);\n ranked.forEach(([path], i) => {\n const existing = candidates.get(path);\n if (existing) {\n existing.score += 1 / (RRF_K + i);\n existing.via = 'match+link';\n } else {\n candidates.set(path, { score: 1 / (RRF_K + i), via: 'link' });\n }\n });\n }\n\n db.exec('CREATE TEMP TABLE IF NOT EXISTS _find (\"path\" TEXT PRIMARY KEY, score REAL, via TEXT, hit TEXT)');\n db.exec('DELETE FROM _find');\n const insert = db.prepare('INSERT INTO _find (\"path\", score, via, hit) VALUES (?, ?, ?, ?)');\n for (const [path, c] of candidates) insert.run(path, c.score, c.via, hits.get(path) ?? null);\n\n const where = opts.where ? `WHERE ${opts.where}` : '';\n return db\n .prepare(\n `SELECT f.\"path\" AS path, content.title, content.summary, _find.hit, _find.via, round(_find.score, 4) AS score\n FROM _find JOIN frontmatter f ON f.\"path\" = _find.\"path\" JOIN content ON content.path = _find.\"path\"\n ${where} ORDER BY _find.score DESC LIMIT ?`\n )\n .all(k) as Row[];\n}\n\nexport interface TreeMap {\n docs: { count: number; bytes: number };\n fields: Row[]; // top 20 by coverage; fieldsTotal carries the real count\n fieldsTotal: number;\n hubs: Row[];\n recent: Row[];\n}\n\nconst INTERNAL_COLUMNS = new Set(['path', '_mtime', '_size', '_rank']);\n\n// Layer 0: what is this tree. Fixed-size output regardless of tree size.\nexport function mapTree(db: DatabaseSync, cfg: Config): TreeMap {\n const docs = db.prepare('SELECT COUNT(*) AS count, COALESCE(SUM(\"_size\"), 0) AS bytes FROM frontmatter').get() as { count: number; bytes: number };\n\n const columns = (db.prepare('PRAGMA table_info(frontmatter)').all() as Array<{ name: string }>).map((r) => r.name).filter((name) => !INTERNAL_COLUMNS.has(name));\n const allFields = columns\n .map((name) => {\n const { n } = db.prepare(`SELECT COUNT(\"${name.split('\"').join('\"\"')}\") AS n FROM frontmatter`).get() as { n: number };\n return { field: name, coverage: n };\n })\n .sort((a, b) => (b.coverage as number) - (a.coverage as number)) as Row[];\n const fields = allFields.slice(0, 20);\n\n const hubs = featureEnabled(cfg, 'rank') ? (db.prepare(`SELECT f.\"path\" AS path, round(f.\"_rank\" * 100, 2) AS rank, content.title FROM frontmatter f JOIN content ON content.path = f.\"path\" WHERE f.\"_rank\" IS NOT NULL ORDER BY f.\"_rank\" DESC LIMIT 8`).all() as Row[]) : [];\n\n const recent = db.prepare(`SELECT \"path\", datetime(\"_mtime\" / 1000, 'unixepoch') AS modified FROM frontmatter ORDER BY \"_mtime\" DESC LIMIT 5`).all() as Row[];\n\n return { docs, fields, fieldsTotal: allFields.length, hubs, recent };\n}\n\nexport interface Peek {\n path: string;\n tokens: number;\n frontmatter: Row;\n sections: Row[];\n outbound: string[];\n backlinks: string[];\n unresolved: string[];\n // Totals before truncation: a hub can have thousands of backlinks, and peek's whole\n // point is bounded output. Query the links table directly for the full list.\n outboundTotal: number;\n backlinksTotal: number;\n unresolvedTotal: number;\n}\n\nconst PEEK_LINK_LIMIT = 20;\n\n// Layer 2: everything about one note except its prose -- frontmatter, outline with line\n// ranges + token estimates (so the follow-up Read is a range, not the file), links both ways.\nexport function peek(db: DatabaseSync, cfg: Config, pathArg: string): Peek {\n const paths = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n let path = paths.find((p) => p === pathArg);\n if (!path) {\n const base = posix.basename(pathArg).replace(/\\.md$/i, '').toLowerCase();\n const matches = paths.filter((p) => posix.basename(p).replace(/\\.md$/i, '').toLowerCase() === base);\n if (matches.length === 1) path = matches[0];\n else if (matches.length > 1) throw new SenseError('NOTE_AMBIGUOUS', `\"${pathArg}\" is ambiguous: ${matches.join(', ')}`);\n else throw new SenseError('NOTE_NOT_FOUND', `no note matches \"${pathArg}\"`);\n }\n\n const row = db.prepare('SELECT * FROM frontmatter WHERE \"path\" = ?').get(path) as Row;\n const frontmatter: Row = {};\n for (const [key, value] of Object.entries(row)) {\n if (!INTERNAL_COLUMNS.has(key) && value !== null) frontmatter[key] = value;\n }\n\n const sections = featureEnabled(cfg, 'sections') ? (db.prepare('SELECT level, heading, start_line, end_line, tokens FROM sections WHERE \"path\" = ? ORDER BY idx').all(path) as Row[]) : [];\n\n let outbound: string[] = [];\n let backlinks: string[] = [];\n let unresolved: string[] = [];\n let backlinksTotal = 0;\n if (featureEnabled(cfg, 'links')) {\n const out = db.prepare('SELECT target, dst FROM links WHERE src = ? ORDER BY target').all(path) as Array<{ target: string; dst: string | null }>;\n outbound = [...new Set(out.filter((l) => l.dst !== null).map((l) => l.dst as string))];\n unresolved = out.filter((l) => l.dst === null).map((l) => l.target);\n backlinksTotal = (db.prepare('SELECT COUNT(DISTINCT src) AS n FROM links WHERE dst = ?').get(path) as { n: number }).n;\n backlinks = (db.prepare('SELECT DISTINCT src FROM links WHERE dst = ? ORDER BY src LIMIT ?').all(path, PEEK_LINK_LIMIT) as Array<{ src: string }>).map((r) => r.src);\n }\n\n return {\n path,\n tokens: Math.ceil(((row._size as number) ?? 0) / 4),\n frontmatter,\n sections,\n outbound: outbound.slice(0, PEEK_LINK_LIMIT),\n backlinks,\n unresolved: unresolved.slice(0, PEEK_LINK_LIMIT),\n outboundTotal: outbound.length,\n backlinksTotal,\n unresolvedTotal: unresolved.length,\n };\n}\n"],"names":["posix","featureEnabled","SenseError","linkEdges","personalizedRank","WEIGHTED_BM25","RRF_K","find","db","cfg","terms","opts","hits","k","fetch","Math","max","whereJoin","where","whereCond","matchSql","matchRows","prepare","all","Map","map","r","path","hit","candidates","forEach","i","set","score","via","length","nodes","seeds","ranked","filter","sort","a","b","slice","existing","get","exec","insert","c","run","INTERNAL_COLUMNS","Set","mapTree","docs","columns","name","has","allFields","n","split","join","field","coverage","fields","hubs","recent","fieldsTotal","PEEK_LINK_LIMIT","peek","pathArg","row","paths","p","base","basename","replace","toLowerCase","matches","frontmatter","key","value","Object","entries","sections","outbound","backlinks","unresolved","backlinksTotal","out","l","dst","target","src","tokens","ceil","_size","outboundTotal","unresolvedTotal"],"mappings":"AAAA,OAAOA,WAAW,kBAAkB;AAGpC,SAASC,cAAc,QAAQ,cAAc;AAC7C,SAASC,UAAU,QAAQ,cAAc;AACzC,SAASC,SAAS,QAAQ,sBAAsB;AAChD,SAASC,gBAAgB,QAAQ,aAAa;AAG9C,4EAA4E;AAC5E,gFAAgF;AAEhF,MAAMC,gBAAgB;AACtB,MAAMC,QAAQ;AAOd,mFAAmF;AACnF,4EAA4E;AAC5E,OAAO,SAASC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B,GAAG,CAAClB,MAAwB+B,CAAC;QACtH2B,YAAY,AAAC7E,GAAGc,OAAO,CAAC,qEAAqEC,GAAG,CAACI,MAAMwC,iBAA4C1C,GAAG,CAAC,CAACC,IAAMA,EAAEkE,GAAG;IACrK;IAEA,OAAO;QACLjE;QACAkE,QAAQ9E,KAAK+E,IAAI,CAAC,EAAExB,aAAAA,IAAIyB,KAAK,cAATzB,wBAAAA,aAAwB,KAAK;QACjDQ;QACAK;QACAC,UAAUA,SAASzC,KAAK,CAAC,GAAGwB;QAC5BkB;QACAC,YAAYA,WAAW3C,KAAK,CAAC,GAAGwB;QAChC6B,eAAeZ,SAASjD,MAAM;QAC9BoD;QACAU,iBAAiBX,WAAWnD,MAAM;IACpC;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/verbs.ts"],"sourcesContent":["import posix from 'node:path/posix';\nimport type { DatabaseSync } from 'node:sqlite';\nimport type { Config, FeatureName } from './config.ts';\nimport { featureEnabled, featureStates } from './config.ts';\nimport { SenseError } from './errors.ts';\nimport { semanticCandidates } from './features/embed.ts';\nimport { linkEdges } from './features/index.ts';\nimport { personalizedRank } from './graph.ts';\nimport type { Row } from './output.ts';\n\n// The three layer verbs: mapTree (orient), find (locate), peek (structure).\n// Each returns data; cli.ts renders. All of them degrade when a feature is off.\n\nconst WEIGHTED_BM25 = 'bm25(content, 10.0, 5.0, 1.0)';\nconst RRF_K = 60;\n\n// FTS5 reads these as operators, so a bare term containing one is a syntax error or --\n// worse -- a column filter: `end-to-end` parses as a filter on column `to`, and SQLite\n// reports `no such column: to`, which is a true statement about the parse and a false\n// one about the input. Both field reports on 0.6.0 misdiagnosed that message.\nconst FTS5_OPERATORS = /[-'\"/.:^*()]/;\n\nfunction searchError(err: Error, terms: string, scope?: string): Error {\n const message = err.message;\n if (!/no such column|fts5: syntax error|malformed MATCH/.test(message)) return err;\n const suspects = (terms.match(/\\S+/g) ?? []).filter((t) => !t.startsWith('\"') && FTS5_OPERATORS.test(t));\n // Blame the terms only when the failing token actually came from one -- a typo'd column\n // in --where (or the tree's default scope) raises \"no such column\" through this same\n // statement, and naming a term for it would state a false fact about the input.\n const col = /no such column: (\\S+)/.exec(message)?.[1];\n const fromTerms = col === undefined ? suspects.length > 0 : suspects.some((t) => t.split(/[^\\p{L}\\p{N}]+/u).includes(col));\n if (fromTerms && suspects.length > 0) {\n return new SenseError('SEARCH_SYNTAX', `${message} -- the punctuation in ${suspects.map((t) => `\\`${t}\\``).join(', ')} is FTS5 syntax, not literal text; search for it literally by double-quoting: '\"${suspects[0]}\"'. Searchable columns are title, summary, text.`);\n }\n if (col !== undefined && scope !== undefined) {\n return new SenseError('SEARCH_SYNTAX', `${message} -- the where condition (${scope}) references it; frontmatter columns are listed by sense query \"SELECT name FROM pragma_table_info('frontmatter')\".`);\n }\n return new SenseError('SEARCH_SYNTAX', `${message} -- searchable columns are title, summary, text; frontmatter fields are queried with --where or sense query (list them with pragma_table_info('frontmatter')).`);\n}\n\nexport interface FindOptions {\n k?: number;\n where?: string; // SQL fragment against frontmatter alias `f`, e.g. \"f.status = 'active'\"\n semantic?: boolean; // invoke vector expansion (requires features.embed); rows gain via 'vector' and a lines column\n}\n\n// Layer 1: BM25 + link-graph expansion, fused by reciprocal rank. `via` says which\n// signal produced each row so the agent knows what evidence it is trusting.\n// Semantic expansion is per-query opt-in: without opts.semantic the result is\n// byte-for-byte independent of the embed feature.\nexport async function find(db: DatabaseSync, cfg: Config, terms: string, opts: FindOptions = {}): Promise<Row[]> {\n const k = opts.k ?? 10;\n const fetch = Math.max(k * 3, 30);\n\n // Terms pass verbatim to FTS5 MATCH: bare words AND-join, operators are the caller's.\n // Invalid syntax propagates as an error, zero matches return zero -- no silent rewrites.\n // --where applies inside the candidate query (a post-filter over the top-N would drop\n // matches ranked past the pool) and again on the final select for link-derived rows.\n // An explicit --where replaces the tree's declared default rather than ANDing with it,\n // so a caller can always widen back to the whole tree.\n const scope = opts.where ?? cfg.defaults?.find?.where;\n const whereJoin = scope ? `JOIN frontmatter f ON f.\"path\" = content.path` : '';\n const whereCond = scope ? `AND (${scope})` : '';\n const matchSql = `SELECT content.path AS path, snippet(content, -1, '«', '»', '…', 10) AS hit FROM content ${whereJoin} WHERE content MATCH ? ${whereCond} ORDER BY ${WEIGHTED_BM25} LIMIT ${fetch}`;\n let matchRows: Array<{ path: string; hit: string }>;\n try {\n matchRows = db.prepare(matchSql).all(terms) as Array<{ path: string; hit: string }>;\n } catch (err) {\n throw searchError(err as Error, terms, scope);\n }\n\n const hits = new Map(matchRows.map((r) => [r.path, r.hit]));\n const candidates = new Map<string, { score: number; via: string }>();\n matchRows.forEach((r, i) => {\n candidates.set(r.path, { score: 1 / (RRF_K + i), via: 'match' });\n });\n\n const edges = featureEnabled(cfg, 'links') && matchRows.length > 0 ? linkEdges(db) : [];\n if (edges.length > 0) {\n // `linked` gates the label only, not the score: PPR restart mass gives every seed a\n // nonzero rank even without an incident edge, which is not link evidence — but dropping\n // that mass from the score list reweights fusion toward connectivity and measurably\n // wrecks ranking on link-dense corpora (FEVER hit@10 0.997 -> 0.907; fusion-tuning.md).\n const linked = new Set(edges.flat());\n const nodes = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n const seeds = new Map(matchRows.map((r, i) => [r.path, 1 / (i + 1)]));\n const ranked = [...personalizedRank(nodes, edges, seeds)]\n .filter(([, score]) => score > 1e-9)\n .sort((a, b) => b[1] - a[1])\n .slice(0, fetch);\n ranked.forEach(([path], i) => {\n const existing = candidates.get(path);\n if (existing) {\n existing.score += 1 / (RRF_K + i);\n if (linked.has(path)) existing.via = 'match+link';\n } else {\n candidates.set(path, { score: 1 / (RRF_K + i), via: 'link' });\n }\n });\n }\n\n // Vector expansion, invoked only: a third RRF list at the swept flat-region constants\n // (weight 1, pool = fetch). Each row carries its best chunk's line range.\n const chunkLines = new Map<string, string>();\n const chunkSimilarity = new Map<string, number>();\n if (opts.semantic) {\n const vec = await semanticCandidates(db, cfg, terms, fetch);\n vec.forEach(({ path, lines, similarity }, i) => {\n chunkLines.set(path, lines);\n chunkSimilarity.set(path, similarity);\n const existing = candidates.get(path);\n if (existing) {\n existing.score += 1 / (RRF_K + i);\n existing.via = `${existing.via}+vector`;\n } else {\n candidates.set(path, { score: 1 / (RRF_K + i), via: 'vector' });\n }\n });\n }\n\n db.exec('DROP TABLE IF EXISTS _find');\n db.exec('CREATE TEMP TABLE _find (\"path\" TEXT PRIMARY KEY, score REAL, via TEXT, hit TEXT, lines TEXT, similarity REAL)');\n const insert = db.prepare('INSERT INTO _find (\"path\", score, via, hit, lines, similarity) VALUES (?, ?, ?, ?, ?, ?)');\n for (const [path, c] of candidates) insert.run(path, c.score, c.via, hits.get(path) ?? null, chunkLines.get(path) ?? null, chunkSimilarity.get(path) ?? null);\n\n const where = scope ? `WHERE ${scope}` : '';\n const linesCol = opts.semantic ? ', _find.lines, _find.similarity' : '';\n return db\n .prepare(\n `SELECT f.\"path\" AS path, content.title, content.summary, _find.hit, _find.via, round(_find.score, 4) AS score${linesCol}\n FROM _find JOIN frontmatter f ON f.\"path\" = _find.\"path\" JOIN content ON content.path = _find.\"path\"\n ${where} ORDER BY _find.score DESC LIMIT ?`\n )\n .all(k) as Row[];\n}\n\nexport interface TreeMap {\n docs: { count: number; bytes: number };\n fields: Row[]; // top 20 by coverage; fieldsTotal carries the real count\n fieldsTotal: number;\n features: { on: FeatureName[]; off: FeatureName[] };\n hubs: Row[];\n recent: Row[];\n}\n\nconst INTERNAL_COLUMNS = new Set(['path', '_mtime', '_size', '_rank']);\n\n// Layer 0: what is this tree. Fixed-size output regardless of tree size.\nexport function mapTree(db: DatabaseSync, cfg: Config): TreeMap {\n const docs = db.prepare('SELECT COUNT(*) AS count, COALESCE(SUM(\"_size\"), 0) AS bytes FROM frontmatter').get() as { count: number; bytes: number };\n\n const columns = (db.prepare('PRAGMA table_info(frontmatter)').all() as Array<{ name: string }>).map((r) => r.name).filter((name) => !INTERNAL_COLUMNS.has(name));\n const allFields = columns\n .map((name) => {\n const quoted = `\"${name.split('\"').join('\"\"')}\"`;\n // Observed storage class, not a declared one: these columns are added dynamically and\n // SQLite types per value, so a field can be text in most notes and numeric in a few.\n // Listing every distinct type makes both the type and any drift visible.\n const { n, types } = db.prepare(`SELECT COUNT(${quoted}) AS n, GROUP_CONCAT(DISTINCT typeof(${quoted})) AS types FROM frontmatter WHERE ${quoted} IS NOT NULL`).get() as { n: number; types: string | null };\n return { field: name, coverage: n, type: types ?? '' };\n })\n .sort((a, b) => (b.coverage as number) - (a.coverage as number)) as Row[];\n const fields = allFields.slice(0, 20);\n\n const hubs = featureEnabled(cfg, 'rank') ? (db.prepare(`SELECT f.\"path\" AS path, round(f.\"_rank\" * 100, 2) AS rank, content.title FROM frontmatter f JOIN content ON content.path = f.\"path\" WHERE f.\"_rank\" IS NOT NULL ORDER BY f.\"_rank\" DESC LIMIT 8`).all() as Row[]) : [];\n\n const recent = db.prepare(`SELECT \"path\", datetime(\"_mtime\" / 1000, 'unixepoch') AS modified FROM frontmatter ORDER BY \"_mtime\" DESC LIMIT 5`).all() as Row[];\n\n return { docs, fields, fieldsTotal: allFields.length, features: featureStates(cfg), hubs, recent };\n}\n\nexport interface Peek {\n path: string;\n tokens: number;\n frontmatter: Row;\n sections: Row[];\n outbound: string[];\n backlinks: string[];\n unresolved: string[];\n // Totals before truncation: a hub can have thousands of backlinks, and peek's whole\n // point is bounded output. Query the links table directly for the full list.\n outboundTotal: number;\n backlinksTotal: number;\n unresolvedTotal: number;\n off: FeatureName[]; // disabled features whose blocks are omitted (not empty)\n}\n\nconst PEEK_LINK_LIMIT = 20;\n\n// Layer 2: everything about one note except its prose -- frontmatter, outline with line\n// ranges + token estimates (so the follow-up Read is a range, not the file), links both ways.\nexport function peek(db: DatabaseSync, cfg: Config, pathArg: string): Peek {\n const paths = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n let path = paths.find((p) => p === pathArg);\n if (!path) {\n const base = posix.basename(pathArg).replace(/\\.md$/i, '').toLowerCase();\n const matches = paths.filter((p) => posix.basename(p).replace(/\\.md$/i, '').toLowerCase() === base);\n if (matches.length === 1) path = matches[0];\n else if (matches.length > 1) throw new SenseError('NOTE_AMBIGUOUS', `\"${pathArg}\" is ambiguous: ${matches.join(', ')}`);\n else throw new SenseError('NOTE_NOT_FOUND', `no note matches \"${pathArg}\"`);\n }\n\n const row = db.prepare('SELECT * FROM frontmatter WHERE \"path\" = ?').get(path) as Row;\n const frontmatter: Row = {};\n for (const [key, value] of Object.entries(row)) {\n if (!INTERNAL_COLUMNS.has(key) && value !== null) frontmatter[key] = value;\n }\n\n const sections = featureEnabled(cfg, 'sections') ? (db.prepare('SELECT level, heading, start_line, end_line, tokens FROM sections WHERE \"path\" = ? ORDER BY idx').all(path) as Row[]) : [];\n\n let outbound: string[] = [];\n let backlinks: string[] = [];\n let unresolved: string[] = [];\n let backlinksTotal = 0;\n if (featureEnabled(cfg, 'links')) {\n const out = db.prepare('SELECT target, dst FROM links WHERE src = ? ORDER BY target').all(path) as Array<{ target: string; dst: string | null }>;\n outbound = [...new Set(out.filter((l) => l.dst !== null).map((l) => l.dst as string))];\n unresolved = out.filter((l) => l.dst === null).map((l) => l.target);\n backlinksTotal = (db.prepare('SELECT COUNT(DISTINCT src) AS n FROM links WHERE dst = ?').get(path) as { n: number }).n;\n backlinks = (db.prepare('SELECT DISTINCT src FROM links WHERE dst = ? ORDER BY src LIMIT ?').all(path, PEEK_LINK_LIMIT) as Array<{ src: string }>).map((r) => r.src);\n }\n\n return {\n path,\n tokens: Math.ceil(((row._size as number) ?? 0) / 4),\n frontmatter,\n sections,\n outbound: outbound.slice(0, PEEK_LINK_LIMIT),\n backlinks,\n unresolved: unresolved.slice(0, PEEK_LINK_LIMIT),\n outboundTotal: outbound.length,\n backlinksTotal,\n unresolvedTotal: unresolved.length,\n off: (['sections', 'links'] as FeatureName[]).filter((name) => !featureEnabled(cfg, name)),\n };\n}\n"],"names":["posix","featureEnabled","featureStates","SenseError","semanticCandidates","linkEdges","personalizedRank","WEIGHTED_BM25","RRF_K","FTS5_OPERATORS","searchError","err","terms","scope","message","test","suspects","match","filter","t","startsWith","col","exec","fromTerms","undefined","length","some","split","includes","map","join","find","db","cfg","opts","hits","chunkLines","chunkSimilarity","k","fetch","Math","max","where","defaults","whereJoin","whereCond","matchSql","matchRows","prepare","all","Map","r","path","hit","candidates","forEach","i","set","score","via","edges","linked","Set","flat","nodes","seeds","ranked","sort","a","b","slice","existing","get","has","semantic","vec","lines","similarity","insert","c","run","linesCol","INTERNAL_COLUMNS","mapTree","docs","columns","name","allFields","quoted","n","types","field","coverage","type","fields","hubs","recent","fieldsTotal","features","PEEK_LINK_LIMIT","peek","pathArg","row","paths","p","base","basename","replace","toLowerCase","matches","frontmatter","key","value","Object","entries","sections","outbound","backlinks","unresolved","backlinksTotal","out","l","dst","target","src","tokens","ceil","_size","outboundTotal","unresolvedTotal","off"],"mappings":"AAAA,OAAOA,WAAW,kBAAkB;AAGpC,SAASC,cAAc,EAAEC,aAAa,QAAQ,cAAc;AAC5D,SAASC,UAAU,QAAQ,cAAc;AACzC,SAASC,kBAAkB,QAAQ,sBAAsB;AACzD,SAASC,SAAS,QAAQ,sBAAsB;AAChD,SAASC,gBAAgB,QAAQ,aAAa;AAG9C,4EAA4E;AAC5E,gFAAgF;AAEhF,MAAMC,gBAAgB;AACtB,MAAMC,QAAQ;AAEd,uFAAuF;AACvF,uFAAuF;AACvF,sFAAsF;AACtF,8EAA8E;AAC9E,MAAMC,iBAAiB;AAEvB,SAASC,YAAYC,GAAU,EAAEC,KAAa,EAAEC,KAAc;QAG1CD;QAIN;IANZ,MAAME,UAAUH,IAAIG,OAAO;IAC3B,IAAI,CAAC,oDAAoDC,IAAI,CAACD,UAAU,OAAOH;IAC/E,MAAMK,WAAW,EAACJ,eAAAA,MAAMK,KAAK,CAAC,qBAAZL,0BAAAA,eAAuB,EAAE,EAAEM,MAA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CAAC,4DAA4DwB,GAAG,CAACpB,MAAwBqC,CAAC;QACtH4B,YAAY,AAACrF,GAAGgB,OAAO,CAAC,qEAAqEC,GAAG,CAACG,MAAM+C,iBAA4CtE,GAAG,CAAC,CAACsB,IAAMA,EAAEyE,GAAG;IACrK;IAEA,OAAO;QACLxE;QACAyE,QAAQrF,KAAKsF,IAAI,CAAC,EAAExB,aAAAA,IAAIyB,KAAK,cAATzB,wBAAAA,aAAwB,KAAK;QACjDQ;QACAK;QACAC,UAAUA,SAAS9C,KAAK,CAAC,GAAG6B;QAC5BkB;QACAC,YAAYA,WAAWhD,KAAK,CAAC,GAAG6B;QAChC6B,eAAeZ,SAAS3F,MAAM;QAC9B8F;QACAU,iBAAiBX,WAAW7F,MAAM;QAClCyG,KAAK,AAAC;YAAC;YAAY;SAAQ,CAAmBhH,MAAM,CAAC,CAACoE,OAAS,CAACrF,eAAegC,KAAKqD;IACtF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sensemaking",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "Query a knowledge base you build with an agent: filter notes by frontmatter, then search inside them",
5
5
  "keywords": [
6
6
  "markdown",
@@ -47,6 +47,7 @@
47
47
  "version": "tsds version"
48
48
  },
49
49
  "dependencies": {
50
+ "@huggingface/tokenizers": "^0.1.3",
50
51
  "fast-glob": "^3.3.3",
51
52
  "remove-markdown": "^0.6.4",
52
53
  "yaml": "^2.9.0"
package/schema.json CHANGED
@@ -45,12 +45,46 @@
45
45
  "rank": {
46
46
  "type": "boolean",
47
47
  "description": "PageRank over resolved links into `frontmatter._rank` at reconcile -- a static importance prior. Powers `map`'s hub list; usable in any ORDER BY. Requires `links`."
48
+ },
49
+ "embed": {
50
+ "description": "Semantic vectors, opt-in (absent = off; most trees don't need them). When on, vectors are computed and kept fresh at reconcile; expansion runs only on `find --semantic` invocations -- default `find` results are unchanged. `true` = defaults (static type, minishlab/potion-retrieval-32M, downloaded to ~/.cache/sensemaking on first use). Object form: `model` (Hugging Face id or local path), `type` (`static` = built-in pure-JS Model2Vec loader; `api` = OpenAI-compatible POST /embeddings), `url` (api base, e.g. http://localhost:11434/v1), `key` (name of the env var holding the bearer token). Changing model or type rebuilds the cache like a feature toggle.",
51
+ "oneOf": [
52
+ { "type": "boolean" },
53
+ {
54
+ "type": "object",
55
+ "additionalProperties": false,
56
+ "properties": {
57
+ "model": { "type": "string" },
58
+ "type": { "type": "string", "enum": ["static", "api"] },
59
+ "url": { "type": "string" },
60
+ "key": { "type": "string" }
61
+ }
62
+ }
63
+ ]
64
+ }
65
+ }
66
+ },
67
+ "defaults": {
68
+ "type": "object",
69
+ "additionalProperties": false,
70
+ "description": "Tree-declared defaults for the verbs.",
71
+ "properties": {
72
+ "find": {
73
+ "type": "object",
74
+ "additionalProperties": false,
75
+ "description": "Default scope for `find`. Use when a tree holds a layer that should stay queryable but out of ordinary search -- generated output, or unverified source extractions that must not be cited as conclusions.",
76
+ "properties": {
77
+ "where": {
78
+ "type": "string",
79
+ "description": "SQL condition against frontmatter alias `f`, e.g. \"f.type != 'raw'\". Applied when `find` runs without --where; an explicit --where replaces it (so `--where \"1=1\"` searches the whole tree). Reported by `sense status`."
80
+ }
81
+ }
48
82
  }
49
83
  }
50
84
  },
51
85
  "queries": {
52
86
  "type": "object",
53
- "description": "Named SQL queries runnable as `sense <name> [params...]`. Tables: `frontmatter` (one row per file, one column per discovered frontmatter key, plus `path`/`_mtime`/`_size`/`_rank`), `content` (FTS5: `title`, `summary`, `text`, `path`), `links` (`src`, `target`, `dst`), and `sections` (`path`, `idx`, `level`, `heading`, `start_line`, `end_line`, `tokens`). `?` placeholders bind to CLI positional args in order. `has(field, value)`: array membership on a JSON-array field, substring match on a string (so has(f.status, 'active') also matches 'inactive'), false on NULL. Exact matches: `=` for scalars, `EXISTS (SELECT 1 FROM json_each(f.tags) WHERE value = ?)` for array members. Canonical query: `SELECT f.path, content.title, content.summary, snippet(content, -1, '«', '»', '…', 10) AS hit FROM frontmatter f JOIN content ON content.path = f.path WHERE content MATCH ? ORDER BY bm25(content, 10.0, 5.0, 1.0) LIMIT 10`. Reserved frontmatter keys: `path`, `_mtime`, `_size`, `_rank`, `content`, `links`, `sections`. Reserved query names (unreachable as subcommands): `init`, `query`, `find`, `map`, `peek`, `watch`, `status`, `rebuild`.",
87
+ "description": "Named SQL queries runnable as `sense <name> [params...]`. Tables: `frontmatter` (one row per file, one column per discovered frontmatter key, plus `path`/`_mtime`/`_size`/`_rank`), `content` (FTS5: `title`, `summary`, `text`, `path`), `links` (`src`, `target`, `dst`), and `sections` (`path`, `idx`, `level`, `heading`, `start_line`, `end_line`, `tokens`). `?` placeholders bind to CLI positional args in order. `has(field, value)`: array membership on a JSON-array field, substring match on a string (so has(f.status, 'active') also matches 'inactive'), false on NULL. Exact matches: `=` for scalars, `EXISTS (SELECT 1 FROM json_each(f.tags) WHERE value = ?)` for array members. Canonical query: `SELECT f.path, content.title, content.summary, snippet(content, -1, '«', '»', '…', 10) AS hit FROM frontmatter f JOIN content ON content.path = f.path WHERE content MATCH ? ORDER BY bm25(content, 10.0, 5.0, 1.0) LIMIT 10`. Reserved frontmatter keys: `path`, `_mtime`, `_size`, `_rank`, `content`, `links`, `sections`. Reserved query names (unreachable as subcommands): `init`, `query`, `find`, `map`, `peek`, `watch`, `status`, `rebuild`, `check`.",
54
88
  "additionalProperties": { "type": "string" }
55
89
  }
56
90
  }
@@ -75,6 +75,22 @@ sense --list # named queries someone already saved
75
75
  sense query "SELECT DISTINCT type FROM frontmatter" # what a field's values are
76
76
  ```
77
77
 
78
+ ## F. "The notes say it in different words"
79
+
80
+ ```
81
+ sense find "children dying from poor nutrition" --semantic --k 3 --format json
82
+ ```
83
+
84
+ ```json
85
+ [
86
+ { "path": "notes/malnutrition-outcomes.md", "title": "Malnutrition outcomes",
87
+ "summary": "Stunting and mortality by region", "hit": null, "via": "vector", "score": 0.0167, "lines": "L14-52" }
88
+ ]
89
+ ```
90
+
91
+ A `via: "vector"` row never contained the terms — it is semantically near them; `lines` is the
92
+ best-matching section, a direct `Read` range. Only on trees whose config enables `features.embed`.
93
+
78
94
  ## Consequences
79
95
 
80
96
  | query | what happens | bounded alternative |
@@ -10,22 +10,32 @@ SQL over a markdown tree, kept fresh by a filesystem check on every query. Four
10
10
  `title`, `summary`, `text`), `links` (`src`, `target`, `dst` — `NULL` dst = dead link),
11
11
  `sections` (heading outline with line ranges and token estimates).
12
12
 
13
- ## The descent
13
+ ## What each tool is for
14
14
 
15
- Spend tokens in this order (progressive disclosure: metadata first, payloads just in time); go
16
- only as deep as the question needs.
15
+ Every result is a reference (path, metadata, excerpt), never file contents; prose enters
16
+ context only when you Read it. Costs: `map` is fixed-size, a `find` row ~30 tokens, `peek`
17
+ ~17% of reading the file. Which tool fits is a property of the question:
17
18
 
18
- 1. `sense map` — orient once: fields, hub notes, recent changes. Fixed-size output.
19
- 2. `sense find "<terms>"` — locate: ranked references with excerpts, ~30 tokens/row.
20
- FTS5 standard: bare words AND-join (one absent word = zero rows) — write
21
- `a OR b OR c` for any-word matching.
22
- 3. `sense peek <path>` — structure before reading: outline with `[L143-162, ~380t]` ranges,
23
- links both ways. ~17% the cost of reading the file.
24
- 4. `Read` — the payload. On large files, peek's line ranges let you read just the section
25
- you need; small files are often cheaper to read whole.
19
+ - A deterministic, factual answer over known fields — counts, filters, "which notes have
20
+ X" — is SQL: `sense query`, a named query, or `find --where`. Enumerates every match;
21
+ same result regardless of phrasing.
22
+ - Locating notes by words in their prose is `find` — ranked lexical match. Results shift as
23
+ phrasing shifts, and bare words AND-join (one absent word = zero rows): write
24
+ `a OR b OR c` for any-word matching.
25
+ - A conceptual question the notes phrase in different words is `find --semantic` (exists only
26
+ on trees whose config enables `embed`): adds meaning-based candidates labeled `via: vector`.
27
+ Conceptual similarity, not typo-tolerance; false positives are expected, labeled, and
28
+ bounded by `--k`.
29
+ - `map` answers "what is this tree" — fields, hub notes, recent changes — when the tree is
30
+ unfamiliar.
31
+ - `peek <path>` prices a file before you pay for it: outline with `[L143-162, ~380t]`
32
+ ranges, links both ways.
33
+ - When you know the file and need its contents, `Read` it — sense adds nothing there. On
34
+ large files peek's ranges let you read just one section; small files are often cheaper
35
+ whole.
26
36
 
27
- Every result is a reference, never file contents. Output defaults to a table, built for
28
- humans; `--format json` returns the same rows machine-parseable.
37
+ Output defaults to a table, built for humans; `--format json` returns the same rows
38
+ machine-parseable.
29
39
 
30
40
  ## Verbs
31
41
 
@@ -35,7 +45,7 @@ sense peek notes/pricing-model.md # a unique basename also works
35
45
  sense map
36
46
  sense query "<sql>" [params...] # ad-hoc SQL; ? binds positional args, count-checked
37
47
  sense <name> [params...] # named query from sense.config.json
38
- sense --list | status | rebuild
48
+ sense --list | status | rebuild | check
39
49
  ```
40
50
 
41
51
  - Terms pass verbatim to FTS5 MATCH. Bare words AND-join — one absent word means zero rows —
@@ -44,15 +54,37 @@ sense --list | status | rebuild
44
54
  rules apply to search commands you write into subagent briefs.
45
55
  - When a search misses, the recall levers are: OR-in synonyms and concrete instances (the
46
56
  index only knows the words in the files — a note about a specific tool rarely names its
47
- category), and raise `--k` (a row costs ~30 tokens). Each widening adds candidates and
48
- dilutes ranking, so the noise trade-off runs both ways.
57
+ category), raise `--k` (a row costs ~30 tokens), and on embed-enabled trees `--semantic`
58
+ (matches meaning where term overlap fails). Each widening adds candidates and dilutes
59
+ ranking, so the noise trade-off runs both ways.
49
60
  - A frontmatter query enumerates its matches deterministically; search ranks by term overlap,
50
61
  so results shift as phrasing shifts. Trade-off: a query needs a known field, search doesn't.
51
62
  - `find` fuses BM25 with link-graph expansion; the `via` column says what produced each row —
52
- `match` (terms hit), `link` (connected to notes that hit), `match+link` (both).
53
- - `--where` takes a frontmatter condition against alias `f`, e.g. `"f.status = 'active' AND has(f.tags, 'x')"`.
63
+ `match` (terms hit), `link` (connected to notes that hit), `match+link` (both). With
64
+ `--semantic`, `vector` joins the composition and rows gain a `lines` column pointing at the
65
+ best-matching section, a direct `Read` range.
66
+ - `--where` takes any SQL condition against frontmatter alias `f` — not only field equality:
67
+ `"f.status = 'active' AND has(f.tags, 'x')"`, `"f.path NOT LIKE 'generated/%'"`,
68
+ `"f.created >= datetime(?)"`. A tree can declare a default scope in `sense.config.json`
69
+ (`defaults.find.where`); an explicit `--where` replaces it, so `--where "1=1"` searches
70
+ everything. `sense status` prints the active default.
71
+ - `score` is a rank-fusion value: it ranks rows within one result set and is not comparable
72
+ across queries, not a relevance magnitude — a perfect lexical hit and a weak vector-only
73
+ hit can both read ~0.017, because the number encodes how many signals fired and at what
74
+ rank. With `--semantic`, rows carry `similarity` (cosine, -1 to 1) which does measure
75
+ match quality: on a query whose words are absent from the tree, similarities sit near zero
76
+ (and can be negative), while a genuine paraphrase match runs high.
77
+ - Lexical `find` returns 0 rows when nothing matches, so it answers "is this in the tree at
78
+ all". `--semantic` always returns up to `k` rows — nearest-neighbour search has a nearest
79
+ neighbour for any input — so absence is a lexical question; with `--semantic` the
80
+ `similarity` column is what separates a real hit from the best of a bad lot.
81
+ - `sense check` prepares every saved query (catching syntax and unknown-column errors), runs
82
+ the ones taking no parameters, and prints row counts: a saved query returning 0 rows looks
83
+ the same as a true empty result until something distinguishes them.
54
84
 
55
- ## SQL, when the verbs aren't enough
85
+ ## SQL
86
+
87
+ The verbs are shorthands over the same four tables; anything they don't express, SQL does.
56
88
 
57
89
  ```
58
90
  sense query "SELECT name FROM pragma_table_info('frontmatter')" # what fields exist
@@ -72,6 +104,10 @@ sense query "SELECT j.value, COUNT(*) n FROM frontmatter, json_each(frontmatter.
72
104
  `snippet(content, -1, '«', '»', '…', 10)`.
73
105
  - Select `content.title`/`content.summary` (always exist, empty when absent) rather than
74
106
  `f.title`/`f.summary` (discovered columns — error on trees that never declare them).
107
+ - Frontmatter values keep their YAML type: strings are TEXT, whole numbers and booleans are
108
+ INTEGER (`true` stores as 1, so `WHERE flag = 1` matches and `WHERE flag = 'true'` matches
109
+ nothing), fractions are REAL, lists and maps are JSON text. `map` prints the observed type
110
+ per field, and a field showing two types (`integer,text`) has drifted across notes.
75
111
  - `has(field, value)`: array membership on JSON-array fields, substring on strings, false on NULL
76
112
  — the `includes()` convention. Substring means `has(f.status, 'active')` also matches
77
113
  `inactive`; exact scalar match is `f.status = ?`, deliberate substring is `LIKE`, exact array
@@ -92,7 +128,11 @@ Worked traces: [EXAMPLES.md](EXAMPLES.md).
92
128
  ## Setup and upkeep
93
129
 
94
130
  - Missing CLI: `npm install -g sensemaking`. Missing config: `sense init` at the tree root.
95
- Discovery walks up from cwd; `--config <path>` overrides.
131
+ Discovery walks up from cwd; `--config <path>` overrides. Setting up or restructuring a
132
+ tree (features, frontmatter conventions, note design) is the `sense-setup` skill.
133
+ - `map` and `status` report feature state (`features: links, sections, rank · off: embed
134
+ (features.embed)`). Invoking a capability whose feature is off is an error naming the
135
+ config key to enable — nothing silently falls back.
96
136
  - Save a query into `sense.config.json` only when it will be reused; run ad-hoc otherwise.
97
137
  - A one-line `summary:` per note is optional and pays twice: it appears in result rows and is a
98
138
  weighted search field. Date comparisons work for dates written as ISO 8601 (`2026-08-12`, or
@@ -0,0 +1,91 @@
1
+ ---
2
+ name: sense-setup
3
+ description: Set up the sense CLI on a markdown tree and make the tree-design decisions that shape it — sense init, enabling features (links, sections, rank, embed), and the trade-offs of frontmatter conventions, summaries, folder layout, and note size. Use when creating or restructuring a markdown knowledge base, running sense init, editing sense.config.json, enabling semantic search, or deciding how notes should be written for an agent to query later.
4
+ ---
5
+
6
+ # sense: setup and tree design
7
+
8
+ Querying an existing tree is the `sense` skill. This one covers making a tree:
9
+ installing, configuring features, and the design decisions a tree owner faces.
10
+
11
+ ## Setup
12
+
13
+ - `npm install -g sensemaking`, then `sense init` at the tree root writes
14
+ `sense.config.json` (all opt-out features on, `embed` off). Config discovery
15
+ walks up from cwd; `--config <path>` overrides.
16
+ - `scan.include` globs resolve relative to the config file, never the cwd.
17
+ - `sense map` and `sense status` report feature state
18
+ (`features: links, sections, rank · off: embed (features.embed)`), so the
19
+ current config is always discoverable from output.
20
+
21
+ ## Features
22
+
23
+ | feature | powers | cost when on | config key |
24
+ |---|---|---|---|
25
+ | `links` | backlinks, dead-link queries, `find`'s link expansion, `peek`'s link lists | link re-resolution at reconcile | `features.links` (default on) |
26
+ | `sections` | `peek`'s outline, line-range reads, per-section token estimates | heading extraction at parse | `features.sections` (default on) |
27
+ | `rank` | `map`'s hubs, `_rank` in any ORDER BY | PageRank pass at reconcile; requires `links` | `features.rank` (default on) |
28
+ | `embed` | `find --semantic` (meaning-based expansion) | vectors computed at reconcile; model download to `~/.cache/sensemaking` on first use; ~40 ms model load per semantic invocation | `features.embed` (default off) |
29
+
30
+ - `embed` accepts `true` (built-in static model) or an object: `model` (Hugging
31
+ Face id or local path), `type` (`static` pure-JS built-in, or `api` for any
32
+ OpenAI-compatible `/v1/embeddings` endpoint — Ollama, LM Studio, llama.cpp,
33
+ hosted), `url`, `key` (env var name). A local `model` path is fully offline.
34
+ - The two types differ in what they match, not only in cost: `static` is a
35
+ context-free distilled model that handles paraphrase and reworded concepts
36
+ (a query like "delegating without micromanaging" can reach a note that uses
37
+ neither word); tight near-synonyms and domain jargon ("heart attack" for
38
+ "myocardial infarction") are where it misses and an `api` transformer model
39
+ tends to succeed. The gain concentrates where the searcher's vocabulary
40
+ differs from the notes' — measured in the retrieval eval (BENCHMARKING.md,
41
+ "Retrieval quality"): on a vocabulary-gap corpus semantic expansion adds
42
+ recall; where vocabulary overlaps, BM25 plus link expansion already answers
43
+ most queries and vectors mostly reorder.
44
+ - Enabling `embed` changes no default `find` result — expansion runs only when
45
+ a query passes `--semantic`. Invoking `--semantic` on a tree without `embed`
46
+ is an error naming the config key.
47
+ - Toggling any feature rebuilds the cache on the next query (safe, automatic).
48
+ - Disabled features degrade output, visibly: `peek` prints
49
+ `sections: off (features.sections)` rather than an empty outline.
50
+
51
+ ## Tree design decisions
52
+
53
+ These belong to the tree's owner. sense works with any of them and reads no
54
+ instruction files of its own; each choice below only changes what queries can
55
+ do, and every consequence is listed so the choice can be made deliberately.
56
+
57
+ - **Frontmatter fields.** Columns are discovered per tree — whatever keys notes
58
+ declare become queryable. Consistent fields across notes make SQL filters
59
+ and named queries possible (`WHERE status = 'active'`). Reserved keys
60
+ (dropped with a warning): `path`, `_mtime`, `_size`, `_rank`, `content`,
61
+ `links`, `sections`. Values keep their YAML type: strings TEXT, whole numbers
62
+ and booleans INTEGER (`true` is 1), fractions REAL, lists and maps JSON text;
63
+ `map` prints the observed type per field.
64
+ - **What a note omits is also a filter.** A layer that deliberately carries none
65
+ of the fields the saved views filter on is excluded from all of them without
66
+ any view naming the layer; only a view filtering solely on a field the layer
67
+ does share needs an explicit condition (`AND type != 'raw'`). Sparse fields cut
68
+ both ways: less of the tree filters when you want breadth, and exactly this
69
+ separation when layers differ in authority — source extractions vs.
70
+ conclusions, generated output vs. notes.
71
+ - **Dates.** `datetime()` comparisons work for dates written as ISO 8601 —
72
+ the only format it parses. A tree that mixes date formats can store them,
73
+ but can't compare them in SQL.
74
+ - **Summaries.** A one-line `summary:` is optional and pays twice: it shows in
75
+ every result row (often answering a question with no file read) and is a
76
+ weighted search field ranked above body text. The cost is writing and
77
+ maintaining the line as notes change.
78
+ - **Folder shape.** sense is structure-indifferent: globs find the files,
79
+ paths are queryable text, links resolve by basename at any depth. Folders
80
+ are for the humans and agents navigating the tree, not for the index —
81
+ flat and nested trees query identically.
82
+ - **Note size.** Many small notes: precise `find` hits, whole-file reads stay
83
+ cheap, more links to maintain. Fewer large notes: `sections` and `peek`
84
+ carry the cost down to line-range reads. Both work; per-section token
85
+ estimates exist either way.
86
+ - **Where decisions live.** Choices that should outlive one conversation can
87
+ be recorded in the agent's own instruction or skill files, or in a note in
88
+ the tree itself; a one-off search over an existing corpus needs none of
89
+ that. Whether to settle a choice with the user or proceed on the corpus as
90
+ found depends on whether the agent is only querying or also authoring —
91
+ an authoring agent's choices compound; a querying agent's don't.