sensemaking 0.12.2 → 0.13.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 (245) hide show
  1. package/dist/cjs/cli/download.js +4 -4
  2. package/dist/cjs/cli/download.js.map +1 -1
  3. package/dist/cjs/cli/init.js +4 -4
  4. package/dist/cjs/cli/init.js.map +1 -1
  5. package/dist/cjs/cli/map.js +4 -4
  6. package/dist/cjs/cli/map.js.map +1 -1
  7. package/dist/cjs/cli/named.js +2 -2
  8. package/dist/cjs/cli/named.js.map +1 -1
  9. package/dist/cjs/cli/path.js +6 -6
  10. package/dist/cjs/cli/path.js.map +1 -1
  11. package/dist/cjs/cli/peek.js +4 -4
  12. package/dist/cjs/cli/peek.js.map +1 -1
  13. package/dist/cjs/cli/related.js +4 -4
  14. package/dist/cjs/cli/related.js.map +1 -1
  15. package/dist/cjs/cli/search.js +4 -4
  16. package/dist/cjs/cli/search.js.map +1 -1
  17. package/dist/cjs/cli/shared.d.cts +2 -2
  18. package/dist/cjs/cli/shared.d.ts +2 -2
  19. package/dist/cjs/cli/shared.js +5 -5
  20. package/dist/cjs/cli/shared.js.map +1 -1
  21. package/dist/cjs/cli/status.js +16 -16
  22. package/dist/cjs/cli/status.js.map +1 -1
  23. package/dist/cjs/cli/types.d.cts +1 -1
  24. package/dist/cjs/cli/types.d.ts +1 -1
  25. package/dist/cjs/cli.js +3 -3
  26. package/dist/cjs/cli.js.map +1 -1
  27. package/dist/cjs/commands/index.d.cts +10 -0
  28. package/dist/cjs/commands/index.d.ts +10 -0
  29. package/dist/cjs/commands/index.js +42 -0
  30. package/dist/cjs/commands/index.js.map +1 -0
  31. package/dist/cjs/commands/map.d.cts +21 -0
  32. package/dist/cjs/commands/map.d.ts +21 -0
  33. package/dist/cjs/commands/map.js +90 -0
  34. package/dist/cjs/commands/map.js.map +1 -0
  35. package/dist/cjs/commands/peek.d.cts +20 -0
  36. package/dist/cjs/commands/peek.d.ts +20 -0
  37. package/dist/cjs/commands/peek.js +175 -0
  38. package/dist/cjs/commands/peek.js.map +1 -0
  39. package/dist/cjs/commands/related.d.cts +6 -0
  40. package/dist/cjs/commands/related.d.ts +6 -0
  41. package/dist/cjs/commands/related.js +232 -0
  42. package/dist/cjs/commands/related.js.map +1 -0
  43. package/dist/cjs/commands/scope.d.cts +10 -0
  44. package/dist/cjs/commands/scope.d.ts +10 -0
  45. package/dist/cjs/commands/scope.js +124 -0
  46. package/dist/cjs/commands/scope.js.map +1 -0
  47. package/dist/cjs/commands/search.d.cts +12 -0
  48. package/dist/cjs/commands/search.d.ts +12 -0
  49. package/dist/cjs/{commands.js → commands/search.js} +20 -358
  50. package/dist/cjs/commands/search.js.map +1 -0
  51. package/dist/cjs/commands/status.d.cts +9 -0
  52. package/dist/cjs/commands/status.d.ts +9 -0
  53. package/dist/cjs/commands/status.js +25 -0
  54. package/dist/cjs/commands/status.js.map +1 -0
  55. package/dist/cjs/config/access.d.cts +19 -0
  56. package/dist/cjs/config/access.d.ts +19 -0
  57. package/dist/cjs/config/access.js +149 -0
  58. package/dist/cjs/config/access.js.map +1 -0
  59. package/dist/cjs/config/index.d.cts +5 -0
  60. package/dist/cjs/config/index.d.ts +5 -0
  61. package/dist/cjs/config/index.js +77 -0
  62. package/dist/cjs/config/index.js.map +1 -0
  63. package/dist/cjs/config/load.d.cts +8 -0
  64. package/dist/cjs/config/load.d.ts +8 -0
  65. package/dist/cjs/config/load.js +448 -0
  66. package/dist/cjs/config/load.js.map +1 -0
  67. package/dist/cjs/config/resolve.d.cts +6 -0
  68. package/dist/cjs/config/resolve.d.ts +6 -0
  69. package/dist/cjs/config/resolve.js +50 -0
  70. package/dist/cjs/config/resolve.js.map +1 -0
  71. package/dist/{esm/config.d.ts → cjs/config/types.d.cts} +2 -32
  72. package/dist/cjs/{config.d.cts → config/types.d.ts} +2 -32
  73. package/dist/cjs/config/types.js +39 -0
  74. package/dist/cjs/config/types.js.map +1 -0
  75. package/dist/cjs/config/validate.d.cts +4 -0
  76. package/dist/cjs/config/validate.d.ts +4 -0
  77. package/dist/cjs/config/validate.js +363 -0
  78. package/dist/cjs/config/validate.js.map +1 -0
  79. package/dist/cjs/db/index.d.cts +4 -0
  80. package/dist/cjs/db/index.d.ts +4 -0
  81. package/dist/cjs/db/index.js +42 -0
  82. package/dist/cjs/db/index.js.map +1 -0
  83. package/dist/cjs/{db.d.cts → db/open.d.cts} +2 -8
  84. package/dist/cjs/{db.d.ts → db/open.d.ts} +2 -8
  85. package/dist/cjs/db/open.js +223 -0
  86. package/dist/cjs/db/open.js.map +1 -0
  87. package/dist/cjs/db/reconcile.d.cts +9 -0
  88. package/dist/cjs/db/reconcile.d.ts +9 -0
  89. package/dist/cjs/{db.js → db/reconcile.js} +24 -261
  90. package/dist/cjs/db/reconcile.js.map +1 -0
  91. package/dist/cjs/db/shared.d.cts +5 -0
  92. package/dist/cjs/db/shared.d.ts +5 -0
  93. package/dist/cjs/db/shared.js +45 -0
  94. package/dist/cjs/db/shared.js.map +1 -0
  95. package/dist/cjs/features/embed.d.cts +1 -1
  96. package/dist/cjs/features/embed.d.ts +1 -1
  97. package/dist/cjs/features/embed.js +4 -3
  98. package/dist/cjs/features/embed.js.map +1 -1
  99. package/dist/cjs/features/index.d.cts +1 -1
  100. package/dist/cjs/features/index.d.ts +1 -1
  101. package/dist/cjs/features/index.js +4 -2
  102. package/dist/cjs/features/index.js.map +1 -1
  103. package/dist/cjs/features/links.js +38 -20
  104. package/dist/cjs/features/links.js.map +1 -1
  105. package/dist/cjs/features/tags.d.cts +2 -0
  106. package/dist/cjs/features/tags.d.ts +2 -0
  107. package/dist/cjs/features/tags.js +188 -0
  108. package/dist/cjs/features/tags.js.map +1 -0
  109. package/dist/cjs/features/types.d.cts +2 -2
  110. package/dist/cjs/features/types.d.ts +2 -2
  111. package/dist/cjs/index.d.cts +6 -6
  112. package/dist/cjs/index.d.ts +6 -6
  113. package/dist/cjs/index.js +15 -15
  114. package/dist/cjs/index.js.map +1 -1
  115. package/dist/cjs/scan.d.cts +3 -1
  116. package/dist/cjs/scan.d.ts +3 -1
  117. package/dist/cjs/scan.js +9 -6
  118. package/dist/cjs/scan.js.map +1 -1
  119. package/dist/cjs/sql-functions.d.cts +2 -0
  120. package/dist/cjs/sql-functions.d.ts +2 -0
  121. package/dist/cjs/sql-functions.js +64 -0
  122. package/dist/cjs/sql-functions.js.map +1 -0
  123. package/dist/cjs/watch.d.cts +1 -1
  124. package/dist/cjs/watch.d.ts +1 -1
  125. package/dist/cjs/watch.js +12 -12
  126. package/dist/cjs/watch.js.map +1 -1
  127. package/dist/esm/cli/download.js +1 -1
  128. package/dist/esm/cli/download.js.map +1 -1
  129. package/dist/esm/cli/init.js +1 -1
  130. package/dist/esm/cli/init.js.map +1 -1
  131. package/dist/esm/cli/map.js +1 -1
  132. package/dist/esm/cli/map.js.map +1 -1
  133. package/dist/esm/cli/named.js +1 -1
  134. package/dist/esm/cli/named.js.map +1 -1
  135. package/dist/esm/cli/path.js +1 -1
  136. package/dist/esm/cli/path.js.map +1 -1
  137. package/dist/esm/cli/peek.js +1 -1
  138. package/dist/esm/cli/peek.js.map +1 -1
  139. package/dist/esm/cli/related.js +1 -1
  140. package/dist/esm/cli/related.js.map +1 -1
  141. package/dist/esm/cli/search.js +1 -1
  142. package/dist/esm/cli/search.js.map +1 -1
  143. package/dist/esm/cli/shared.d.ts +2 -2
  144. package/dist/esm/cli/shared.js +2 -2
  145. package/dist/esm/cli/shared.js.map +1 -1
  146. package/dist/esm/cli/status.js +3 -3
  147. package/dist/esm/cli/status.js.map +1 -1
  148. package/dist/esm/cli/types.d.ts +1 -1
  149. package/dist/esm/cli/types.js.map +1 -1
  150. package/dist/esm/cli.js +1 -1
  151. package/dist/esm/cli.js.map +1 -1
  152. package/dist/esm/commands/index.d.ts +10 -0
  153. package/dist/esm/commands/index.js +8 -0
  154. package/dist/esm/commands/index.js.map +1 -0
  155. package/dist/esm/commands/map.d.ts +21 -0
  156. package/dist/esm/commands/map.js +56 -0
  157. package/dist/esm/commands/map.js.map +1 -0
  158. package/dist/esm/commands/peek.d.ts +20 -0
  159. package/dist/esm/commands/peek.js +63 -0
  160. package/dist/esm/commands/peek.js.map +1 -0
  161. package/dist/esm/commands/related.d.ts +6 -0
  162. package/dist/esm/commands/related.js +47 -0
  163. package/dist/esm/commands/related.js.map +1 -0
  164. package/dist/esm/commands/scope.d.ts +10 -0
  165. package/dist/esm/commands/scope.js +60 -0
  166. package/dist/esm/commands/scope.js.map +1 -0
  167. package/dist/esm/commands/search.d.ts +12 -0
  168. package/dist/esm/commands/search.js +258 -0
  169. package/dist/esm/commands/search.js.map +1 -0
  170. package/dist/esm/commands/status.d.ts +9 -0
  171. package/dist/esm/commands/status.js +16 -0
  172. package/dist/esm/commands/status.js.map +1 -0
  173. package/dist/esm/config/access.d.ts +19 -0
  174. package/dist/esm/config/access.js +89 -0
  175. package/dist/esm/config/access.js.map +1 -0
  176. package/dist/esm/config/index.d.ts +5 -0
  177. package/dist/esm/config/index.js +4 -0
  178. package/dist/esm/config/index.js.map +1 -0
  179. package/dist/esm/config/load.d.ts +8 -0
  180. package/dist/esm/config/load.js +242 -0
  181. package/dist/esm/config/load.js.map +1 -0
  182. package/dist/esm/config/resolve.d.ts +6 -0
  183. package/dist/esm/config/resolve.js +35 -0
  184. package/dist/esm/config/resolve.js.map +1 -0
  185. package/dist/{cjs/config.d.ts → esm/config/types.d.ts} +2 -32
  186. package/dist/esm/config/types.js +15 -0
  187. package/dist/esm/config/types.js.map +1 -0
  188. package/dist/esm/config/validate.d.ts +4 -0
  189. package/dist/esm/config/validate.js +226 -0
  190. package/dist/esm/config/validate.js.map +1 -0
  191. package/dist/esm/db/index.d.ts +4 -0
  192. package/dist/esm/db/index.js +5 -0
  193. package/dist/esm/db/index.js.map +1 -0
  194. package/dist/esm/{db.d.ts → db/open.d.ts} +2 -8
  195. package/dist/esm/db/open.js +160 -0
  196. package/dist/esm/db/open.js.map +1 -0
  197. package/dist/esm/db/reconcile.d.ts +9 -0
  198. package/dist/esm/{db.js → db/reconcile.js} +12 -216
  199. package/dist/esm/db/reconcile.js.map +1 -0
  200. package/dist/esm/db/shared.d.ts +5 -0
  201. package/dist/esm/db/shared.js +20 -0
  202. package/dist/esm/db/shared.js.map +1 -0
  203. package/dist/esm/features/embed.d.ts +1 -1
  204. package/dist/esm/features/embed.js +2 -1
  205. package/dist/esm/features/embed.js.map +1 -1
  206. package/dist/esm/features/index.d.ts +1 -1
  207. package/dist/esm/features/index.js +3 -1
  208. package/dist/esm/features/index.js.map +1 -1
  209. package/dist/esm/features/links.js +36 -21
  210. package/dist/esm/features/links.js.map +1 -1
  211. package/dist/esm/features/tags.d.ts +2 -0
  212. package/dist/esm/features/tags.js +80 -0
  213. package/dist/esm/features/tags.js.map +1 -0
  214. package/dist/esm/features/types.d.ts +2 -2
  215. package/dist/esm/features/types.js.map +1 -1
  216. package/dist/esm/index.d.ts +6 -6
  217. package/dist/esm/index.js +3 -3
  218. package/dist/esm/index.js.map +1 -1
  219. package/dist/esm/scan.d.ts +3 -1
  220. package/dist/esm/scan.js +5 -2
  221. package/dist/esm/scan.js.map +1 -1
  222. package/dist/esm/sql-functions.d.ts +2 -0
  223. package/dist/esm/sql-functions.js +47 -0
  224. package/dist/esm/sql-functions.js.map +1 -0
  225. package/dist/esm/watch.d.ts +1 -1
  226. package/dist/esm/watch.js +2 -2
  227. package/dist/esm/watch.js.map +1 -1
  228. package/package.json +2 -1
  229. package/schema.json +4 -0
  230. package/skills/sense/SKILL.md +3 -3
  231. package/skills/sense-bases/EXAMPLES.md +103 -0
  232. package/skills/sense-bases/SKILL.md +137 -0
  233. package/skills/sense-setup/SKILL.md +1 -1
  234. package/dist/cjs/commands.d.cts +0 -58
  235. package/dist/cjs/commands.d.ts +0 -58
  236. package/dist/cjs/commands.js.map +0 -1
  237. package/dist/cjs/config.js +0 -919
  238. package/dist/cjs/config.js.map +0 -1
  239. package/dist/cjs/db.js.map +0 -1
  240. package/dist/esm/commands.d.ts +0 -58
  241. package/dist/esm/commands.js +0 -486
  242. package/dist/esm/commands.js.map +0 -1
  243. package/dist/esm/config.js +0 -599
  244. package/dist/esm/config.js.map +0 -1
  245. package/dist/esm/db.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/sql-functions.ts"],"sourcesContent":["import posix from 'node:path/posix';\nimport type { DatabaseSync } from 'node:sqlite';\nimport { segmentMatch } from './segment.ts';\n\n// has(field, value): JSON-array field -> membership, string field -> substring, NULL -> false.\nexport function registerFunctions(db: DatabaseSync, segmenting: boolean): void {\n db.function('has', { deterministic: true, varargs: false }, (field: unknown, value: unknown): number => {\n if (field === null || field === undefined) return 0;\n\n const needle = String(value);\n\n if (typeof field === 'string') {\n if (field.startsWith('[')) {\n try {\n const parsed = JSON.parse(field);\n if (Array.isArray(parsed)) {\n return parsed.some((item) => String(item) === needle) ? 1 : 0;\n }\n } catch {}\n }\n return field.includes(needle) ? 1 : 0;\n }\n\n return String(field).includes(needle) ? 1 : 0;\n });\n\n // Unix basename(path, suffix?): the filename, minus suffix when it ends with one. SQLite\n // itself has no filename function, and the LIKE tricks that fake one also match folder names.\n db.function('basename', { deterministic: true, varargs: true }, (path: unknown, suffix?: unknown): string | null => {\n if (path === null || path === undefined) return null;\n const name = posix.basename(String(path));\n const tail = suffix === null || suffix === undefined ? '' : String(suffix);\n // POSIX: a suffix identical to the whole name is not removed (node's own basename strips it).\n return tail !== '' && tail !== name && name.endsWith(tail) ? name.slice(0, -tail.length) : name;\n });\n\n // Raw `content MATCH '<unspaced text>'` cannot be rewritten behind the author's back, and\n // matches nothing, so the same transform is available to hand-written SQL by name. `segmenting`\n // is the same config predicate commands.ts's search() gates on (contentTokenize(cfg) ===\n // undefined), passed in by open() rather than read back from persisted state.\n db.function('segment', { deterministic: true, varargs: false }, (terms: unknown): string => {\n const text = terms === null || terms === undefined ? '' : String(terms);\n return segmenting ? segmentMatch(text) : text;\n });\n}\n"],"names":["posix","segmentMatch","registerFunctions","db","segmenting","function","deterministic","varargs","field","value","undefined","needle","String","startsWith","parsed","JSON","parse","Array","isArray","some","item","includes","path","suffix","name","basename","tail","endsWith","slice","length","terms","text"],"mappings":"AAAA,OAAOA,WAAW,kBAAkB;AAEpC,SAASC,YAAY,QAAQ,eAAe;AAE5C,+FAA+F;AAC/F,OAAO,SAASC,kBAAkBC,EAAgB,EAAEC,UAAmB;IACrED,GAAGE,QAAQ,CAAC,OAAO;QAAEC,eAAe;QAAMC,SAAS;IAAM,GAAG,CAACC,OAAgBC;QAC3E,IAAID,UAAU,QAAQA,UAAUE,WAAW,OAAO;QAElD,MAAMC,SAASC,OAAOH;QAEtB,IAAI,OAAOD,UAAU,UAAU;YAC7B,IAAIA,MAAMK,UAAU,CAAC,MAAM;gBACzB,IAAI;oBACF,MAAMC,SAASC,KAAKC,KAAK,CAACR;oBAC1B,IAAIS,MAAMC,OAAO,CAACJ,SAAS;wBACzB,OAAOA,OAAOK,IAAI,CAAC,CAACC,OAASR,OAAOQ,UAAUT,UAAU,IAAI;oBAC9D;gBACF,EAAE,OAAM,CAAC;YACX;YACA,OAAOH,MAAMa,QAAQ,CAACV,UAAU,IAAI;QACtC;QAEA,OAAOC,OAAOJ,OAAOa,QAAQ,CAACV,UAAU,IAAI;IAC9C;IAEA,yFAAyF;IACzF,8FAA8F;IAC9FR,GAAGE,QAAQ,CAAC,YAAY;QAAEC,eAAe;QAAMC,SAAS;IAAK,GAAG,CAACe,MAAeC;QAC9E,IAAID,SAAS,QAAQA,SAASZ,WAAW,OAAO;QAChD,MAAMc,OAAOxB,MAAMyB,QAAQ,CAACb,OAAOU;QACnC,MAAMI,OAAOH,WAAW,QAAQA,WAAWb,YAAY,KAAKE,OAAOW;QACnE,8FAA8F;QAC9F,OAAOG,SAAS,MAAMA,SAASF,QAAQA,KAAKG,QAAQ,CAACD,QAAQF,KAAKI,KAAK,CAAC,GAAG,CAACF,KAAKG,MAAM,IAAIL;IAC7F;IAEA,0FAA0F;IAC1F,gGAAgG;IAChG,yFAAyF;IACzF,8EAA8E;IAC9ErB,GAAGE,QAAQ,CAAC,WAAW;QAAEC,eAAe;QAAMC,SAAS;IAAM,GAAG,CAACuB;QAC/D,MAAMC,OAAOD,UAAU,QAAQA,UAAUpB,YAAY,KAAKE,OAAOkB;QACjE,OAAO1B,aAAaH,aAAa8B,QAAQA;IAC3C;AACF"}
@@ -1,4 +1,4 @@
1
- import type { ResolvedConfig } from './config.js';
1
+ import type { ResolvedConfig } from './config/index.js';
2
2
  export type WatchEvent = {
3
3
  type: 'started';
4
4
  baseDir: string;
package/dist/esm/watch.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { watch as fsWatch } from 'node:fs';
2
- import { STATE_DIR } from './config.js';
3
- import { docCount, getMeta, open, reconcile, setMeta } from './db.js';
2
+ import { STATE_DIR } from './config/index.js';
3
+ import { docCount, getMeta, open, reconcile, setMeta } from './db/index.js';
4
4
  import { SenseError } from './errors.js';
5
5
  // Watch is a cache pre-warmer, not a correctness mechanism: open() always reconciles anyway, so any fs event just triggers a debounced full reconcile.
6
6
  const DEBOUNCE_MS = 200;
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/watch.ts"],"sourcesContent":["import { watch as fsWatch } from 'node:fs';\nimport type { ResolvedConfig } from './config.ts';\nimport { STATE_DIR } from './config.ts';\nimport { docCount, getMeta, open, reconcile, setMeta } from './db.ts';\nimport { SenseError } from './errors.ts';\n\n// Watch is a cache pre-warmer, not a correctness mechanism: open() always reconciles anyway, so any fs event just triggers a debounced full reconcile.\nconst DEBOUNCE_MS = 200;\nconst HEARTBEAT_INTERVAL_MS = 5000;\nconst STALE_HEARTBEAT_MS = 15000;\n\nexport type WatchEvent = { type: 'started'; baseDir: string; dbPath: string } | { type: 'reconciled'; parsed: number; total: number; warnings: string[] } | { type: 'reconcile-error'; message: string };\n\nexport interface WatchOptions {\n force?: boolean;\n onEvent?: (event: WatchEvent) => void;\n}\n\n// Runs in the foreground until SIGINT/SIGTERM. Throws WATCH_ACTIVE if another watcher's heartbeat is still fresh and --force wasn't given.\nexport async function runWatch(cfg: ResolvedConfig, opts: WatchOptions = {}): Promise<void> {\n const onEvent = opts.onEvent ?? (() => {});\n const { db, dbPath, warnings: initialWarnings, parsed: initialParsed } = open(cfg);\n const baseDir = cfg.baseDir;\n\n const existingHeartbeat = getMeta(db, 'watch_heartbeat');\n if (existingHeartbeat && !opts.force) {\n const age = Date.now() - Date.parse(existingHeartbeat);\n if (age >= 0 && age < STALE_HEARTBEAT_MS) {\n db.close();\n throw new SenseError('WATCH_ACTIVE', `another watcher appears active (heartbeat ${Math.round(age / 1000)}s ago); use --force to override`);\n }\n }\n\n onEvent({ type: 'started', baseDir, dbPath });\n if (initialWarnings.length > 0 || initialParsed > 0) {\n onEvent({ type: 'reconciled', parsed: initialParsed, total: docCount(db), warnings: initialWarnings });\n }\n\n const touchHeartbeat = () => {\n setMeta(db, 'watch_heartbeat', new Date().toISOString());\n setMeta(db, 'watch_pid', String(process.pid));\n };\n touchHeartbeat();\n\n let debounceTimer: NodeJS.Timeout | null = null;\n const scheduleReconcile = () => {\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n try {\n const { parsed, warnings } = reconcile(db, cfg, baseDir);\n onEvent({ type: 'reconciled', parsed, total: docCount(db), warnings });\n } catch (err) {\n onEvent({ type: 'reconcile-error', message: (err as Error).message });\n }\n }, DEBOUNCE_MS);\n };\n\n // Ignore our own state dir, or the heartbeat write would retrigger itself forever.\n const watcher = fsWatch(baseDir, { recursive: true }, (_event, filename) => {\n if (typeof filename === 'string' && filename.startsWith(STATE_DIR)) return;\n scheduleReconcile();\n });\n const heartbeatTimer = setInterval(touchHeartbeat, HEARTBEAT_INTERVAL_MS);\n\n return new Promise<void>((resolveShutdown) => {\n const cleanExit = () => {\n clearInterval(heartbeatTimer);\n if (debounceTimer) clearTimeout(debounceTimer);\n watcher.close();\n setMeta(db, 'watch_heartbeat', null);\n setMeta(db, 'watch_pid', null);\n db.close();\n resolveShutdown();\n };\n process.once('SIGINT', cleanExit);\n process.once('SIGTERM', cleanExit);\n });\n}\n"],"names":["watch","fsWatch","STATE_DIR","docCount","getMeta","open","reconcile","setMeta","SenseError","DEBOUNCE_MS","HEARTBEAT_INTERVAL_MS","STALE_HEARTBEAT_MS","runWatch","cfg","opts","onEvent","db","dbPath","warnings","initialWarnings","parsed","initialParsed","baseDir","existingHeartbeat","force","age","Date","now","parse","close","Math","round","type","length","total","touchHeartbeat","toISOString","String","process","pid","debounceTimer","scheduleReconcile","clearTimeout","setTimeout","err","message","watcher","recursive","_event","filename","startsWith","heartbeatTimer","setInterval","Promise","resolveShutdown","cleanExit","clearInterval","once"],"mappings":"AAAA,SAASA,SAASC,OAAO,QAAQ,UAAU;AAE3C,SAASC,SAAS,QAAQ,cAAc;AACxC,SAASC,QAAQ,EAAEC,OAAO,EAAEC,IAAI,EAAEC,SAAS,EAAEC,OAAO,QAAQ,UAAU;AACtE,SAASC,UAAU,QAAQ,cAAc;AAEzC,uJAAuJ;AACvJ,MAAMC,cAAc;AACpB,MAAMC,wBAAwB;AAC9B,MAAMC,qBAAqB;AAS3B,2IAA2I;AAC3I,OAAO,eAAeC,SAASC,GAAmB,EAAEC,OAAqB,CAAC,CAAC;QACzDA;IAAhB,MAAMC,WAAUD,gBAAAA,KAAKC,OAAO,cAAZD,2BAAAA,gBAAiB,KAAO;IACxC,MAAM,EAAEE,EAAE,EAAEC,MAAM,EAAEC,UAAUC,eAAe,EAAEC,QAAQC,aAAa,EAAE,GAAGhB,KAAKQ;IAC9E,MAAMS,UAAUT,IAAIS,OAAO;IAE3B,MAAMC,oBAAoBnB,QAAQY,IAAI;IACtC,IAAIO,qBAAqB,CAACT,KAAKU,KAAK,EAAE;QACpC,MAAMC,MAAMC,KAAKC,GAAG,KAAKD,KAAKE,KAAK,CAACL;QACpC,IAAIE,OAAO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S,IAAI,mBAAmB;YAC/BT,QAAQS,IAAI,aAAa;YACzBA,GAAGa,KAAK;YACRyB;QACF;QACAhB,QAAQmB,IAAI,CAAC,UAAUF;QACvBjB,QAAQmB,IAAI,CAAC,WAAWF;IAC1B;AACF"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/watch.ts"],"sourcesContent":["import { watch as fsWatch } from 'node:fs';\nimport type { ResolvedConfig } from './config/index.ts';\nimport { STATE_DIR } from './config/index.ts';\nimport { docCount, getMeta, open, reconcile, setMeta } from './db/index.ts';\nimport { SenseError } from './errors.ts';\n\n// Watch is a cache pre-warmer, not a correctness mechanism: open() always reconciles anyway, so any fs event just triggers a debounced full reconcile.\nconst DEBOUNCE_MS = 200;\nconst HEARTBEAT_INTERVAL_MS = 5000;\nconst STALE_HEARTBEAT_MS = 15000;\n\nexport type WatchEvent = { type: 'started'; baseDir: string; dbPath: string } | { type: 'reconciled'; parsed: number; total: number; warnings: string[] } | { type: 'reconcile-error'; message: string };\n\nexport interface WatchOptions {\n force?: boolean;\n onEvent?: (event: WatchEvent) => void;\n}\n\n// Runs in the foreground until SIGINT/SIGTERM. Throws WATCH_ACTIVE if another watcher's heartbeat is still fresh and --force wasn't given.\nexport async function runWatch(cfg: ResolvedConfig, opts: WatchOptions = {}): Promise<void> {\n const onEvent = opts.onEvent ?? (() => {});\n const { db, dbPath, warnings: initialWarnings, parsed: initialParsed } = open(cfg);\n const baseDir = cfg.baseDir;\n\n const existingHeartbeat = getMeta(db, 'watch_heartbeat');\n if (existingHeartbeat && !opts.force) {\n const age = Date.now() - Date.parse(existingHeartbeat);\n if (age >= 0 && age < STALE_HEARTBEAT_MS) {\n db.close();\n throw new SenseError('WATCH_ACTIVE', `another watcher appears active (heartbeat ${Math.round(age / 1000)}s ago); use --force to override`);\n }\n }\n\n onEvent({ type: 'started', baseDir, dbPath });\n if (initialWarnings.length > 0 || initialParsed > 0) {\n onEvent({ type: 'reconciled', parsed: initialParsed, total: docCount(db), warnings: initialWarnings });\n }\n\n const touchHeartbeat = () => {\n setMeta(db, 'watch_heartbeat', new Date().toISOString());\n setMeta(db, 'watch_pid', String(process.pid));\n };\n touchHeartbeat();\n\n let debounceTimer: NodeJS.Timeout | null = null;\n const scheduleReconcile = () => {\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n try {\n const { parsed, warnings } = reconcile(db, cfg, baseDir);\n onEvent({ type: 'reconciled', parsed, total: docCount(db), warnings });\n } catch (err) {\n onEvent({ type: 'reconcile-error', message: (err as Error).message });\n }\n }, DEBOUNCE_MS);\n };\n\n // Ignore our own state dir, or the heartbeat write would retrigger itself forever.\n const watcher = fsWatch(baseDir, { recursive: true }, (_event, filename) => {\n if (typeof filename === 'string' && filename.startsWith(STATE_DIR)) return;\n scheduleReconcile();\n });\n const heartbeatTimer = setInterval(touchHeartbeat, HEARTBEAT_INTERVAL_MS);\n\n return new Promise<void>((resolveShutdown) => {\n const cleanExit = () => {\n clearInterval(heartbeatTimer);\n if (debounceTimer) clearTimeout(debounceTimer);\n watcher.close();\n setMeta(db, 'watch_heartbeat', null);\n setMeta(db, 'watch_pid', null);\n db.close();\n resolveShutdown();\n };\n process.once('SIGINT', cleanExit);\n process.once('SIGTERM', cleanExit);\n });\n}\n"],"names":["watch","fsWatch","STATE_DIR","docCount","getMeta","open","reconcile","setMeta","SenseError","DEBOUNCE_MS","HEARTBEAT_INTERVAL_MS","STALE_HEARTBEAT_MS","runWatch","cfg","opts","onEvent","db","dbPath","warnings","initialWarnings","parsed","initialParsed","baseDir","existingHeartbeat","force","age","Date","now","parse","close","Math","round","type","length","total","touchHeartbeat","toISOString","String","process","pid","debounceTimer","scheduleReconcile","clearTimeout","setTimeout","err","message","watcher","recursive","_event","filename","startsWith","heartbeatTimer","setInterval","Promise","resolveShutdown","cleanExit","clearInterval","once"],"mappings":"AAAA,SAASA,SAASC,OAAO,QAAQ,UAAU;AAE3C,SAASC,SAA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eAAeE,aAAaF;QAChCA,gBAAgBG,WAAW;YACzBH,gBAAgB;YAChB,IAAI;gBACF,MAAM,EAAEpB,MAAM,EAAEF,QAAQ,EAAE,GAAGZ,UAAUU,IAAIH,KAAKS;gBAChDP,QAAQ;oBAAEiB,MAAM;oBAAcZ;oBAAQc,OAAO/B,SAASa;oBAAKE;gBAAS;YACtE,EAAE,OAAO0B,KAAK;gBACZ7B,QAAQ;oBAAEiB,MAAM;oBAAmBa,SAAS,AAACD,IAAcC,OAAO;gBAAC;YACrE;QACF,GAAGpC;IACL;IAEA,mFAAmF;IACnF,MAAMqC,UAAU7C,QAAQqB,SAAS;QAAEyB,WAAW;IAAK,GAAG,CAACC,QAAQC;QAC7D,IAAI,OAAOA,aAAa,YAAYA,SAASC,UAAU,CAAChD,YAAY;QACpEuC;IACF;IACA,MAAMU,iBAAiBC,YAAYjB,gBAAgBzB;IAEnD,OAAO,IAAI2C,QAAc,CAACC;QACxB,MAAMC,YAAY;YAChBC,cAAcL;YACd,IAAIX,eAAeE,aAAaF;YAChCM,QAAQjB,KAAK;YACbtB,QAAQS,IAAI,mBAAmB;YAC/BT,QAAQS,IAAI,aAAa;YACzBA,GAAGa,KAAK;YACRyB;QACF;QACAhB,QAAQmB,IAAI,CAAC,UAAUF;QACvBjB,QAAQmB,IAAI,CAAC,WAAWF;IAC1B;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sensemaking",
3
- "version": "0.12.2",
3
+ "version": "0.13.0",
4
4
  "description": "Query and search your markdown notes with context-aware progressive disclosure: SQL over frontmatter, links, and text, plus semantic search and link-graph ranking. No server, no build step",
5
5
  "keywords": [
6
6
  "markdown",
@@ -27,6 +27,7 @@
27
27
  "notes",
28
28
  "obsidian",
29
29
  "markdowndb",
30
+ "mdbase",
30
31
  "iwe",
31
32
  "silverbullet",
32
33
  "logseq",
package/schema.json CHANGED
@@ -65,6 +65,10 @@
65
65
  "type": "boolean",
66
66
  "description": "Extract headings into the `sections` table (path, idx, level, heading, start_line, end_line, tokens estimate). Powers `peek`'s outline so agents can read line ranges instead of whole files."
67
67
  },
68
+ "tags": {
69
+ "type": "boolean",
70
+ "description": "Extract frontmatter and inline #tags into the `tags` table (path, tag), deduplicated and not distinguishing source -- Obsidian's `file.tags` grain. Nested tags store full (book/scifi); match a parent too with `tag = 'book' OR tag LIKE 'book/%'`."
71
+ },
68
72
  "rank": {
69
73
  "type": "boolean",
70
74
  "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`."
@@ -5,7 +5,7 @@ description: "Query a markdown tree with the sense CLI: filter notes by frontmat
5
5
 
6
6
  # sense
7
7
 
8
- SQL over a markdown tree, kept fresh by a filesystem check on every query. Every file becomes rows in `frontmatter` (one column per key, plus `path`/`_mtime`/`_size`/`_rank`/`_parse_error`), `content` (FTS5: `title`, `summary`, `text`, `path`, plus machine-written `title_seg`/`summary_seg`/`text_seg` sidecars used for matching Chinese, Japanese, Thai, Khmer, Lao, and Burmese text, not for reading), `links` (`src`, `target`, `dst`; `NULL` dst = dead link; one row per distinct written target with alias and anchor stripped, so `[[Foo]]` and `[[Foo|alias]]` are one row while `[[Foo]]` and `[[notes/Foo]]` are two rows that can share a `dst`), `sections` (heading outline with line ranges and token estimates), and `preset_files` (`path`, `preset`: which presets cover which files). Features add their own storage; `map` and `status` report which are on.
8
+ SQL over a markdown tree, kept fresh by a filesystem check on every query. Every file becomes rows in `frontmatter` (one column per key, plus `path`/`_mtime`/`_ctime`/`_size`/`_rank`/`_parse_error`; `_ctime` is filesystem birthtime, which a clone or copy resets just like `_mtime`), `content` (FTS5: `title`, `summary`, `text`, `path`, plus machine-written `title_seg`/`summary_seg`/`text_seg` sidecars used for matching Chinese, Japanese, Thai, Khmer, Lao, and Burmese text, not for reading), `links` (`src`, `target`, `dst`, `embed`; `NULL` dst = dead link; `embed` 1 for `![[...]]` embeds, 0 for links; one row per distinct written target and kind with alias and anchor stripped, so `[[Foo]]` and `[[Foo|alias]]` are one row while `[[Foo]]` and `[[notes/Foo]]` are two rows that can share a `dst`, and a target both linked and embedded is a row of each kind), `tags` (`path`, `tag`: frontmatter and inline `#tags` merged and deduplicated; nested tags stored full, so `book/scifi` matches `tag = 'book' OR tag LIKE 'book/%'`), `sections` (heading outline with line ranges and token estimates), and `preset_files` (`path`, `preset`: which presets cover which files). Features add their own storage; `map` and `status` report which are on.
9
9
 
10
10
  ## What each tool is for
11
11
 
@@ -107,11 +107,11 @@ Worked traces: [EXAMPLES.md](EXAMPLES.md).
107
107
 
108
108
  ## Setup and upkeep
109
109
 
110
- - Missing CLI: `npm install -g sensemaking`. Missing config: `sense init` at the tree root. Discovery walks up from cwd; `--config <path>` overrides. Setting up or restructuring a tree (presets, frontmatter conventions, note design) is the `sense-setup` skill.
110
+ - Missing CLI: `npm install -g sensemaking`. Missing config: `sense init` at the tree root. Discovery walks up from cwd; `--config <path>` overrides. Setting up or restructuring a tree (presets, frontmatter conventions, note design) is the `sense-setup` skill. Translating an Obsidian Bases `.base` file into equivalent queries is the `sense-bases` skill.
111
111
  - `map` and `status` report each preset's coverage (files matched, embedded count). Indexing derives from presets, so the coverage numbers are how you see what a config actually indexes and embeds. A scope with fewer signals just uses fewer (a semantic-off preset searches lexically); a saved search naming an unknown preset errors when run, listing the declared ones.
112
112
  - Save a query into `sense.config.json` only when it will be reused; run ad-hoc otherwise.
113
113
  - A one-line `summary:` per note is optional and pays twice: it appears in result rows and is a weighted search field. Date comparisons work for dates written as ISO 8601 (`2026-08-12`, or with time and offset); other formats do not compare. Field names in examples (`status`, `tags`, `created`) are illustrative; your tree defines its own.
114
- - Reserved frontmatter keys (dropped with a warning): `path`, `_mtime`, `_size`, `_rank`, `_parse_error`, `content`, `links`, `sections`.
114
+ - Reserved frontmatter keys (dropped with a warning): `path`, `_mtime`, `_ctime`, `_size`, `_rank`, `_parse_error`, `content`, `links`, `sections`. The `tags` frontmatter column and the `tags` table coexist: the column holds the raw YAML list, the table the merged frontmatter+inline set.
115
115
  - A note whose frontmatter does not parse is indexed with **no** frontmatter columns and `_parse_error` set to the YAML message, which carries the line. Nothing is half-recovered: a non-NULL value is a value the author wrote. So a NULL column means the key was absent *or* the note did not parse, and `_parse_error` is how you tell: `WHERE status IS NULL AND _parse_error IS NULL` is "genuinely missing status". List what needs fixing with `sense sql "SELECT path, _parse_error FROM frontmatter WHERE _parse_error IS NOT NULL"`; fixing a file clears it on the next command. `sense status` reports the count.
116
116
  - Exit codes: `0` ok, `1` error (SQLite message verbatim), `2` usage (unknown query, wrong param count).
117
117
  - Doubted cache: delete the directory `sense status` prints on its `cache:` line. Rarely needed; every query reconciles first.
@@ -0,0 +1,103 @@
1
+ # sense-bases: worked translations
2
+
3
+ Two real `.base` shapes translated end to end. Field names are illustrative; your tree
4
+ defines its own.
5
+
6
+ ## A. Filtered, sorted table with formulas
7
+
8
+ The base: notes categorized as Movies, excluding templates, with a "To-watch" view of unseen
9
+ entries sorted by score.
10
+
11
+ ```yaml
12
+ filters:
13
+ and:
14
+ - categories.contains(link("Movies"))
15
+ - '!file.name.contains("Template")'
16
+ views:
17
+ - type: table
18
+ name: To-watch
19
+ filters:
20
+ and:
21
+ - last.isEmpty()
22
+ - rating.isEmpty()
23
+ order: [file.name, year, scoreImdb, runtime, director]
24
+ sort:
25
+ - { property: scoreImdb, direction: DESC }
26
+ - { property: file.name, direction: ASC }
27
+ ```
28
+
29
+ One view, one query. Base filters AND view filters; `order` is the SELECT list; `sort` the
30
+ ORDER BY. The link comparison is the literal written text (`[[Movies]]`), the name test uses
31
+ `basename` so a folder named Templates does not false-positive:
32
+
33
+ ```sql
34
+ SELECT basename(f.path, '.md') AS name, f.year, f.scoreImdb, f.runtime, f.director
35
+ FROM frontmatter f
36
+ WHERE EXISTS (SELECT 1 FROM json_each(f.categories) WHERE value = '[[Movies]]')
37
+ AND instr(basename(f.path), 'Template') = 0
38
+ AND (f.last IS NULL OR f.last = '[null]')
39
+ AND (f.rating IS NULL OR f.rating = '[null]')
40
+ ORDER BY f.scoreImdb DESC, name ASC
41
+ ```
42
+
43
+ Saved in `sense.config.json` under `queries` as e.g. `to-watch`, it runs as `sense to-watch`.
44
+
45
+ ## B. `this`-relative: the Related pattern
46
+
47
+ The base: for the current note, every other note ranked by shared outgoing links, including
48
+ anything it links or that links to it.
49
+
50
+ ```yaml
51
+ filters:
52
+ and:
53
+ - file.path != this.file.path
54
+ formulas:
55
+ Related: list(this.file.links).filter(list(file.links).containsAny(value)).unique()
56
+ LinksOverlap: formula.Related.length
57
+ views:
58
+ - type: table
59
+ name: Related
60
+ filters:
61
+ or:
62
+ - formula.LinksOverlap > 2
63
+ - file.hasLink(this)
64
+ - this.file.hasLink(file)
65
+ sort:
66
+ - { property: formula.LinksOverlap, direction: DESC }
67
+ limit: 20
68
+ ```
69
+
70
+ `this` becomes one bound path. The chained list formula (`filter(...containsAny).unique()`)
71
+ is set intersection, which SQL states as an IN-filtered count; the `Related` list itself is
72
+ the same rows through `GROUP_CONCAT`:
73
+
74
+ ```sql
75
+ WITH me AS (SELECT ? AS p),
76
+ mine AS (SELECT DISTINCT dst FROM links, me WHERE src = me.p AND dst IS NOT NULL),
77
+ scored AS (
78
+ SELECT f.path,
79
+ (SELECT COUNT(DISTINCT l.dst) FROM links l
80
+ WHERE l.src = f.path AND l.dst IN (SELECT dst FROM mine)) AS overlap,
81
+ EXISTS (SELECT 1 FROM links, me WHERE src = f.path AND dst = me.p) AS links_to_me,
82
+ EXISTS (SELECT 1 FROM links, me WHERE src = me.p AND dst = f.path) AS linked_by_me,
83
+ (SELECT GROUP_CONCAT(DISTINCT l.dst) FROM links l
84
+ WHERE l.src = f.path AND l.dst IN (SELECT dst FROM mine)) AS shared_links
85
+ FROM frontmatter f, me WHERE f.path != me.p)
86
+ SELECT path, overlap, shared_links FROM scored
87
+ WHERE overlap > 2 OR links_to_me OR linked_by_me
88
+ ORDER BY overlap DESC
89
+ LIMIT 20
90
+ ```
91
+
92
+ Run as `sense sql "..." current-note.md`, or saved with the `?` in place and the path passed
93
+ as the parameter. The `or:` block reproduces Obsidian's semantics exactly: rows qualify by
94
+ overlap, by linking to the note, or by being linked from it -- so leaf notes the current note
95
+ links to appear even at zero overlap, as they do in Obsidian.
96
+
97
+ ## Notes that recur across translations
98
+
99
+ - Multiple views over the same base share the base-level filter; write it once per query
100
+ rather than factoring it out -- saved queries are self-contained by design.
101
+ - `sort` keys referencing formulas sort by the SELECT alias.
102
+ - A `groupBy` view keeps its rows; see the window-function shape in SKILL.md. Only a
103
+ deliberately collapsed report wants `GROUP BY`.
@@ -0,0 +1,137 @@
1
+ ---
2
+ name: sense-bases
3
+ description: "Translate an Obsidian Bases .base file into sense SQL that returns the same rows. Use when asked to convert, import, or reproduce a .base file (or a Bases view, filter, or formula) with sense, or when a markdown tree contains .base files whose views someone wants queryable outside Obsidian."
4
+ ---
5
+
6
+ # sense-bases
7
+
8
+ A `.base` file is YAML: filters selecting notes, formulas computing values, and views ordering
9
+ and grouping them. Obsidian evaluates it against its own metadata cache; sense holds the same
10
+ data in SQL tables. Every Bases construct that selects or computes rows has a SQL equivalent.
11
+ What has none is presentation (`columnSize`, card layout) -- those change pixels, not rows, so
12
+ a translation loses nothing by ignoring them.
13
+
14
+ Translate one view to one query: base-level `filters` AND the view's `filters`, the view's
15
+ `order`/`sort`/`limit` as the SELECT list, ORDER BY, and LIMIT. A base with four views becomes
16
+ four queries; saving them under the base's name in `sense.config.json`'s `queries` block keeps
17
+ them runnable as `sense <name>`. The general query surface is the `sense` skill; this one only
18
+ maps Bases constructs onto it.
19
+
20
+ ## Properties
21
+
22
+ | Bases | sense | notes |
23
+ |---|---|---|
24
+ | `note.field` / bare `field` | `f.<field>` | frontmatter column, same name |
25
+ | `file.name` | `basename(f.path, '.md')` | the Name column: no directory, no extension |
26
+ | a name with extension | `basename(f.path)` | the suffix arg is Unix basename's: present, stripped |
27
+ | `file.folder` | `f.path LIKE 'Folder/%'` | for `inFolder("Folder")` |
28
+ | `file.ext` | `'md'` | sense indexes only markdown |
29
+ | `file.size` | `f._size` | bytes |
30
+ | `file.mtime` | `datetime(f._mtime / 1000, 'unixepoch')` | stored as ms |
31
+ | `file.ctime` | `datetime(f._ctime / 1000, 'unixepoch')` | see the caveat below |
32
+ | `file.tags` | the `tags` table | frontmatter + inline `#tags`, deduplicated, Obsidian's grain |
33
+ | `file.links` | `links WHERE embed = 0` | one row per distinct written target |
34
+ | `file.embeds` | `links WHERE embed = 1` | |
35
+ | `file.backlinks` | `links WHERE dst = f.path` | |
36
+ | `this` | a bound `?` | see below |
37
+
38
+ `file.ctime` is the filesystem's creation time. A `git clone` or a copy resets it, so on a
39
+ tree that arrived as a checkout, every ctime is the checkout date and age formulas are wrong
40
+ about authorship without being wrong about the filesystem. `map` warns when modification
41
+ times have this shape; creation times share it.
42
+
43
+ ## Predicates
44
+
45
+ | Bases | sense |
46
+ |---|---|
47
+ | `==` `!=` `>` `<` `>=` `<=` | same |
48
+ | `&&` `\|\|` `!` | `AND` `OR` `NOT` |
49
+ | `and:` / `or:` / `not:` filter blocks | parenthesized `AND` / `OR` / `NOT` |
50
+ | `field.isEmpty()` | `(f.field IS NULL OR f.field = '[null]')` |
51
+ | `file.hasTag("book")` | `EXISTS (SELECT 1 FROM tags WHERE tags.path = f.path AND (tag = 'book' OR tag LIKE 'book/%'))` |
52
+ | `file.hasLink("Note")` | `EXISTS (SELECT 1 FROM links WHERE src = f.path AND dst = 'Note.md')` |
53
+ | `list.contains(x)` | `EXISTS (SELECT 1 FROM json_each(f.list) WHERE value = x)` |
54
+ | `string.contains(x)` | `instr(f.string, x) > 0` |
55
+ | `list.containsAny(...)` | the `json_each` EXISTS with `value IN (...)` |
56
+ | `/regex/.matches(x)` | no SQLite regex; `LIKE`/`GLOB` cover anchored and wildcard shapes |
57
+
58
+ A field no note in the tree declares has no column at all, so a filter naming it errors with
59
+ `no such column` instead of treating every row as empty. Obsidian's evaluator returns empty
60
+ for unknown properties; SQL does not. Dropping the clause states the same thing the error
61
+ did, and `SELECT name FROM pragma_table_info('frontmatter')` lists what exists.
62
+
63
+ `isEmpty()`'s second arm exists because a list key written with no items (`tags:` above a bare
64
+ `-`) stores as the JSON text `[null]`: present, not NULL, holding nothing. Obsidian's
65
+ `isEmpty()` is true for it; `IS NULL` alone is not.
66
+
67
+ `contains(link("Movies"))` compares against a link value. In frontmatter, a list of links
68
+ holds the written text, so the `json_each` comparison value is the literal `[[Movies]]`.
69
+ `hasLink` compares resolved paths: `links.dst` is the resolved target (`NULL` for dead
70
+ links), so the comparison value is the target's path, not its display name.
71
+
72
+ sense's own `has(field, x)` is looser than both `contains` variants: exact membership on JSON
73
+ arrays but substring on strings, so `has(f.status, 'active')` also matches `inactive`. It
74
+ reads shorter when the field is known to be a list; the `json_each` form is the exact
75
+ translation.
76
+
77
+ ## Formulas
78
+
79
+ Formulas are SELECT expressions. The Bases functions map onto SQLite's:
80
+
81
+ | Bases | sense |
82
+ |---|---|
83
+ | `if(c, a, b)` | `iif(c, a, b)` or `CASE WHEN` |
84
+ | `now()` / `today()` | `datetime('now')` / `date('now')` |
85
+ | `date(x)` | `datetime(x)` |
86
+ | `(date1 - date2).days` | `julianday(date1) - julianday(date2)` |
87
+ | `(now() - acquired).months` | `(julianday('now') - julianday(f.acquired)) / 30.44` |
88
+ | `x.round(n)` / `x.toFixed(n)` | `round(x, n)` / `printf('%.2f', x)` |
89
+ | `d.format("YYYY-MM-DD")` | `strftime('%Y-%m-%d', d)` |
90
+ | `x.toString()` | `CAST(x AS TEXT)` |
91
+ | `list.length` | `json_array_length(f.list)` on a JSON column, a COUNT subquery on a table |
92
+ | `list(a).filter(list(b).containsAny(value)).unique()` | an EXISTS-joined subquery; worked example in EXAMPLES.md |
93
+
94
+ Bases durations are typed; SQL date arithmetic is julianday day-fractions. A formula chaining
95
+ duration fields (`.days.round()`) flattens to arithmetic on the julianday difference.
96
+
97
+ ## Views
98
+
99
+ - `sort:` (multi-key, each with direction) -> `ORDER BY a DESC, b ASC`. `limit:` -> `LIMIT`.
100
+ - `groupBy` does not collapse rows -- Obsidian shows every row bucketed under headers with
101
+ per-group summaries. The SQL producing the same rows and numbers is ordering plus window
102
+ functions, not GROUP BY:
103
+
104
+ ```sql
105
+ SELECT f.path, f.status, f.days,
106
+ AVG(f.days) OVER (PARTITION BY f.status) AS group_avg,
107
+ COUNT(*) OVER (PARTITION BY f.status) AS group_n
108
+ FROM frontmatter f WHERE f.days IS NOT NULL
109
+ ORDER BY f.status, f.days DESC
110
+ ```
111
+
112
+ A collapsed one-row-per-group report is plain `GROUP BY` -- that is a different result than
113
+ the Bases view shows.
114
+ - View `summaries` (Sum, Average, Median via ordering, Unique, Filled, Checked) are the
115
+ matching aggregates, windowed as above to keep the rows, or a separate aggregate query.
116
+
117
+ ## `this`
118
+
119
+ `this` is the note the base is evaluated against: the embedding note, or Obsidian's active
120
+ pane. sense has no pane, so the caller supplies the path as a bound parameter -- `sense sql
121
+ "..." <path>`, or a saved query run as `sense <name> <path>`. A CTE keeps it single-bind:
122
+
123
+ ```sql
124
+ WITH me AS (SELECT ? AS p)
125
+ ```
126
+
127
+ and every `this.file.*` expression joins `me`. The full Related.base translation in
128
+ EXAMPLES.md is the worked case: link overlap, mutual-link filters, and the shared-target list
129
+ via `GROUP_CONCAT`, all from one bound path.
130
+
131
+ ## Not translatable, and why it costs nothing
132
+
133
+ - `columnSize`, card/table/list/map chrome: pixel layout over the same rows.
134
+ - Obsidian choosing `this` from the active pane: there is no pane; the path parameter is the
135
+ resolution.
136
+ - Live re-evaluation as files change: every sense query reconciles against the filesystem
137
+ first, so the freshness is already there; nothing re-renders on its own.
@@ -38,7 +38,7 @@ A preset is a named, self-contained bundle of settings. `default` (required) is
38
38
 
39
39
  These belong to the tree's owner. sense works with any of them and reads no instruction files of its own; each choice only changes what queries can do.
40
40
 
41
- - **Frontmatter fields.** Columns are discovered per tree: whatever keys notes declare become queryable. Consistent fields across notes make SQL filters and saved queries possible (`WHERE status = 'active'`). SQLite's compiled column limit (2,000; sqlite.org/limits.html) bounds distinct keys per tree. The crawl stops with an error naming the count and the levers. Reserved keys (dropped with a warning): `path`, `_mtime`, `_size`, `_rank`, `content`, `links`, `sections`. Values keep their YAML type: strings TEXT, whole numbers and booleans INTEGER (`true` is 1), fractions REAL, lists and maps JSON text; `map` prints the observed type per field.
41
+ - **Frontmatter fields.** Columns are discovered per tree: whatever keys notes declare become queryable. Consistent fields across notes make SQL filters and saved queries possible (`WHERE status = 'active'`). SQLite's compiled column limit (2,000; sqlite.org/limits.html) bounds distinct keys per tree. The crawl stops with an error naming the count and the levers. Reserved keys (dropped with a warning): `path`, `_mtime`, `_ctime`, `_size`, `_rank`, `content`, `links`, `sections`. Values keep their YAML type: strings TEXT, whole numbers and booleans INTEGER (`true` is 1), fractions REAL, lists and maps JSON text; `map` prints the observed type per field.
42
42
  - **Presets are path-shaped; frontmatter is state-shaped.** A preset's coverage must be computable from the path alone (it decides indexing, baked into the cache). Volatile state (`status`, `project`, dates) lives in frontmatter and filters at query time (`where`, `has()`, `datetime()`). A state worth different *indexing* (retired memory, superseded sources) is a state worth moving the file: the archive-folder pattern in EXAMPLES.md.
43
43
  - **What a note omits is also a filter.** A layer that deliberately carries none of the fields the saved views filter on is excluded from all of them without any view naming the layer. Sparse fields cut both ways: less of the tree filters when you want breadth, and exactly this separation when layers differ in authority.
44
44
  - **Dates.** `datetime()` comparisons work for dates written as ISO 8601, the only format it parses. A tree that mixes date formats can store them, but can't compare them in SQL.
@@ -1,58 +0,0 @@
1
- import type { DatabaseSync } from 'node:sqlite';
2
- import type { FeatureName, ResolvedConfig, SearchOverrides } from './config.js';
3
- import type { Row } from './output.js';
4
- export interface SearchOptions {
5
- k?: number;
6
- where?: string;
7
- preset?: string;
8
- include?: string[];
9
- exclude?: string[];
10
- noExclude?: boolean;
11
- }
12
- export declare function search(db: DatabaseSync, cfg: ResolvedConfig, terms: string, opts?: SearchOptions): Promise<Row[]>;
13
- export declare function scopedPaths(db: DatabaseSync, cfg: ResolvedConfig, overrides: SearchOverrides): Set<string>;
14
- export interface PresetCoverage {
15
- name: string;
16
- files: number;
17
- embedded: number;
18
- semantic: boolean;
19
- }
20
- export declare function presetCoverage(db: DatabaseSync, cfg: ResolvedConfig): PresetCoverage[];
21
- export interface TreeMap {
22
- docs: {
23
- count: number;
24
- bytes: number;
25
- };
26
- fields: Row[];
27
- fieldsTotal: number;
28
- features: {
29
- on: FeatureName[];
30
- off: FeatureName[];
31
- };
32
- presets: PresetCoverage[];
33
- hubs: Row[];
34
- recent: Row[];
35
- recentCaveat: string | null;
36
- }
37
- export declare function mapTree(db: DatabaseSync, cfg: ResolvedConfig, overrides?: SearchOverrides): TreeMap;
38
- export declare function resolveNote(paths: string[], arg: string): string;
39
- export interface Peek {
40
- path: string;
41
- tokens: number;
42
- frontmatter: Row;
43
- parseError: string | null;
44
- sections: Row[];
45
- outbound: string[];
46
- backlinks: string[];
47
- unresolved: string[];
48
- sectionsTotal: number;
49
- outboundTotal: number;
50
- backlinksTotal: number;
51
- unresolvedTotal: number;
52
- off: FeatureName[];
53
- }
54
- export declare function peek(db: DatabaseSync, cfg: ResolvedConfig, pathArg: string, overrides?: SearchOverrides): Peek;
55
- export declare function relatedNotes(db: DatabaseSync, cfg: ResolvedConfig, pathArg: string, overrides: SearchOverrides, k: number): Promise<Array<{
56
- path: string;
57
- similarity: number;
58
- }>>;
@@ -1,58 +0,0 @@
1
- import type { DatabaseSync } from 'node:sqlite';
2
- import type { FeatureName, ResolvedConfig, SearchOverrides } from './config.js';
3
- import type { Row } from './output.js';
4
- export interface SearchOptions {
5
- k?: number;
6
- where?: string;
7
- preset?: string;
8
- include?: string[];
9
- exclude?: string[];
10
- noExclude?: boolean;
11
- }
12
- export declare function search(db: DatabaseSync, cfg: ResolvedConfig, terms: string, opts?: SearchOptions): Promise<Row[]>;
13
- export declare function scopedPaths(db: DatabaseSync, cfg: ResolvedConfig, overrides: SearchOverrides): Set<string>;
14
- export interface PresetCoverage {
15
- name: string;
16
- files: number;
17
- embedded: number;
18
- semantic: boolean;
19
- }
20
- export declare function presetCoverage(db: DatabaseSync, cfg: ResolvedConfig): PresetCoverage[];
21
- export interface TreeMap {
22
- docs: {
23
- count: number;
24
- bytes: number;
25
- };
26
- fields: Row[];
27
- fieldsTotal: number;
28
- features: {
29
- on: FeatureName[];
30
- off: FeatureName[];
31
- };
32
- presets: PresetCoverage[];
33
- hubs: Row[];
34
- recent: Row[];
35
- recentCaveat: string | null;
36
- }
37
- export declare function mapTree(db: DatabaseSync, cfg: ResolvedConfig, overrides?: SearchOverrides): TreeMap;
38
- export declare function resolveNote(paths: string[], arg: string): string;
39
- export interface Peek {
40
- path: string;
41
- tokens: number;
42
- frontmatter: Row;
43
- parseError: string | null;
44
- sections: Row[];
45
- outbound: string[];
46
- backlinks: string[];
47
- unresolved: string[];
48
- sectionsTotal: number;
49
- outboundTotal: number;
50
- backlinksTotal: number;
51
- unresolvedTotal: number;
52
- off: FeatureName[];
53
- }
54
- export declare function peek(db: DatabaseSync, cfg: ResolvedConfig, pathArg: string, overrides?: SearchOverrides): Peek;
55
- export declare function relatedNotes(db: DatabaseSync, cfg: ResolvedConfig, pathArg: string, overrides: SearchOverrides, k: number): Promise<Array<{
56
- path: string;
57
- similarity: number;
58
- }>>;
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/commands.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { join, matchesGlob } from 'node:path';\nimport posix from 'node:path/posix';\nimport type { DatabaseSync } from 'node:sqlite';\nimport type { FeatureName, ResolvedConfig, SearchOverrides } from './config.ts';\nimport { anyPresetEmbeds, contentTokenize, embedEnabled, featureEnabled, featureStates, presetNames, presetSemanticEnabled, resolveSearch } from './config.ts';\nimport { SenseError } from './errors.ts';\nimport { embedPending, hasEmbedding, modelPresent, semanticCandidates, similarNotes } from './features/embed.ts';\nimport { linkEdges } from './features/index.ts';\nimport { personalizedRank } from './graph.ts';\nimport type { Row } from './output.ts';\nimport { searchError } from './search-error.ts';\nimport { segmentMatch } from './segment.ts';\n\n// The three commands: mapTree (orient), search (locate), peek (structure).\n// Each returns data; cli.ts renders. All of them degrade when a feature is off.\n\n// Mirrors the main columns onto the sidecars, so a title match found through title_seg ranks\n// like a title match found through title, not like a body match.\nconst WEIGHTED_BM25 = 'bm25(content, 10.0, 5.0, 1.0, 0, 10.0, 5.0, 1.0)';\nconst RRF_K = 60;\n\n// snippet() re-tokenizes each candidate doc, superlinearly: ~10s for one 1MB doc\n// (BENCHMARKING.md). Past this bound, rows get the linear JS excerpt instead.\nconst SNIPPET_BOUND = 16_384;\nconst EXCERPT_WINDOW = 160;\n\n// Bare terms from an FTS5 query string: strips operators/quoting so the oversized-doc excerpt\n// scan matches the same words the query matched on, not FTS5 syntax.\nfunction extractBareTerms(query: string): string[] {\n const cleaned = query\n .replace(/\"/g, ' ')\n .replace(/[()*]/g, ' ')\n .replace(/\\b(AND|OR|NOT|NEAR)\\b(\\/\\d+)?/gi, ' ');\n return cleaned\n .split(/\\s+/)\n .map((tok) => tok.replace(/^[A-Za-z_]\\w*:/, '')) // column filter, e.g. title:term\n .map((tok) => tok.toLowerCase().trim())\n .filter((tok) => tok.length > 0);\n}\n\nfunction findOccurrences(haystackLower: string, terms: string[]): Array<{ start: number; end: number; term: string }> {\n const occ: Array<{ start: number; end: number; term: string }> = [];\n for (const term of terms) {\n let idx = 0;\n for (;;) {\n const found = haystackLower.indexOf(term, idx);\n if (found === -1) break;\n occ.push({ start: found, end: found + term.length, term });\n idx = found + term.length;\n }\n }\n // Longest span first at equal start, so \"tests\" beats its substring \"test\" and the\n // whole word gets highlighted; the emit loop then absorbs the shorter overlap.\n return occ.sort((a, b) => a.start - b.start || b.end - a.end);\n}\n\n// Slides a window over the sorted occurrences, same semantics as FTS5's own best-window\n// pick: most distinct terms, ties broken by most total hits.\nfunction bestWindowStart(occ: Array<{ start: number; end: number; term: string }>, windowSize: number): number {\n let best = occ[0].start;\n let bestDistinct = 0;\n let bestCount = 0;\n for (let i = 0; i < occ.length; i++) {\n const winEnd = occ[i].start + windowSize;\n const seen = new Set<string>();\n let count = 0;\n for (let j = i; j < occ.length && occ[j].start < winEnd; j++) {\n seen.add(occ[j].term);\n count++;\n }\n if (seen.size > bestDistinct || (seen.size === bestDistinct && count > bestCount)) {\n best = occ[i].start;\n bestDistinct = seen.size;\n bestCount = count;\n }\n }\n return best;\n}\n\n// snippet()-shaped excerpt: matched terms wrapped in «», … at cut edges. Linear in doc\n// length, only run for rows actually returned (<= k), unlike snippet()'s per-row cost.\nfunction computeExcerpt(text: string, terms: string[]): { excerpt: string; offset: number } {\n const occ = findOccurrences(text.toLowerCase(), terms);\n if (occ.length === 0) {\n // This is a raw substring scan, not porter-stemmed: a doc matched only through a\n // stemmed variant (query \"negotiate\" vs doc \"negotiating\") finds no occurrence here.\n // Fall back to the doc's start, unmarked, rather than claim a match that isn't there.\n const end = Math.min(text.length, EXCERPT_WINDOW);\n return { excerpt: `${text.slice(0, end).replace(/\\s+/g, ' ').trim()}${end < text.length ? '…' : ''}`, offset: 0 };\n }\n const start = bestWindowStart(occ, EXCERPT_WINDOW);\n const end = Math.min(text.length, start + EXCERPT_WINDOW);\n let out = '';\n let cursor = start;\n for (const o of occ) {\n if (o.start < start || o.end > end) continue;\n // Occurrences of duplicate or substring-overlapping terms (\"test tests\") can overlap;\n // emitting each would duplicate document text. Keep the first, absorb the rest.\n if (o.start < cursor) continue;\n out += `${text.slice(cursor, o.start)}«${text.slice(o.start, o.end)}»`;\n cursor = o.end;\n }\n out += text.slice(cursor, end);\n const prefix = start > 0 ? '…' : '';\n const suffix = end < text.length ? '…' : '';\n return { excerpt: `${prefix}${out.replace(/\\s+/g, ' ')}${suffix}`, offset: start };\n}\n\nfunction lineNumberAt(text: string, offset: number): number {\n let line = 1;\n for (let i = 0; i < offset; i++) if (text.charCodeAt(i) === 10) line++;\n return line;\n}\n\nfunction lineRangeFor(db: DatabaseSync, path: string, line: number): string | null {\n const row = db.prepare('SELECT start_line, end_line FROM sections WHERE \"path\" = ? AND start_line <= ? AND end_line >= ? ORDER BY start_line DESC LIMIT 1').get(path, line, line) as { start_line: number; end_line: number } | undefined;\n return row ? `L${row.start_line}-${row.end_line}` : null;\n}\n\nexport interface SearchOptions {\n k?: number;\n where?: string; // SQL fragment against frontmatter alias `f`, e.g. \"f.status = 'active'\"\n preset?: string; // named preset; unknown name throws listing declared presets, undefined -> \"default\"\n include?: string[]; // ad hoc scope override (repeatable --include); independent of exclude\n exclude?: string[]; // ad hoc scope override (repeatable --exclude); independent of include\n noExclude?: boolean; // --no-exclude: drop the preset's exclude for this command\n}\n\n// node:path's matchesGlob is experimental (stable behind an unstable-API flag) as of the\n// engines floor (Node >=22.20); scope filtering only ever needs single-pattern matching, so\n// it's used here in JS rather than running a directory walk in the query path.\nfunction inScope(path: string, include: string[], exclude?: string[]): boolean {\n if (!include.some((g) => matchesGlob(path, g))) return false;\n if (exclude?.some((g) => matchesGlob(path, g))) return false;\n return true;\n}\n\nfunction scopeHasEmbeddings(db: DatabaseSync, cfg: ResolvedConfig, scopedPaths: Set<string>): boolean {\n if (!anyPresetEmbeds(cfg)) return false; // the embeddings table doesn't exist at all in this case\n const rows = db.prepare('SELECT DISTINCT \"path\" FROM embeddings').all() as Array<{ path: string }>;\n return rows.some((r) => scopedPaths.has(r.path));\n}\n\n// BM25 + link expansion + vectors, fused by reciprocal rank; `via` names the signal per row.\n// `opts` arrives already resolved (config.ts:resolveSearch).\nexport async function search(db: DatabaseSync, cfg: ResolvedConfig, terms: string, opts: SearchOptions = {}): Promise<Row[]> {\n const effective = resolveSearch(cfg, opts);\n const { k } = effective;\n\n const allPaths = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n const scopePaths = rawScope(db, cfg, opts, allPaths);\n const scopeActive = scopePaths.size < allPaths.length;\n // The set every candidate pool must be filtered to before truncation: scope narrowed by\n // --where, the same composition scopedPaths() gives the other commands. Runs the same where\n // fragment matchSql does, so a bad column gets the same attributed error either way.\n let allowedPaths: Set<string>;\n try {\n allowedPaths = narrowByWhere(db, scopePaths, effective.where);\n } catch (err) {\n throw searchError(err as Error, terms, effective.where);\n }\n const fetch = Math.max(k * 3, 30);\n\n // Asking for vectors without a model is a misconfiguration, not a mode: degrading would make\n // the same search answer differently before and after a download. semantic:false never asks.\n const wantsVectors = effective.semantic && anyPresetEmbeds(cfg);\n if (wantsVectors && !modelPresent(cfg)) {\n throw new SenseError('EMBED_MODEL_MISSING', `preset \"${effective.presetName}\" searches with vectors, but the embedding model is not available; run \\`sense download\\`, or set \"semantic\": false on that preset to search on words and links`);\n }\n const semanticEnabled = wantsVectors && scopeHasEmbeddings(db, cfg, allowedPaths);\n\n // Terms pass to MATCH as written, with one transform: a run of text whose language marks no\n // word boundaries becomes a quoted grapheme phrase (and a title:/summary:/text: qualifier\n // ahead of it retargets its _seg column), matching how it was indexed. Text that already\n // carries boundaries comes through untouched, so this is a no-op for the languages that\n // never needed it. Gated on the same predicate that decided whether the sidecars were\n // populated (contentTokenize(cfg) === undefined), so index and query can't disagree. Invalid\n // syntax still errors rather than being rewritten.\n // --where\n // applies inside the candidate query (a post-filter would drop matches ranked past the pool)\n // and again on the final select, for link-derived rows.\n const scope = effective.where;\n const whereJoin = scope ? `JOIN frontmatter f ON f.\"path\" = content.path` : '';\n const whereCond = scope ? `AND (${scope})` : '';\n // A scope narrower than the whole index must filter the candidate pool before LIMIT, not\n // after -- otherwise scoped notes ranking below the global top-`fetch` never reach the\n // filter. A join against a temp table, not a bound parameter list: real scopes run to\n // thousands of paths, past SQLITE_MAX_VARIABLE_NUMBER on older builds.\n if (scopeActive) materializeScope(db, '_search_scope', scopePaths);\n const scopeCond = scopeActive ? `AND content.path IN (SELECT \"path\" FROM _search_scope)` : '';\n // Docs past SNIPPET_BOUND skip snippet() entirely -- SQLite\n // short-circuits the untaken CASE branch, so it's never invoked on them.\n // Column 2 (text), not -1 (best column): -1 could surface a _seg sidecar as the excerpt,\n // which is machine-spaced and not what the author wrote. A row that matches only in a\n // sidecar gets an unhighlighted text excerpt below instead -- a stated cost.\n const matchSql = `SELECT content.path AS path, CASE WHEN length(content.text) <= ${SNIPPET_BOUND} THEN snippet(content, 2, '«', '»', '…', 10) ELSE NULL END AS hit FROM content ${whereJoin} WHERE content MATCH ? ${whereCond} ${scopeCond} ORDER BY ${WEIGHTED_BM25} LIMIT ${fetch}`;\n const query = contentTokenize(cfg) === undefined ? segmentMatch(terms) : terms;\n let matchRows: Array<{ path: string; hit: string | null }>;\n try {\n matchRows = db.prepare(matchSql).all(query) as Array<{ path: string; hit: string | null }>;\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 // hit === null here means the bound suppressed snippet(), not \"no match\" -- distinguish\n // from via='link' rows (never in matchRows, so absent from this set) below.\n const oversized = new Set(matchRows.filter((r) => r.hit === null).map((r) => r.path));\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 // Gates the label only, not the score: restart mass ranks every seed without an incident\n // edge, but dropping it from the score reweights fusion (FEVER hit@10 0.997 -> 0.907).\n const linked = new Set(edges.flat());\n const seeds = new Map(matchRows.map((r, i) => [r.path, 1 / (i + 1)]));\n const ranked = [...personalizedRank(allPaths, edges, seeds)]\n .filter(([path, score]) => score > 1e-9 && allowedPaths.has(path))\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 (semanticEnabled) {\n const vec = await semanticCandidates(db, cfg, terms, fetch, allowedPaths);\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 _search');\n db.exec('CREATE TEMP TABLE _search (\"path\" TEXT PRIMARY KEY, score REAL, via TEXT, hit TEXT, lines TEXT, similarity REAL)');\n const insert = db.prepare('INSERT INTO _search (\"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 // All three candidate paths (match, link, vector) already filtered to scope+where before\n // reaching _search; this reapplies --where anyway since the join to frontmatter is already\n // needed for the path column.\n const where = scope ? `WHERE (${scope})` : '';\n // lines is always present now: semantic rows carry their chunk's range, oversized-doc\n // lexical rows gain one below, everything else stays null. similarity stays semantic-only.\n const similarityCol = semanticEnabled ? ', _search.similarity' : '';\n const rows = db\n .prepare(\n `SELECT f.\"path\" AS path, content.title, content.summary, _search.hit, _search.via, round(_search.score, 4) AS score, _search.lines${similarityCol}\n FROM _search JOIN frontmatter f ON f.\"path\" = _search.\"path\" JOIN content ON content.path = _search.\"path\"\n ${where} ORDER BY _search.score DESC LIMIT ?`\n )\n .all(k) as Row[];\n\n if (oversized.size > 0) {\n const bareTerms = extractBareTerms(terms);\n for (const row of rows) {\n if (row.hit !== null || !oversized.has(row.path as string)) continue;\n let text: string;\n try {\n text = readFileSync(join(cfg.baseDir, row.path as string), 'utf8');\n } catch {\n continue; // vanished since the match; leave hit/lines null rather than throw\n }\n const { excerpt, offset } = computeExcerpt(text, bareTerms);\n row.hit = excerpt;\n if (row.lines == null) row.lines = featureEnabled(cfg, 'sections') ? lineRangeFor(db, row.path as string, lineNumberAt(text, offset)) : null;\n }\n }\n\n return rows;\n}\n\n// Scope only (no --where): preset_files for a named preset, JS glob matching for an ad hoc\n// include/exclude override. Shared by scopedPaths() and search(), which also needs the\n// pre-where set to size the candidate-pool filter.\nfunction rawScope(db: DatabaseSync, cfg: ResolvedConfig, overrides: SearchOverrides, allPaths?: string[]): Set<string> {\n const effective = resolveSearch(cfg, overrides);\n const { include, exclude } = effective;\n const adHocScope = overrides.include !== undefined || overrides.exclude !== undefined || overrides.noExclude === true;\n if (!adHocScope) return new Set((db.prepare('SELECT \"path\" FROM preset_files WHERE preset = ?').all(effective.presetName) as Array<{ path: string }>).map((r) => r.path));\n const paths = allPaths ?? (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n return new Set(paths.filter((p) => inScope(p, include, exclude)));\n}\n\nfunction narrowByWhere(db: DatabaseSync, paths: Set<string>, where: string | undefined): Set<string> {\n if (!where) return paths;\n const whereRows = db.prepare(`SELECT \"path\" FROM frontmatter f WHERE (${where})`).all() as Array<{ path: string }>;\n const wherePaths = new Set(whereRows.map((r) => r.path));\n return new Set([...paths].filter((p) => wherePaths.has(p)));\n}\n\n// The scope resolver for non-search commands (path, peek, map): same coverage rule search()\n// applies, then narrowed by the resolved `where`.\nexport function scopedPaths(db: DatabaseSync, cfg: ResolvedConfig, overrides: SearchOverrides): Set<string> {\n const effective = resolveSearch(cfg, overrides);\n return narrowByWhere(db, rawScope(db, cfg, overrides), effective.where);\n}\n\nexport interface PresetCoverage {\n name: string;\n files: number;\n embedded: number;\n // Reported so 0 embedded reads as \"this scope declined vectors\" rather than \"not yet built\".\n semantic: boolean;\n}\n\n// Indexing derives from presets, so the derivation stays visible. Read from preset_files, not\n// recomputed from globs, so it reflects the cache rather than the config.\nexport function presetCoverage(db: DatabaseSync, cfg: ResolvedConfig): PresetCoverage[] {\n const embedActive = anyPresetEmbeds(cfg);\n return presetNames(cfg).map((name) => {\n const files = (db.prepare('SELECT COUNT(*) AS n FROM preset_files WHERE preset = ?').get(name) as { n: number }).n;\n const embedded = embedActive ? (db.prepare('SELECT COUNT(*) AS n FROM preset_files pf WHERE pf.preset = ? AND EXISTS (SELECT 1 FROM embeddings e WHERE e.\"path\" = pf.\"path\" AND e.vector IS NOT NULL)').get(name) as { n: number }).n : 0;\n return { name, files, embedded, semantic: presetSemanticEnabled(cfg, name) };\n });\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 presets: PresetCoverage[];\n hubs: Row[];\n recent: Row[];\n recentCaveat: string | null;\n}\n\nconst INTERNAL_COLUMNS = new Set(['path', '_mtime', '_size', '_rank', '_parse_error']);\n\n// A result row is capped at SQLITE_MAX_COLUMN (2000, default); two aggregate expressions\n// per field keeps a chunk's row safely under that regardless of how many fields the tree has.\nconst MAP_COLUMN_CHUNK = 300;\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\n// Materializes a path set into a named temp table (same shape as traverse.ts's allowed_nodes)\n// so a query can join/filter against it cheaply instead of binding a parameter per path.\nfunction materializeScope(db: DatabaseSync, table: string, paths: Set<string>): void {\n db.exec(`DROP TABLE IF EXISTS ${table}`);\n db.exec(`CREATE TEMP TABLE ${table} (\"path\" TEXT PRIMARY KEY)`);\n db.prepare(`INSERT INTO ${table} SELECT DISTINCT value FROM json_each(?1)`).run(JSON.stringify([...paths]));\n}\n\nfunction setupMapScope(db: DatabaseSync, paths: Set<string>): void {\n materializeScope(db, '_map_scope', paths);\n}\n\n// What is this scope: fixed-size output regardless of tree size. Coverage and features stay\n// global -- they describe the tree, not the current question.\nexport function mapTree(db: DatabaseSync, cfg: ResolvedConfig, overrides: SearchOverrides = {}): TreeMap {\n setupMapScope(db, scopedPaths(db, cfg, overrides));\n const scopeWhere = 'WHERE \"path\" IN (SELECT \"path\" FROM _map_scope)';\n const scopeAnd = 'AND f.\"path\" IN (SELECT \"path\" FROM _map_scope)';\n\n const docs = db.prepare(`SELECT COUNT(*) AS count, COALESCE(SUM(\"_size\"), 0) AS bytes FROM frontmatter ${scopeWhere}`).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 // Observed types, not declared: SQLite types per value, so a field can be text in most notes\n // and numeric in a few. One aggregate scan per chunk of columns; FILTER matches COUNT's nulls.\n const allFields: Row[] = [];\n for (const group of chunk(columns, MAP_COLUMN_CHUNK)) {\n const exprs = group.map((name, i) => {\n const quoted = `\"${name.split('\"').join('\"\"')}\"`;\n return `COUNT(${quoted}) AS n${i}, GROUP_CONCAT(DISTINCT typeof(${quoted})) FILTER (WHERE ${quoted} IS NOT NULL) AS t${i}`;\n });\n const result = db.prepare(`SELECT ${exprs.join(', ')} FROM frontmatter ${scopeWhere}`).get() as Record<string, number | string | null>;\n group.forEach((name, i) => allFields.push({ field: name, coverage: result[`n${i}`] as number, type: (result[`t${i}`] as string) ?? '' }));\n }\n allFields.sort((a, b) => (b.coverage as number) - (a.coverage as number));\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 ${scopeAnd} 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 ${scopeWhere} ORDER BY \"_mtime\" DESC LIMIT 5`).all() as Row[];\n\n // A fresh clone/copy stamps files with checkout time, not edit history; second granularity\n // matches the `recent` table above and is coarse enough to catch that without an exact-ms match.\n const topSecond = db.prepare(`SELECT COUNT(*) AS n FROM frontmatter ${scopeWhere} GROUP BY CAST(\"_mtime\" / 1000 AS INTEGER) ORDER BY n DESC LIMIT 1`).get() as { n: number } | undefined;\n const recentCaveat = topSecond && docs.count > 1 && topSecond.n > docs.count / 2 ? `${topSecond.n} of ${docs.count} files share one modified second, so recency likely reflects a checkout or copy, not edit history` : null;\n\n return { docs, fields, fieldsTotal: allFields.length, features: featureStates(cfg), presets: presetCoverage(db, cfg), hubs, recent, recentCaveat };\n}\n\n// Note resolution shared by peek and path: an exact path, or a unique basename (case\n// insensitive, .md stripped).\nexport function resolveNote(paths: string[], arg: string): string {\n const exact = paths.find((p) => p === arg);\n if (exact) return exact;\n const base = posix.basename(arg).replace(/\\.md$/i, '').toLowerCase();\n const matches = paths.filter((p) => posix.basename(p).replace(/\\.md$/i, '').toLowerCase() === base);\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) throw new SenseError('NOTE_AMBIGUOUS', `\"${arg}\" is ambiguous: ${matches.join(', ')}`);\n throw new SenseError('NOTE_NOT_FOUND', `no note matches \"${arg}\"`);\n}\n\nexport interface Peek {\n path: string;\n tokens: number;\n frontmatter: Row;\n // Set when the note's frontmatter was refused, so an empty frontmatter block reads as \"did\n // not parse\" rather than \"has none\". Same reason `_parse_error` sits in the row.\n parseError: string | null;\n sections: Row[];\n outbound: string[];\n backlinks: string[];\n unresolved: string[];\n // Totals before truncation: a hub can have thousands of backlinks (or a note thousands of\n // headings), and peek's whole point is bounded output. Query the sections/links tables\n // directly for the full list.\n sectionsTotal: number;\n outboundTotal: number;\n backlinksTotal: number;\n unresolvedTotal: number;\n // Bounded k-hop expansion beyond the immediate ring already shown by outbound/backlinks\n // (depth starts at 2).\n off: FeatureName[]; // disabled features whose blocks are omitted (not empty)\n}\n\nconst PEEK_LIST_LIMIT = 20;\n\n// peek: 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: ResolvedConfig, pathArg: string, overrides: SearchOverrides = {}): Peek {\n const paths = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n const path = resolveNote(paths, pathArg);\n\n const row = db.prepare('SELECT * FROM frontmatter WHERE \"path\" = ?').get(path) as Row;\n const parseError = (row._parse_error as string | null) ?? null;\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 sectionsTotal = featureEnabled(cfg, 'sections') ? (db.prepare('SELECT COUNT(*) AS n FROM sections WHERE \"path\" = ?').get(path) as { n: number }).n : 0;\n const sections = featureEnabled(cfg, 'sections') ? (db.prepare('SELECT level, heading, start_line, end_line, tokens FROM sections WHERE \"path\" = ? ORDER BY idx LIMIT ?').all(path, PEEK_LIST_LIMIT) as Row[]) : [];\n\n let outbound: string[] = [];\n let backlinks: string[] = [];\n let unresolved: string[] = [];\n let backlinksTotal = 0;\n const _allowed = scopedPaths(db, cfg, overrides);\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_LIST_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 parseError,\n sections,\n outbound: outbound.slice(0, PEEK_LIST_LIMIT),\n backlinks,\n unresolved: unresolved.slice(0, PEEK_LIST_LIMIT),\n sectionsTotal,\n outboundTotal: outbound.length,\n backlinksTotal,\n unresolvedTotal: unresolved.length,\n off: (['sections', 'links'] as FeatureName[]).filter((name) => !featureEnabled(cfg, name)),\n };\n}\n\n// Notes most similar by cosine, excluding self and everything already linked either way.\n// Its own command, not a peek section: a full embeddings scan is ~480ms at 26k notes.\nexport async function relatedNotes(db: DatabaseSync, cfg: ResolvedConfig, pathArg: string, overrides: SearchOverrides, k: number): Promise<Array<{ path: string; similarity: number }>> {\n const paths = (db.prepare('SELECT \"path\" FROM frontmatter').all() as Array<{ path: string }>).map((r) => r.path);\n const path = resolveNote(paths, pathArg);\n\n const outbound = (db.prepare('SELECT DISTINCT dst FROM links WHERE src = ? AND dst IS NOT NULL').all(path) as Array<{ dst: string }>).map((r) => r.dst);\n const backlinks = (db.prepare('SELECT DISTINCT src FROM links WHERE dst = ?').all(path) as Array<{ src: string }>).map((r) => r.src);\n const exclude = new Set([path, ...outbound, ...backlinks]);\n\n // Vectors are the only signal `related` has, so every way of not having them is an error\n // naming the cause. An empty table then means one thing: nothing near in meaning that this\n // note does not already link to, which is a real answer.\n const effective = resolveSearch(cfg, overrides);\n if (!embedEnabled(cfg)) {\n throw new SenseError('EMBED_DISABLED', 'related ranks notes by meaning, and this tree has no embedding model; add an \"embed\" block naming one to sense.config.json, then run `sense download` (search works without it, on words and links)');\n }\n // search gates on the same flag (see wantsVectors above); reading it here too keeps\n // `semantic: false` meaning one thing. Without this, an overlapping semantic-on preset's\n // vectors would answer for a scope that declined them.\n if (!effective.semantic) {\n throw new SenseError('PRESET_NOT_SEMANTIC', `preset \"${effective.presetName}\" sets \"semantic\": false, so this scope has no vectors and related has no other signal; search it instead (words and links), or set semantic back on for that preset`);\n }\n if (!modelPresent(cfg)) {\n throw new SenseError('EMBED_MODEL_MISSING', 'related ranks notes by meaning, so it needs the embedding model, which is not downloaded; run `sense download` (search still works without it, on words and links)');\n }\n const allowed = scopedPaths(db, cfg, overrides);\n // Top up pending rows before the seed check, or a fresh index reports every note as\n // having no indexed text until some search has run.\n await embedPending(db, cfg, cfg.baseDir);\n if (!hasEmbedding(db, path)) {\n throw new SenseError('NOTE_NOT_EMBEDDED', `${path} has no indexed text to compare -- a note that is frontmatter only, or empty, has nothing to rank by meaning`);\n }\n if (!scopeHasEmbeddings(db, cfg, allowed)) return [];\n return similarNotes(db, cfg, path, { exclude, allowed, k });\n}\n"],"names":["mapTree","peek","presetCoverage","relatedNotes","resolveNote","scopedPaths","search","WEIGHTED_BM25","RRF_K","SNIPPET_BOUND","EXCERPT_WINDOW","extractBareTerms","query","cleaned","replace","split","map","tok","toLowerCase","trim","filter","length","findOccurrences","haystackLower","terms","occ","term","idx","found","indexOf","push","start","end","sort","a","b","bestWindowStart","windowSize","best","bestDistinct","bestCount","i","winEnd","seen","Set","count","j","add","size","computeExcerpt","text","Math","min","excerpt","slice","offset","out","cursor","o","prefix","suffix","lineNumberAt","line","charCodeAt","lineRangeFor","db","path","row","prepare","get","start_line","end_line","inScope","include","exclude","some","g","matchesGlob","scopeHasEmbeddings","cfg","anyPresetEmbeds","rows","all","r","has","opts","hits","chunkLines","chunkSimilarity","effective","k","allPaths","scopePaths","scopeActive","allowedPaths","fetch","wantsVectors","semanticEnabled","scope","whereJoin","whereCond","scopeCond","matchSql","matchRows","oversized","candidates","edges","linked","seeds","ranked","vec","insert","c","where","similarityCol","bareTerms","resolveSearch","rawScope","narrowByWhere","err","searchError","max","semantic","modelPresent","SenseError","presetName","materializeScope","contentTokenize","undefined","segmentMatch","Map","hit","forEach","set","score","via","featureEnabled","linkEdges","flat","personalizedRank","existing","semanticCandidates","lines","similarity","exec","run","readFileSync","join","baseDir","overrides","adHocScope","noExclude","paths","p","whereRows","wherePaths","embedActive","presetNames","name","files","n","embedded","presetSemanticEnabled","INTERNAL_COLUMNS","MAP_COLUMN_CHUNK","chunk","items","table","JSON","stringify","setupMapScope","scopeWhere","scopeAnd","docs","columns","allFields","group","exprs","quoted","result","field","coverage","type","fields","hubs","recent","topSecond","recentCaveat","fieldsTotal","features","featureStates","presets","arg","exact","find","base","posix","basename","matches","PEEK_LIST_LIMIT","pathArg","parseError","_parse_error","frontmatter","Object","entries","key","value","sectionsTotal","sections","outbound","backlinks","unresolved","backlinksTotal","_allowed","l","dst","target","src","tokens","ceil","_size","outboundTotal","unresolvedTotal","off","allowed","embedEnabled","embedPending","hasEmbedding","similarNotes"],"mappings":";;;;;;;;;;;QAuXgBA;eAAAA;;QAyEAC;eAAAA;;QAvHAC;eAAAA;;QAqKMC;eAAAA;;QAnFNC;eAAAA;;QAjGAC;eAAAA;;QAxKMC;eAAAA;;;sBAlJO;wBACK;4DAChB;wBAG+H;wBACtH;uBACgE;uBACjE;uBACO;6BAEL;yBACC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE7B,2EAA2E;AAC3E,gFAAgF;AAEhF,6FAA6F;AAC7F,iEAAiE;AACjE,IAAMC,gBAAgB;AACtB,IAAMC,QAAQ;AAEd,iFAAiF;AACjF,8EAA8E;AAC9E,IAAMC,gBAAgB;AACtB,IAAMC,iBAAiB;AAEvB,8FAA8F;AAC9F,qEAAqE;AACrE,SAASC,iBAAiBC,KAAa;IACrC,IAAMC,UAAUD,MACbE,OAAO,CAAC,MAAM,KACdA,OAAO,CAAC,UAAU,KAClBA,OAAO,CAAC,mCAAmC;IAC9C,OAAOD,QACJE,KAAK,CAAC,OACNC,GAAG,CAAC,SAACC;eAAQA,IAAIH,OAAO,CAAC,kBAAkB;OAAK,iCAAiC;KACjFE,GAAG,CAAC,SAACC;eAAQA,IAAIC,WAAW,GAAGC,IAAI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