sensemaking 0.6.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 (64) hide show
  1. package/dist/cjs/cli.js +3 -0
  2. package/dist/cjs/cli.js.map +1 -1
  3. package/dist/cjs/commands/check.d.cts +3 -0
  4. package/dist/cjs/commands/check.d.ts +3 -0
  5. package/dist/cjs/commands/check.js +130 -0
  6. package/dist/cjs/commands/check.js.map +1 -0
  7. package/dist/cjs/commands/index.js +5 -0
  8. package/dist/cjs/commands/index.js.map +1 -1
  9. package/dist/cjs/commands/status.js +67 -9
  10. package/dist/cjs/commands/status.js.map +1 -1
  11. package/dist/cjs/config.d.cts +6 -0
  12. package/dist/cjs/config.d.ts +6 -0
  13. package/dist/cjs/config.js +61 -1
  14. package/dist/cjs/config.js.map +1 -1
  15. package/dist/cjs/db.d.cts +1 -1
  16. package/dist/cjs/db.d.ts +1 -1
  17. package/dist/cjs/db.js +1 -1
  18. package/dist/cjs/db.js.map +1 -1
  19. package/dist/cjs/errors.d.cts +1 -1
  20. package/dist/cjs/errors.d.ts +1 -1
  21. package/dist/cjs/errors.js.map +1 -1
  22. package/dist/cjs/features/embed.d.cts +1 -0
  23. package/dist/cjs/features/embed.d.ts +1 -0
  24. package/dist/cjs/features/embed.js +6 -2
  25. package/dist/cjs/features/embed.js.map +1 -1
  26. package/dist/cjs/output.js +34 -8
  27. package/dist/cjs/output.js.map +1 -1
  28. package/dist/cjs/scan.d.cts +1 -1
  29. package/dist/cjs/scan.d.ts +1 -1
  30. package/dist/cjs/scan.js +8 -2
  31. package/dist/cjs/scan.js.map +1 -1
  32. package/dist/cjs/verbs.js +56 -12
  33. package/dist/cjs/verbs.js.map +1 -1
  34. package/dist/esm/cli.js +3 -0
  35. package/dist/esm/cli.js.map +1 -1
  36. package/dist/esm/commands/check.d.ts +3 -0
  37. package/dist/esm/commands/check.js +56 -0
  38. package/dist/esm/commands/check.js.map +1 -0
  39. package/dist/esm/commands/index.js +1 -0
  40. package/dist/esm/commands/index.js.map +1 -1
  41. package/dist/esm/commands/status.js +38 -7
  42. package/dist/esm/commands/status.js.map +1 -1
  43. package/dist/esm/config.d.ts +6 -0
  44. package/dist/esm/config.js +35 -1
  45. package/dist/esm/config.js.map +1 -1
  46. package/dist/esm/db.d.ts +1 -1
  47. package/dist/esm/db.js +1 -1
  48. package/dist/esm/db.js.map +1 -1
  49. package/dist/esm/errors.d.ts +1 -1
  50. package/dist/esm/errors.js.map +1 -1
  51. package/dist/esm/features/embed.d.ts +1 -0
  52. package/dist/esm/features/embed.js +11 -2
  53. package/dist/esm/features/embed.js.map +1 -1
  54. package/dist/esm/output.js +29 -7
  55. package/dist/esm/output.js.map +1 -1
  56. package/dist/esm/scan.d.ts +1 -1
  57. package/dist/esm/scan.js +8 -2
  58. package/dist/esm/scan.js.map +1 -1
  59. package/dist/esm/verbs.js +52 -12
  60. package/dist/esm/verbs.js.map +1 -1
  61. package/package.json +1 -1
  62. package/schema.json +19 -1
  63. package/skills/sense/SKILL.md +23 -2
  64. package/skills/sense-setup/SKILL.md +22 -4
package/dist/esm/verbs.js CHANGED
@@ -8,22 +8,55 @@ import { personalizedRank } from './graph.js';
8
8
  // Each returns data; cli.ts renders. All of them degrade when a feature is off.
9
9
  const WEIGHTED_BM25 = 'bm25(content, 10.0, 5.0, 1.0)';
10
10
  const RRF_K = 60;
11
+ // FTS5 reads these as operators, so a bare term containing one is a syntax error or --
12
+ // worse -- a column filter: `end-to-end` parses as a filter on column `to`, and SQLite
13
+ // reports `no such column: to`, which is a true statement about the parse and a false
14
+ // one about the input. Both field reports on 0.6.0 misdiagnosed that message.
15
+ const FTS5_OPERATORS = /[-'"/.:^*()]/;
16
+ function searchError(err, terms, scope) {
17
+ var _terms_match;
18
+ var _exec;
19
+ const message = err.message;
20
+ if (!/no such column|fts5: syntax error|malformed MATCH/.test(message)) return err;
21
+ const suspects = ((_terms_match = terms.match(/\S+/g)) !== null && _terms_match !== void 0 ? _terms_match : []).filter((t)=>!t.startsWith('"') && FTS5_OPERATORS.test(t));
22
+ // Blame the terms only when the failing token actually came from one -- a typo'd column
23
+ // in --where (or the tree's default scope) raises "no such column" through this same
24
+ // statement, and naming a term for it would state a false fact about the input.
25
+ const col = (_exec = /no such column: (\S+)/.exec(message)) === null || _exec === void 0 ? void 0 : _exec[1];
26
+ const fromTerms = col === undefined ? suspects.length > 0 : suspects.some((t)=>t.split(/[^\p{L}\p{N}]+/u).includes(col));
27
+ if (fromTerms && suspects.length > 0) {
28
+ 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.`);
29
+ }
30
+ if (col !== undefined && scope !== undefined) {
31
+ 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')".`);
32
+ }
33
+ 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')).`);
34
+ }
11
35
  // Layer 1: BM25 + link-graph expansion, fused by reciprocal rank. `via` says which
12
36
  // signal produced each row so the agent knows what evidence it is trusting.
13
37
  // Semantic expansion is per-query opt-in: without opts.semantic the result is
14
38
  // byte-for-byte independent of the embed feature.
15
39
  export async function find(db, cfg, terms, opts = {}) {
16
- var _opts_k, _hits_get, _chunkLines_get;
40
+ var _opts_k, _opts_where, _hits_get, _chunkLines_get, _chunkSimilarity_get;
41
+ var _cfg_defaults_find, _cfg_defaults;
17
42
  const k = (_opts_k = opts.k) !== null && _opts_k !== void 0 ? _opts_k : 10;
18
43
  const fetch = Math.max(k * 3, 30);
19
44
  // Terms pass verbatim to FTS5 MATCH: bare words AND-join, operators are the caller's.
20
45
  // Invalid syntax propagates as an error, zero matches return zero -- no silent rewrites.
21
46
  // --where applies inside the candidate query (a post-filter over the top-N would drop
22
47
  // matches ranked past the pool) and again on the final select for link-derived rows.
23
- const whereJoin = opts.where ? `JOIN frontmatter f ON f."path" = content.path` : '';
24
- const whereCond = opts.where ? `AND (${opts.where})` : '';
48
+ // An explicit --where replaces the tree's declared default rather than ANDing with it,
49
+ // so a caller can always widen back to the whole tree.
50
+ const scope = (_opts_where = opts.where) !== null && _opts_where !== void 0 ? _opts_where : (_cfg_defaults = cfg.defaults) === null || _cfg_defaults === void 0 ? void 0 : (_cfg_defaults_find = _cfg_defaults.find) === null || _cfg_defaults_find === void 0 ? void 0 : _cfg_defaults_find.where;
51
+ const whereJoin = scope ? `JOIN frontmatter f ON f."path" = content.path` : '';
52
+ const whereCond = scope ? `AND (${scope})` : '';
25
53
  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}`;
26
- const matchRows = db.prepare(matchSql).all(terms);
54
+ let matchRows;
55
+ try {
56
+ matchRows = db.prepare(matchSql).all(terms);
57
+ } catch (err) {
58
+ throw searchError(err, terms, scope);
59
+ }
27
60
  const hits = new Map(matchRows.map((r)=>[
28
61
  r.path,
29
62
  r.hit
@@ -66,10 +99,12 @@ export async function find(db, cfg, terms, opts = {}) {
66
99
  // Vector expansion, invoked only: a third RRF list at the swept flat-region constants
67
100
  // (weight 1, pool = fetch). Each row carries its best chunk's line range.
68
101
  const chunkLines = new Map();
102
+ const chunkSimilarity = new Map();
69
103
  if (opts.semantic) {
70
104
  const vec = await semanticCandidates(db, cfg, terms, fetch);
71
- vec.forEach(({ path, lines }, i)=>{
105
+ vec.forEach(({ path, lines, similarity }, i)=>{
72
106
  chunkLines.set(path, lines);
107
+ chunkSimilarity.set(path, similarity);
73
108
  const existing = candidates.get(path);
74
109
  if (existing) {
75
110
  existing.score += 1 / (RRF_K + i);
@@ -83,11 +118,11 @@ export async function find(db, cfg, terms, opts = {}) {
83
118
  });
84
119
  }
85
120
  db.exec('DROP TABLE IF EXISTS _find');
86
- db.exec('CREATE TEMP TABLE _find ("path" TEXT PRIMARY KEY, score REAL, via TEXT, hit TEXT, lines TEXT)');
87
- const insert = db.prepare('INSERT INTO _find ("path", score, via, hit, lines) VALUES (?, ?, ?, ?, ?)');
88
- for (const [path, c] of candidates)insert.run(path, c.score, c.via, (_hits_get = hits.get(path)) !== null && _hits_get !== void 0 ? _hits_get : null, (_chunkLines_get = chunkLines.get(path)) !== null && _chunkLines_get !== void 0 ? _chunkLines_get : null);
89
- const where = opts.where ? `WHERE ${opts.where}` : '';
90
- const linesCol = opts.semantic ? ', _find.lines' : '';
121
+ db.exec('CREATE TEMP TABLE _find ("path" TEXT PRIMARY KEY, score REAL, via TEXT, hit TEXT, lines TEXT, similarity REAL)');
122
+ const insert = db.prepare('INSERT INTO _find ("path", score, via, hit, lines, similarity) VALUES (?, ?, ?, ?, ?, ?)');
123
+ for (const [path, c] of candidates)insert.run(path, c.score, c.via, (_hits_get = hits.get(path)) !== null && _hits_get !== void 0 ? _hits_get : null, (_chunkLines_get = chunkLines.get(path)) !== null && _chunkLines_get !== void 0 ? _chunkLines_get : null, (_chunkSimilarity_get = chunkSimilarity.get(path)) !== null && _chunkSimilarity_get !== void 0 ? _chunkSimilarity_get : null);
124
+ const where = scope ? `WHERE ${scope}` : '';
125
+ const linesCol = opts.semantic ? ', _find.lines, _find.similarity' : '';
91
126
  return db.prepare(`SELECT f."path" AS path, content.title, content.summary, _find.hit, _find.via, round(_find.score, 4) AS score${linesCol}
92
127
  FROM _find JOIN frontmatter f ON f."path" = _find."path" JOIN content ON content.path = _find."path"
93
128
  ${where} ORDER BY _find.score DESC LIMIT ?`).all(k);
@@ -103,10 +138,15 @@ export function mapTree(db, cfg) {
103
138
  const docs = db.prepare('SELECT COUNT(*) AS count, COALESCE(SUM("_size"), 0) AS bytes FROM frontmatter').get();
104
139
  const columns = db.prepare('PRAGMA table_info(frontmatter)').all().map((r)=>r.name).filter((name)=>!INTERNAL_COLUMNS.has(name));
105
140
  const allFields = columns.map((name)=>{
106
- const { n } = db.prepare(`SELECT COUNT("${name.split('"').join('""')}") AS n FROM frontmatter`).get();
141
+ const quoted = `"${name.split('"').join('""')}"`;
142
+ // Observed storage class, not a declared one: these columns are added dynamically and
143
+ // SQLite types per value, so a field can be text in most notes and numeric in a few.
144
+ // Listing every distinct type makes both the type and any drift visible.
145
+ 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();
107
146
  return {
108
147
  field: name,
109
- coverage: n
148
+ coverage: n,
149
+ type: types !== null && types !== void 0 ? types : ''
110
150
  };
111
151
  }).sort((a, b)=>b.coverage - a.coverage);
112
152
  const fields = allFields.slice(0, 20);
@@ -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, 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\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 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 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 if (opts.semantic) {\n const vec = await semanticCandidates(db, cfg, terms, fetch);\n vec.forEach(({ path, lines }, i) => {\n chunkLines.set(path, lines);\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)');\n const insert = db.prepare('INSERT INTO _find (\"path\", score, via, hit, lines) VALUES (?, ?, ?, ?, ?)');\n for (const [path, c] of candidates) insert.run(path, c.score, c.via, hits.get(path) ?? null, chunkLines.get(path) ?? null);\n\n const where = opts.where ? `WHERE ${opts.where}` : '';\n const linesCol = opts.semantic ? ', _find.lines' : '';\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 { 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, 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","find","db","cfg","terms","opts","hits","chunkLines","k","fetch","Math","max","whereJoin","where","whereCond","matchSql","matchRows","prepare","all","Map","map","r","path","hit","candidates","forEach","i","set","score","via","edges","length","linked","Set","flat","nodes","seeds","ranked","filter","sort","a","b","slice","existing","get","has","semantic","vec","lines","exec","insert","c","run","linesCol","INTERNAL_COLUMNS","mapTree","docs","columns","name","allFields","n","split","join","field","coverage","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;AAQd,mFAAmF;AACnF,4EAA4E;AAC5E,8EAA8E;AAC9E,kDAAkD;AAClD,OAAO,eAAeC,KAAKC,EAAgB,EAAEC,GAAW,EAAEC,KAAa,EAAEC,OAAoB,CAAC,CAAC;QACnFA,SA8D2DC,WAAwBC;IA9D7F,MAAMC,KAAIH,UAAAA,KAAKG,CAAC,cAANH,qBAAAA,UAAU;IACpB,MAAMI,QAAQC,KAAKC,GAAG,CAACH,IAAI,GAAG;IAE9B,sFAAsF;IACtF,yFAAyF;IACzF,sFAAsF;IACtF,qFAAqF;IACrF,MAAMI,YAAYP,KAAKQ,KAAK,GAAG,CAAC,6CAA6C,CAAC,GAAG;IACjF,MAAMC,YAAYT,KAAKQ,KAAK,GAAG,CAAC,KAAK,EAAER,KAAKQ,KAAK,CAAC,CAAC,CAAC,GA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AkB,EAAE;IAE1L,IAAIiE,WAAqB,EAAE;IAC3B,IAAIC,YAAsB,EAAE;IAC5B,IAAIC,aAAuB,EAAE;IAC7B,IAAIC,iBAAiB;IACrB,IAAIjG,eAAeU,KAAK,UAAU;QAChC,MAAMwF,MAAMzF,GAAGe,OAAO,CAAC,+DAA+DC,GAAG,CAACI;QAC1FiE,WAAW;eAAI,IAAItD,IAAI0D,IAAIrD,MAAM,CAAC,CAACsD,IAAMA,EAAEC,GAAG,KAAK,MAAMzE,GAAG,CAAC,CAACwE,IAAMA,EAAEC,GAAG;SAAa;QACtFJ,aAAaE,IAAIrD,MAAM,CAAC,CAACsD,IAAMA,EAAEC,GAAG,KAAK,MAAMzE,GAAG,CAAC,CAACwE,IAAMA,EAAEE,MAAM;QAClEJ,iBAAiB,AAACxF,GAAGe,OAAO,CAAC,4DAA4D2B,GAAG,CAACtB,MAAwBsC,CAAC;QACtH4B,YAAY,AAACtF,GAAGe,OAAO,CAAC,qEAAqEC,GAAG,CAACI,MAAMgD,iBAA4ClD,GAAG,CAAC,CAACC,IAAMA,EAAE0E,GAAG;IACrK;IAEA,OAAO;QACLzE;QACA0E,QAAQtF,KAAKuF,IAAI,CAAC,EAAExB,aAAAA,IAAIyB,KAAK,cAATzB,wBAAAA,aAAwB,KAAK;QACjDQ;QACAK;QACAC,UAAUA,SAAS7C,KAAK,CAAC,GAAG4B;QAC5BkB;QACAC,YAAYA,WAAW/C,KAAK,CAAC,GAAG4B;QAChC6B,eAAeZ,SAASxD,MAAM;QAC9B2D;QACAU,iBAAiBX,WAAW1D,MAAM;QAClCsE,KAAK,AAAC;YAAC;YAAY;SAAQ,CAAmB/D,MAAM,CAAC,CAACoB,OAAS,CAACjE,eAAeU,KAAKuD;IACtF;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","unresolvedTot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6 @@
1
1
  {
2
2
  "name": "sensemaking",
3
- "version": "0.6.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",
package/schema.json CHANGED
@@ -64,9 +64,27 @@
64
64
  }
65
65
  }
66
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
+ }
82
+ }
83
+ }
84
+ },
67
85
  "queries": {
68
86
  "type": "object",
69
- "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`.",
70
88
  "additionalProperties": { "type": "string" }
71
89
  }
72
90
  }
@@ -45,7 +45,7 @@ sense peek notes/pricing-model.md # a unique basename also works
45
45
  sense map
46
46
  sense query "<sql>" [params...] # ad-hoc SQL; ? binds positional args, count-checked
47
47
  sense <name> [params...] # named query from sense.config.json
48
- sense --list | status | rebuild
48
+ sense --list | status | rebuild | check
49
49
  ```
50
50
 
51
51
  - Terms pass verbatim to FTS5 MATCH. Bare words AND-join — one absent word means zero rows —
@@ -63,7 +63,24 @@ sense --list | status | rebuild
63
63
  `match` (terms hit), `link` (connected to notes that hit), `match+link` (both). With
64
64
  `--semantic`, `vector` joins the composition and rows gain a `lines` column pointing at the
65
65
  best-matching section, a direct `Read` range.
66
- - `--where` takes a frontmatter condition against alias `f`, e.g. `"f.status = 'active' AND has(f.tags, 'x')"`.
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.
67
84
 
68
85
  ## SQL
69
86
 
@@ -87,6 +104,10 @@ sense query "SELECT j.value, COUNT(*) n FROM frontmatter, json_each(frontmatter.
87
104
  `snippet(content, -1, '«', '»', '…', 10)`.
88
105
  - Select `content.title`/`content.summary` (always exist, empty when absent) rather than
89
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.
90
111
  - `has(field, value)`: array membership on JSON-array fields, substring on strings, false on NULL
91
112
  — the `includes()` convention. Substring means `has(f.status, 'active')` also matches
92
113
  `inactive`; exact scalar match is `f.status = ?`, deliberate substring is `LIKE`, exact array
@@ -31,6 +31,16 @@ installing, configuring features, and the design decisions a tree owner faces.
31
31
  Face id or local path), `type` (`static` pure-JS built-in, or `api` for any
32
32
  OpenAI-compatible `/v1/embeddings` endpoint — Ollama, LM Studio, llama.cpp,
33
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.
34
44
  - Enabling `embed` changes no default `find` result — expansion runs only when
35
45
  a query passes `--semantic`. Invoking `--semantic` on a tree without `embed`
36
46
  is an error naming the config key.
@@ -46,10 +56,18 @@ do, and every consequence is listed so the choice can be made deliberately.
46
56
 
47
57
  - **Frontmatter fields.** Columns are discovered per tree — whatever keys notes
48
58
  declare become queryable. Consistent fields across notes make SQL filters
49
- and named queries possible (`WHERE status = 'active'`); inconsistent fields
50
- still work but produce sparse columns that filter less of the tree. Reserved
51
- keys (dropped with a warning): `path`, `_mtime`, `_size`, `_rank`, `content`,
52
- `links`, `sections`.
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.
53
71
  - **Dates.** `datetime()` comparisons work for dates written as ISO 8601 —
54
72
  the only format it parses. A tree that mixes date formats can store them,
55
73
  but can't compare them in SQL.