sensemaking 0.28.0 → 0.28.2

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 (87) hide show
  1. package/README.md +2 -2
  2. package/dist/cjs/chunk/group.js +1 -1
  3. package/dist/cjs/cli/path.js +1 -1
  4. package/dist/cjs/cli/peek.js +1 -1
  5. package/dist/cjs/cli/related.js +1 -1
  6. package/dist/cjs/cli/search.js +1 -1
  7. package/dist/cjs/cli/shared.js +1 -1
  8. package/dist/cjs/cli/sql.js +1 -1
  9. package/dist/cjs/cli/status.js +1 -1
  10. package/dist/cjs/cli.js +1 -1
  11. package/dist/cjs/commands/map.js +1 -1
  12. package/dist/cjs/commands/peek.js +1 -1
  13. package/dist/cjs/commands/related.js +1 -1
  14. package/dist/cjs/commands/scope.js +1 -1
  15. package/dist/cjs/commands/search.js +1 -1
  16. package/dist/cjs/commands/signals.js +1 -1
  17. package/dist/cjs/config/access.js +1 -1
  18. package/dist/cjs/config/load.js +1 -1
  19. package/dist/cjs/config/validate.js +1 -1
  20. package/dist/cjs/embed/identity.js +1 -1
  21. package/dist/cjs/embed/langfit.js +1 -1
  22. package/dist/cjs/embed/openai.js +1 -1
  23. package/dist/cjs/embed/query.js +1 -1
  24. package/dist/cjs/embed/static.js +1 -1
  25. package/dist/cjs/embed/store.d.cts +1 -1
  26. package/dist/cjs/embed/store.d.ts +1 -1
  27. package/dist/cjs/embed/store.js +154 -31
  28. package/dist/cjs/embed/store.js.map +1 -1
  29. package/dist/cjs/features/links.js +1 -1
  30. package/dist/cjs/features/rank.js +1 -1
  31. package/dist/cjs/features/tags.js +1 -1
  32. package/dist/cjs/graph/graph.js +1 -1
  33. package/dist/cjs/graph/traverse.js +1 -1
  34. package/dist/cjs/output/column-hint.js +1 -1
  35. package/dist/cjs/output/output.js +1 -1
  36. package/dist/cjs/scan/frontmatter.js +1 -1
  37. package/dist/cjs/scan/list.js +1 -1
  38. package/dist/cjs/scan/pool.js +1 -1
  39. package/dist/cjs/scan/reparse.js +1 -1
  40. package/dist/cjs/store/batch.js +1 -1
  41. package/dist/cjs/store/builder.js +1 -1
  42. package/dist/cjs/store/duckdb/batch.js +1 -1
  43. package/dist/cjs/store/duckdb/connection.js +1 -1
  44. package/dist/cjs/store/duckdb/fieldStats.js +1 -1
  45. package/dist/cjs/store/duckdb/lexical.js +1 -1
  46. package/dist/cjs/store/duckdb/reconcile.js +1 -1
  47. package/dist/cjs/store/duckdb/store.js +1 -1
  48. package/dist/cjs/store/duckdb/vectors.js +1 -1
  49. package/dist/cjs/store/embed-scope.js +1 -1
  50. package/dist/cjs/store/feature-scope.js +1 -1
  51. package/dist/cjs/store/native.js +1 -1
  52. package/dist/cjs/store/open.js +1 -1
  53. package/dist/cjs/store/preset-scope.js +1 -1
  54. package/dist/cjs/store/reconcile.js +1 -1
  55. package/dist/cjs/store/signature.js +1 -1
  56. package/dist/cjs/store/sqlite/connection.js +1 -1
  57. package/dist/cjs/store/sqlite/fieldStats.js +1 -1
  58. package/dist/cjs/store/sqlite/store.js +1 -1
  59. package/dist/cjs/store/sqlite/vectors.js +1 -1
  60. package/dist/cjs/store/stages.js +1 -1
  61. package/dist/cjs/store/turso/connection.js +1 -1
  62. package/dist/cjs/store/turso/fieldStats.js +1 -1
  63. package/dist/cjs/store/turso/lexical.js +1 -1
  64. package/dist/cjs/store/turso/open.js +1 -1
  65. package/dist/cjs/store/turso/store.js +1 -1
  66. package/dist/cjs/store/turso/vectors.js +1 -1
  67. package/dist/esm/embed/store.d.ts +1 -1
  68. package/dist/esm/embed/store.js +77 -8
  69. package/dist/esm/embed/store.js.map +1 -1
  70. package/package.json +3 -3
  71. package/skills/sense/EXAMPLES.md +0 -99
  72. package/skills/sense/SKILL.md +0 -145
  73. package/skills/sense/references/search.md +0 -63
  74. package/skills/sense/references/sql.md +0 -120
  75. package/skills/sense/references/stores/duckdb.md +0 -35
  76. package/skills/sense/references/stores/sqlite.md +0 -66
  77. package/skills/sense/references/stores/turso.md +0 -36
  78. package/skills/sense/references/terminology.md +0 -32
  79. package/skills/sense-bases/EXAMPLES.md +0 -103
  80. package/skills/sense-bases/SKILL.md +0 -147
  81. package/skills/sense-setup/EXAMPLES.md +0 -129
  82. package/skills/sense-setup/SKILL.md +0 -112
  83. package/skills/sense-setup/references/embeddings.md +0 -51
  84. package/skills/sense-setup/references/store-benchmarks.md +0 -16
  85. package/skills/sense-setup/references/stores/duckdb.md +0 -28
  86. package/skills/sense-setup/references/stores/sqlite.md +0 -21
  87. package/skills/sense-setup/references/stores/turso.md +0 -25
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { existsSync, mkdirSync } from 'node:fs';
2
3
  import { join } from 'node:path';
3
4
  import { embedConfig } from '../config/index.js';
@@ -6,6 +7,8 @@ import { writeFileAtomic } from '../lib/atomic-write.js';
6
7
  import { fetchWithRetry, HTTP_ATTEMPT_TIMEOUT_MS, MODEL_FILE_ATTEMPT_TIMEOUT_MS } from './http.js';
7
8
  import { DEFAULT_MODELS_ROOT, hasModelFiles, isDownloadable, languagesPath, MODEL_FILES, readRef, snapshotDir, writeLanguages, writeRef } from './identity.js';
8
9
  import { isKnownLanguageTag, MEASURED_MODEL_LANGUAGES } from './languages.js';
10
+ // The Hub base for every request here; downloadModelRevision takes it as a parameter so a test can point it at a local server.
11
+ const HF_HUB = 'https://huggingface.co';
9
12
  // identity.ts holds paths and cache identity, no network; store.ts holds the network fetches
10
13
  // (downloads, sha resolution, language metadata), re-exported here for its network surface.
11
14
  export { hasModelFiles, isDownloadable, MODEL_FILENAMES, MODEL_FILES, modelDir, readLanguages, refsMainPath, snapshotDir, writeLanguages, writeRef } from './identity.js';
@@ -26,7 +29,7 @@ export function localModelMissing(e) {
26
29
  async function resolveSha(model, root = DEFAULT_MODELS_ROOT) {
27
30
  const existing = readRef(model, root);
28
31
  if (existing) return existing;
29
- const url = `https://huggingface.co/${model}/resolve/main/model.safetensors`;
32
+ const url = `${HF_HUB}/${model}/resolve/main/model.safetensors`;
30
33
  // redirect: manual -- the header rides the Hub's own response; following the LFS/CDN
31
34
  // redirect would read the CDN's headers instead, which do not carry it.
32
35
  const res = await fetchWithRetry(url, {
@@ -80,7 +83,7 @@ async function ensureLanguages(model, root = DEFAULT_MODELS_ROOT) {
80
83
  }
81
84
  let res;
82
85
  try {
83
- res = await fetchWithRetry(`https://huggingface.co/api/models/${model}`, {}, {
86
+ res = await fetchWithRetry(`${HF_HUB}/api/models/${model}`, {}, {
84
87
  attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS
85
88
  });
86
89
  } catch {
@@ -102,24 +105,90 @@ async function ensureLanguages(model, root = DEFAULT_MODELS_ROOT) {
102
105
  }
103
106
  writeLanguages(model, (_languagesFromCard = languagesFromCard(info)) !== null && _languagesFromCard !== void 0 ? _languagesFromCard : [], root);
104
107
  }
105
- async function fetchToFile(url, dest) {
108
+ function isHfTreeEntry(value) {
109
+ if (value === null || typeof value !== 'object') return false;
110
+ if (!('path' in value) || typeof value.path !== 'string') return false;
111
+ if (!('oid' in value) || typeof value.oid !== 'string') return false;
112
+ if (!('size' in value) || typeof value.size !== 'number') return false;
113
+ if (!('lfs' in value) || value.lfs === undefined) return true;
114
+ if (value.lfs === null || typeof value.lfs !== 'object') return false;
115
+ return 'oid' in value.lfs && typeof value.lfs.oid === 'string' && 'size' in value.lfs && typeof value.lfs.size === 'number';
116
+ }
117
+ function isHfTree(value) {
118
+ return Array.isArray(value) && value.every(isHfTreeEntry);
119
+ }
120
+ function unverifiable(model, sha, detail) {
121
+ return new SenseError('EMBED_MODEL', `could not get the Hub's published hashes for ${model}@${sha.slice(0, 8)}: ${detail}; no model file was written. Retry \`sense download\`; if it repeats, something between this machine and Hugging Face is changing the response`);
122
+ }
123
+ async function fetchExpected(model, sha, files, hub) {
124
+ const url = `${hub}/api/models/${model}/tree/${sha}`;
125
+ let res;
126
+ try {
127
+ res = await fetchWithRetry(url, {}, {
128
+ attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS
129
+ });
130
+ } catch (err) {
131
+ throw unverifiable(model, sha, `${url} failed (${err.message})`);
132
+ }
133
+ if (res.status !== 200) throw unverifiable(model, sha, `${url} -> HTTP ${res.status}`);
134
+ let tree;
135
+ try {
136
+ tree = JSON.parse(new TextDecoder().decode(res.body));
137
+ } catch {
138
+ throw unverifiable(model, sha, `${url} did not return JSON`);
139
+ }
140
+ if (!isHfTree(tree)) throw unverifiable(model, sha, `${url} returned an unrecognized tree`);
141
+ const expected = new Map();
142
+ for (const file of files){
143
+ const entry = tree.find((e)=>e.path === file);
144
+ if (!entry) throw unverifiable(model, sha, `the tree has no entry for ${file}`);
145
+ expected.set(file, entry.lfs ? {
146
+ kind: 'sha256',
147
+ hash: entry.lfs.oid,
148
+ size: entry.lfs.size
149
+ } : {
150
+ kind: 'git-sha1',
151
+ hash: entry.oid,
152
+ size: entry.size
153
+ });
154
+ }
155
+ return expected;
156
+ }
157
+ // git blob id: sha1 over "blob <size>\0" then the bytes.
158
+ function digest(kind, bytes) {
159
+ if (kind === 'sha256') return createHash('sha256').update(bytes).digest('hex');
160
+ return createHash('sha1').update(`blob ${bytes.byteLength}\0`).update(bytes).digest('hex');
161
+ }
162
+ async function fetchToFile(url, dest, expected, label) {
106
163
  const res = await fetchWithRetry(url, {}, {
107
164
  attemptTimeoutMs: MODEL_FILE_ATTEMPT_TIMEOUT_MS
108
165
  });
109
166
  if (!res.ok) throw new SenseError('EMBED_MODEL', `${res.url} -> HTTP ${res.status}`);
110
- writeFileAtomic(dest, Buffer.from(res.body));
167
+ const bytes = Buffer.from(res.body);
168
+ const mismatch = (actual)=>new SenseError('EMBED_MODEL', `${label} does not match the Hub's published ${expected.kind}: expected ${expected.hash.slice(0, 12)} (${expected.size} bytes), got ${actual}; ${label} was not written. Retry \`sense download\`; if it repeats, something between this machine and Hugging Face is changing the file`);
169
+ if (bytes.byteLength !== expected.size) throw mismatch(`${bytes.byteLength} bytes`);
170
+ const actual = digest(expected.kind, bytes);
171
+ if (actual !== expected.hash) throw mismatch(`${actual.slice(0, 12)} (${bytes.byteLength} bytes)`);
172
+ writeFileAtomic(dest, bytes);
111
173
  }
112
174
  // Fetches an already-known sha straight into its snapshot dir, without touching refs/main --
113
175
  // for downloadModel below, and for callers pinning an exact revision (the parity suite).
114
- export async function downloadModelRevision(model, sha, onFile, root = DEFAULT_MODELS_ROOT) {
176
+ // Each fetched file is verified against the Hub's published hash before it is written.
177
+ export async function downloadModelRevision(model, sha, onFile, root = DEFAULT_MODELS_ROOT, hub = HF_HUB) {
115
178
  const dir = snapshotDir(model, sha, root);
116
179
  mkdirSync(dir, {
117
180
  recursive: true
118
181
  });
119
- for (const file of MODEL_FILES){
120
- if (existsSync(join(dir, file))) continue;
182
+ // Files already on disk are not re-hashed (0.3 s per open), including ones written before
183
+ // verification existed; removing the snapshot folder re-downloads and verifies them.
184
+ const missing = MODEL_FILES.filter((file)=>!existsSync(join(dir, file)));
185
+ if (missing.length === 0) return dir;
186
+ const expected = await fetchExpected(model, sha, missing, hub);
187
+ for (const file of missing){
188
+ const want = expected.get(file);
189
+ if (!want) throw unverifiable(model, sha, `no expected value for ${file}`);
121
190
  onFile === null || onFile === void 0 ? void 0 : onFile(file, dir);
122
- await fetchToFile(`https://huggingface.co/${model}/resolve/${sha}/${file}`, join(dir, file));
191
+ await fetchToFile(`${hub}/${model}/resolve/${sha}/${file}`, join(dir, file), want, `${model}@${sha.slice(0, 8)}/${file}`);
123
192
  }
124
193
  return dir;
125
194
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/sensemaking/src/embed/store.ts"],"sourcesContent":["import { existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Config } from '../config/index.ts';\nimport { embedConfig } from '../config/index.ts';\nimport { SenseError } from '../errors.ts';\nimport { writeFileAtomic } from '../lib/atomic-write.ts';\nimport { type BufferedResponse, fetchWithRetry, HTTP_ATTEMPT_TIMEOUT_MS, MODEL_FILE_ATTEMPT_TIMEOUT_MS } from './http.ts';\nimport { DEFAULT_MODELS_ROOT, hasModelFiles, isDownloadable, languagesPath, MODEL_FILES, readRef, snapshotDir, writeLanguages, writeRef } from './identity.ts';\nimport { isKnownLanguageTag, MEASURED_MODEL_LANGUAGES } from './languages.ts';\n\n// identity.ts holds paths and cache identity, no network; store.ts holds the network fetches\n// (downloads, sha resolution, language metadata), re-exported here for its network surface.\nexport { hasModelFiles, isDownloadable, MODEL_FILENAMES, MODEL_FILES, modelDir, readLanguages, refsMainPath, snapshotDir, writeLanguages, writeRef } from './identity.ts';\n\n// A non-static provider has nothing to download here; an unreachable endpoint surfaces as an\n// EMBED_MODEL error at call time instead.\nexport function modelPresent(cfg: Config): boolean {\n const e = embedConfig(cfg);\n if (!e) return false;\n return e.provider !== 'static' || hasModelFiles(e.model);\n}\n\ntype ResolvedEmbedConfig = NonNullable<ReturnType<typeof embedConfig>>;\n\n// True when embed.model names a local path (not a Hugging Face id) that is missing its model\n// files -- nothing will ever fetch it for itself, unlike a downloadable id.\nexport function localModelMissing(e: ResolvedEmbedConfig | null): e is ResolvedEmbedConfig {\n return e !== null && e.provider === 'static' && !isDownloadable(e.model) && !hasModelFiles(e.model);\n}\n\n// `main` resolves to a sha once per model: a recorded ref pins until its snapshot is\n// removed, so only the first need for an id ever costs this HEAD request.\nasync function resolveSha(model: string, root: string = DEFAULT_MODELS_ROOT): Promise<string> {\n const existing = readRef(model, root);\n if (existing) return existing;\n const url = `https://huggingface.co/${model}/resolve/main/model.safetensors`;\n // redirect: manual -- the header rides the Hub's own response; following the LFS/CDN\n // redirect would read the CDN's headers instead, which do not carry it.\n const res = await fetchWithRetry(url, { method: 'HEAD', redirect: 'manual' }, { attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS });\n const sha = res.headers.get('x-repo-commit');\n if (!sha) throw new SenseError('EMBED_MODEL', `${res.url}: response carried no x-repo-commit header`);\n writeRef(model, sha, root);\n return sha;\n}\n\ninterface HfModelInfo {\n cardData?: { language?: string | string[] };\n tags?: string[];\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((part) => typeof part === 'string');\n}\n\nfunction isHfModelInfo(value: unknown): value is HfModelInfo {\n if (value === null || typeof value !== 'object') return false;\n if ('tags' in value && value.tags !== undefined && !isStringArray(value.tags)) return false;\n if (!('cardData' in value) || value.cardData === undefined) return true;\n if (value.cardData === null || typeof value.cardData !== 'object') return false;\n if (!('language' in value.cardData) || value.cardData.language === undefined) return true;\n return typeof value.cardData.language === 'string' || isStringArray(value.cardData.language);\n}\n\n// cardData.language is the structured field; tags are a fallback for cards that only tag\n// languages, filtered to recognized codes so an unrelated short tag is never mistaken for one.\nfunction languagesFromCard(info: HfModelInfo): string[] | undefined {\n const lang = info.cardData?.language;\n if (typeof lang === 'string') return [lang];\n if (Array.isArray(lang) && lang.length > 0) return lang;\n const tagLangs = (info.tags ?? []).filter(isKnownLanguageTag);\n return tagLangs.length > 0 ? tagLangs : undefined;\n}\n\n// Unreachable metadata is not an error, only the language-fit check staying off, but it says so:\n// the check that keeps a misfit model loud cannot itself go quiet (PRINCIPLES: no-silent-modes).\nfunction cardUnreadable(model: string): void {\n console.error(`sense: could not read the model card for ${model}; the language-fit check is off until it resolves (retries on next run, or run \\`sense download\\`)`);\n}\n\nasync function ensureLanguages(model: string, root: string = DEFAULT_MODELS_ROOT): Promise<void> {\n if (existsSync(languagesPath(model, root))) return;\n // A measured entry needs no card and no network, and stays deterministic offline.\n const measured = MEASURED_MODEL_LANGUAGES[model];\n if (measured) {\n writeLanguages(model, measured, root);\n return;\n }\n let res: BufferedResponse;\n try {\n res = await fetchWithRetry(`https://huggingface.co/api/models/${model}`, {}, { attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS });\n } catch {\n cardUnreadable(model);\n return;\n }\n if (!res.ok) {\n cardUnreadable(model);\n return;\n }\n let info: HfModelInfo;\n try {\n const decoded: unknown = JSON.parse(new TextDecoder().decode(res.body));\n if (!isHfModelInfo(decoded)) throw new Error('invalid model-card response');\n info = decoded;\n } catch {\n cardUnreadable(model);\n return;\n }\n writeLanguages(model, languagesFromCard(info) ?? [], root);\n}\n\nasync function fetchToFile(url: string, dest: string): Promise<void> {\n const res = await fetchWithRetry(url, {}, { attemptTimeoutMs: MODEL_FILE_ATTEMPT_TIMEOUT_MS });\n if (!res.ok) throw new SenseError('EMBED_MODEL', `${res.url} -> HTTP ${res.status}`);\n writeFileAtomic(dest, Buffer.from(res.body));\n}\n\n// Fetches an already-known sha straight into its snapshot dir, without touching refs/main --\n// for downloadModel below, and for callers pinning an exact revision (the parity suite).\nexport async function downloadModelRevision(model: string, sha: string, onFile?: (file: string, dir: string) => void, root: string = DEFAULT_MODELS_ROOT): Promise<string> {\n const dir = snapshotDir(model, sha, root);\n mkdirSync(dir, { recursive: true });\n for (const file of MODEL_FILES) {\n if (existsSync(join(dir, file))) continue;\n onFile?.(file, dir);\n await fetchToFile(`https://huggingface.co/${model}/resolve/${sha}/${file}`, join(dir, file));\n }\n return dir;\n}\n\n// The only code path that resolves `main`: a static provider's first construction calls it\n// lazily, `sense download` as an explicit prefetch. Idempotent either way.\nexport async function downloadModel(model: string, onFile?: (file: string, dir: string) => void, root: string = DEFAULT_MODELS_ROOT): Promise<string> {\n if (!isDownloadable(model)) {\n throw new SenseError('EMBED_MODEL', `embed.model \"${model}\" is a local path, not a Hugging Face model id, so there is nothing to download; put model.safetensors and tokenizer.json in that directory, or name a model id like \"minishlab/potion-retrieval-32M\"`);\n }\n const sha = await resolveSha(model, root);\n // Independent of the weights above: a fresh HEAD/GET pair either way, so a lazy first\n // construction and an explicit prefetch both end up with a cached language verdict.\n await ensureLanguages(model, root);\n return downloadModelRevision(model, sha, onFile, root);\n}\n"],"names":["existsSync","mkdirSync","join","embedConfig","SenseError","writeFileAtomic","fetchWithRetry","HTTP_ATTEMPT_TIMEOUT_MS","MODEL_FILE_ATTEMPT_TIMEOUT_MS","DEFAULT_MODELS_ROOT","hasModelFiles","isDownloadable","languagesPath","MODEL_FILES","readRef","snapshotDir","writeLanguages","writeRef","isKnownLanguageTag","MEASURED_MODEL_LANGUAGES","MODEL_FILENAMES","modelDir","readLanguages","refsMainPath","modelPresent","cfg","e","provider","model","localModelMissing","resolveSha","root","existing","url","res","method","redirect","attemptTimeoutMs","sha","headers","get","isStringArray","value","Array","isArray","every","part","isHfModelInfo","tags","undefined","cardData","language","languagesFromCard","info","lang","length","tagLangs","filter","cardUnreadable","console","error","ensureLanguages","measured","ok","decoded","JSON","parse","TextDecoder","decode","body","Error","fetchToFile","dest","status","Buffer","from","downloadModelRevision","onFile","dir","recursive","file","downloadModel"],"mappings":"AAAA,SAASA,UAAU,EAAEC,SAAS,QAAQ,UAAU;AAChD,SAASC,IAAI,QAAQ,YAAY;AAEjC,SAASC,WAAW,QAAQ,qBAAqB;AACjD,SAASC,UAAU,QAAQ,eAAe;AAC1C,SAASC,eAAe,QAAQ,yBAAyB;AACzD,SAAgCC,cAAc,EAAEC,uBAAuB,EAAEC,6BAA6B,QAAQ,YAAY;AAC1H,SAASC,mBAAmB,EAAEC,aAAa,EAAEC,cAAc,EAAEC,aAAa,EAAEC,WAAW,EAAEC,OAAO,EAAEC,WAAW,EAAEC,cAAc,EAAEC,QAAQ,QAAQ,gBAAgB;AAC/J,SAASC,kBAAkB,EAAEC,wBAAwB,QAAQ,iBAAiB;AAE9E,6FAA6F;AAC7F,4FAA4F;AAC5F,SAAST,aAAa,EAAEC,cAAc,EAAES,eAAe,EAAEP,WAAW,EAAEQ,QAAQ,EAAEC,aAAa,EAAEC,YAAY,EAAER,WAAW,EAAEC,cAAc,EAAEC,QAAQ,QAAQ,gBAAgB;AAE1K,6FAA6F;AAC7F,0CAA0C;AAC1C,OAAO,SAASO,aAAaC,GAAW;IACtC,MAAMC,IAAIvB,YAAYsB;IACtB,IAAI,CAACC,GAAG,OAAO;IACf,OAAOA,EAAEC,QAAQ,KAAK,YAAYjB,cAAcgB,EAAEE,KAAK;AACzD;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AAMU,MAAM,MAAMR,WAAWF,OAAOG;IACpC,sFAAsF;IACtF,oFAAoF;IACpF,MAAM8B,gBAAgBjC,OAAOG;IAC7B,OAAO6C,sBAAsBhD,OAAOU,KAAKuC,QAAQ9C;AACnD"}
1
+ {"version":3,"sources":["/Users/kevin/Dev/open-source/ai/sensemaking/src/embed/store.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { Config } from '../config/index.ts';\nimport { embedConfig } from '../config/index.ts';\nimport { SenseError } from '../errors.ts';\nimport { writeFileAtomic } from '../lib/atomic-write.ts';\nimport { type BufferedResponse, fetchWithRetry, HTTP_ATTEMPT_TIMEOUT_MS, MODEL_FILE_ATTEMPT_TIMEOUT_MS } from './http.ts';\nimport { DEFAULT_MODELS_ROOT, hasModelFiles, isDownloadable, languagesPath, MODEL_FILES, readRef, snapshotDir, writeLanguages, writeRef } from './identity.ts';\nimport { isKnownLanguageTag, MEASURED_MODEL_LANGUAGES } from './languages.ts';\n\n// The Hub base for every request here; downloadModelRevision takes it as a parameter so a test can point it at a local server.\nconst HF_HUB = 'https://huggingface.co';\n\n// identity.ts holds paths and cache identity, no network; store.ts holds the network fetches\n// (downloads, sha resolution, language metadata), re-exported here for its network surface.\nexport { hasModelFiles, isDownloadable, MODEL_FILENAMES, MODEL_FILES, modelDir, readLanguages, refsMainPath, snapshotDir, writeLanguages, writeRef } from './identity.ts';\n\n// A non-static provider has nothing to download here; an unreachable endpoint surfaces as an\n// EMBED_MODEL error at call time instead.\nexport function modelPresent(cfg: Config): boolean {\n const e = embedConfig(cfg);\n if (!e) return false;\n return e.provider !== 'static' || hasModelFiles(e.model);\n}\n\ntype ResolvedEmbedConfig = NonNullable<ReturnType<typeof embedConfig>>;\n\n// True when embed.model names a local path (not a Hugging Face id) that is missing its model\n// files -- nothing will ever fetch it for itself, unlike a downloadable id.\nexport function localModelMissing(e: ResolvedEmbedConfig | null): e is ResolvedEmbedConfig {\n return e !== null && e.provider === 'static' && !isDownloadable(e.model) && !hasModelFiles(e.model);\n}\n\n// `main` resolves to a sha once per model: a recorded ref pins until its snapshot is\n// removed, so only the first need for an id ever costs this HEAD request.\nasync function resolveSha(model: string, root: string = DEFAULT_MODELS_ROOT): Promise<string> {\n const existing = readRef(model, root);\n if (existing) return existing;\n const url = `${HF_HUB}/${model}/resolve/main/model.safetensors`;\n // redirect: manual -- the header rides the Hub's own response; following the LFS/CDN\n // redirect would read the CDN's headers instead, which do not carry it.\n const res = await fetchWithRetry(url, { method: 'HEAD', redirect: 'manual' }, { attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS });\n const sha = res.headers.get('x-repo-commit');\n if (!sha) throw new SenseError('EMBED_MODEL', `${res.url}: response carried no x-repo-commit header`);\n writeRef(model, sha, root);\n return sha;\n}\n\ninterface HfModelInfo {\n cardData?: { language?: string | string[] };\n tags?: string[];\n}\n\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((part) => typeof part === 'string');\n}\n\nfunction isHfModelInfo(value: unknown): value is HfModelInfo {\n if (value === null || typeof value !== 'object') return false;\n if ('tags' in value && value.tags !== undefined && !isStringArray(value.tags)) return false;\n if (!('cardData' in value) || value.cardData === undefined) return true;\n if (value.cardData === null || typeof value.cardData !== 'object') return false;\n if (!('language' in value.cardData) || value.cardData.language === undefined) return true;\n return typeof value.cardData.language === 'string' || isStringArray(value.cardData.language);\n}\n\n// cardData.language is the structured field; tags are a fallback for cards that only tag\n// languages, filtered to recognized codes so an unrelated short tag is never mistaken for one.\nfunction languagesFromCard(info: HfModelInfo): string[] | undefined {\n const lang = info.cardData?.language;\n if (typeof lang === 'string') return [lang];\n if (Array.isArray(lang) && lang.length > 0) return lang;\n const tagLangs = (info.tags ?? []).filter(isKnownLanguageTag);\n return tagLangs.length > 0 ? tagLangs : undefined;\n}\n\n// Unreachable metadata is not an error, only the language-fit check staying off, but it says so:\n// the check that keeps a misfit model loud cannot itself go quiet (PRINCIPLES: no-silent-modes).\nfunction cardUnreadable(model: string): void {\n console.error(`sense: could not read the model card for ${model}; the language-fit check is off until it resolves (retries on next run, or run \\`sense download\\`)`);\n}\n\nasync function ensureLanguages(model: string, root: string = DEFAULT_MODELS_ROOT): Promise<void> {\n if (existsSync(languagesPath(model, root))) return;\n // A measured entry needs no card and no network, and stays deterministic offline.\n const measured = MEASURED_MODEL_LANGUAGES[model];\n if (measured) {\n writeLanguages(model, measured, root);\n return;\n }\n let res: BufferedResponse;\n try {\n res = await fetchWithRetry(`${HF_HUB}/api/models/${model}`, {}, { attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS });\n } catch {\n cardUnreadable(model);\n return;\n }\n if (!res.ok) {\n cardUnreadable(model);\n return;\n }\n let info: HfModelInfo;\n try {\n const decoded: unknown = JSON.parse(new TextDecoder().decode(res.body));\n if (!isHfModelInfo(decoded)) throw new Error('invalid model-card response');\n info = decoded;\n } catch {\n cardUnreadable(model);\n return;\n }\n writeLanguages(model, languagesFromCard(info) ?? [], root);\n}\n\n// What the Hub publishes for one file at a pinned commit: sha256 of the content for LFS files,\n// the git blob sha1 for plain git files, plus the size.\ninterface ExpectedFile {\n kind: 'sha256' | 'git-sha1';\n hash: string;\n size: number;\n}\n\ninterface HfTreeEntry {\n path: string;\n oid: string;\n size: number;\n lfs?: { oid: string; size: number };\n}\n\nfunction isHfTreeEntry(value: unknown): value is HfTreeEntry {\n if (value === null || typeof value !== 'object') return false;\n if (!('path' in value) || typeof value.path !== 'string') return false;\n if (!('oid' in value) || typeof value.oid !== 'string') return false;\n if (!('size' in value) || typeof value.size !== 'number') return false;\n if (!('lfs' in value) || value.lfs === undefined) return true;\n if (value.lfs === null || typeof value.lfs !== 'object') return false;\n return 'oid' in value.lfs && typeof value.lfs.oid === 'string' && 'size' in value.lfs && typeof value.lfs.size === 'number';\n}\n\nfunction isHfTree(value: unknown): value is HfTreeEntry[] {\n return Array.isArray(value) && value.every(isHfTreeEntry);\n}\n\nfunction unverifiable(model: string, sha: string, detail: string): SenseError {\n return new SenseError('EMBED_MODEL', `could not get the Hub's published hashes for ${model}@${sha.slice(0, 8)}: ${detail}; no model file was written. Retry \\`sense download\\`; if it repeats, something between this machine and Hugging Face is changing the response`);\n}\n\nasync function fetchExpected(model: string, sha: string, files: string[], hub: string): Promise<Map<string, ExpectedFile>> {\n const url = `${hub}/api/models/${model}/tree/${sha}`;\n let res: BufferedResponse;\n try {\n res = await fetchWithRetry(url, {}, { attemptTimeoutMs: HTTP_ATTEMPT_TIMEOUT_MS });\n } catch (err) {\n throw unverifiable(model, sha, `${url} failed (${(err as Error).message})`);\n }\n if (res.status !== 200) throw unverifiable(model, sha, `${url} -> HTTP ${res.status}`);\n let tree: unknown;\n try {\n tree = JSON.parse(new TextDecoder().decode(res.body));\n } catch {\n throw unverifiable(model, sha, `${url} did not return JSON`);\n }\n if (!isHfTree(tree)) throw unverifiable(model, sha, `${url} returned an unrecognized tree`);\n const expected = new Map<string, ExpectedFile>();\n for (const file of files) {\n const entry = tree.find((e) => e.path === file);\n if (!entry) throw unverifiable(model, sha, `the tree has no entry for ${file}`);\n expected.set(file, entry.lfs ? { kind: 'sha256', hash: entry.lfs.oid, size: entry.lfs.size } : { kind: 'git-sha1', hash: entry.oid, size: entry.size });\n }\n return expected;\n}\n\n// git blob id: sha1 over \"blob <size>\\0\" then the bytes.\nfunction digest(kind: ExpectedFile['kind'], bytes: Buffer): string {\n if (kind === 'sha256') return createHash('sha256').update(bytes).digest('hex');\n return createHash('sha1').update(`blob ${bytes.byteLength}\\0`).update(bytes).digest('hex');\n}\n\nasync function fetchToFile(url: string, dest: string, expected: ExpectedFile, label: string): Promise<void> {\n const res = await fetchWithRetry(url, {}, { attemptTimeoutMs: MODEL_FILE_ATTEMPT_TIMEOUT_MS });\n if (!res.ok) throw new SenseError('EMBED_MODEL', `${res.url} -> HTTP ${res.status}`);\n const bytes = Buffer.from(res.body);\n const mismatch = (actual: string) =>\n new SenseError('EMBED_MODEL', `${label} does not match the Hub's published ${expected.kind}: expected ${expected.hash.slice(0, 12)} (${expected.size} bytes), got ${actual}; ${label} was not written. Retry \\`sense download\\`; if it repeats, something between this machine and Hugging Face is changing the file`);\n if (bytes.byteLength !== expected.size) throw mismatch(`${bytes.byteLength} bytes`);\n const actual = digest(expected.kind, bytes);\n if (actual !== expected.hash) throw mismatch(`${actual.slice(0, 12)} (${bytes.byteLength} bytes)`);\n writeFileAtomic(dest, bytes);\n}\n\n// Fetches an already-known sha straight into its snapshot dir, without touching refs/main --\n// for downloadModel below, and for callers pinning an exact revision (the parity suite).\n// Each fetched file is verified against the Hub's published hash before it is written.\nexport async function downloadModelRevision(model: string, sha: string, onFile?: (file: string, dir: string) => void, root: string = DEFAULT_MODELS_ROOT, hub: string = HF_HUB): Promise<string> {\n const dir = snapshotDir(model, sha, root);\n mkdirSync(dir, { recursive: true });\n // Files already on disk are not re-hashed (0.3 s per open), including ones written before\n // verification existed; removing the snapshot folder re-downloads and verifies them.\n const missing = MODEL_FILES.filter((file) => !existsSync(join(dir, file)));\n if (missing.length === 0) return dir;\n const expected = await fetchExpected(model, sha, missing, hub);\n for (const file of missing) {\n const want = expected.get(file);\n if (!want) throw unverifiable(model, sha, `no expected value for ${file}`);\n onFile?.(file, dir);\n await fetchToFile(`${hub}/${model}/resolve/${sha}/${file}`, join(dir, file), want, `${model}@${sha.slice(0, 8)}/${file}`);\n }\n return dir;\n}\n\n// The only code path that resolves `main`: a static provider's first construction calls it\n// lazily, `sense download` as an explicit prefetch. Idempotent either way.\nexport async function downloadModel(model: string, onFile?: (file: string, dir: string) => void, root: string = DEFAULT_MODELS_ROOT): Promise<string> {\n if (!isDownloadable(model)) {\n throw new SenseError('EMBED_MODEL', `embed.model \"${model}\" is a local path, not a Hugging Face model id, so there is nothing to download; put model.safetensors and tokenizer.json in that directory, or name a model id like \"minishlab/potion-retrieval-32M\"`);\n }\n const sha = await resolveSha(model, root);\n // Independent of the weights above: a fresh HEAD/GET pair either way, so a lazy first\n // construction and an explicit prefetch both end up with a cached language verdict.\n await ensureLanguages(model, root);\n return downloadModelRevision(model, sha, onFile, root);\n}\n"],"names":["createHash","existsSync","mkdirSync","join","embedConfig","SenseError","writeFileAtomic","fetchWithRetry","HTTP_ATTEMPT_TIMEOUT_MS","MODEL_FILE_ATTEMPT_TIMEOUT_MS","DEFAULT_MODELS_ROOT","hasModelFiles","isDownloadable","languagesPath","MODEL_FILES","readRef","snapshotDir","writeLanguages","writeRef","isKnownLanguageTag","MEASURED_MODEL_LANGUAGES","HF_HUB","MODEL_FILENAMES","modelDir","readLanguages","refsMainPath","modelPresent","cfg","e","provider","model","localModelMissing","resolveSha","root","existing","url","res","method","redirect","attemptTimeoutMs","sha","headers","get","isStringArray","value","Array","isArray","every","part","isHfModelInfo","tags","undefined","cardData","language","languagesFromCard","info","lang","length","tagLangs","filter","cardUnreadable","console","error","ensureLanguages","measured","ok","decoded","JSON","parse","TextDecoder","decode","body","Error","isHfTreeEntry","path","oid","size","lfs","isHfTree","unverifiable","detail","slice","fetchExpected","files","hub","err","message","status","tree","expected","Map","file","entry","find","set","kind","hash","digest","bytes","update","byteLength","fetchToFile","dest","label","Buffer","from","mismatch","actual","downloadModelRevision","onFile","dir","recursive","missing","want","downloadModel"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AACzC,SAASC,UAAU,EAAEC,SAAS,QAAQ,UAAU;AAChD,SAASC,IAAI,QAAQ,YAAY;AAEjC,SAASC,WAAW,QAAQ,qBAAqB;AACjD,SAASC,UAAU,QAAQ,eAAe;AAC1C,SAASC,eAAe,QAAQ,yBAAyB;AACzD,SAAgCC,cAAc,EAAEC,uBAAuB,EAAEC,6BAA6B,QAAQ,YAAY;AAC1H,SAASC,mBAAmB,EAAEC,aAAa,EAAEC,cAAc,EAAEC,aAAa,EAAEC,WAAW,EAAEC,OAAO,EAAEC,WAAW,EAAEC,cAAc,EAAEC,QAAQ,QAAQ,gBAAgB;AAC/J,SAASC,kBAAkB,EAA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A,OAAOmB;AACT;AAEA,2FAA2F;AAC3F,2EAA2E;AAC3E,OAAO,eAAeI,cAAcpF,KAAa,EAAE+E,MAA4C,EAAE5E,OAAevB,mBAAmB;IACjI,IAAI,CAACE,eAAekB,QAAQ;QAC1B,MAAM,IAAIzB,WAAW,eAAe,CAAC,aAAa,EAAEyB,MAAM,qMAAqM,CAAC;IAClQ;IACA,MAAMU,MAAM,MAAMR,WAAWF,OAAOG;IACpC,sFAAsF;IACtF,oFAAoF;IACpF,MAAM8B,gBAAgBjC,OAAOG;IAC7B,OAAO2E,sBAAsB9E,OAAOU,KAAKqE,QAAQ5E;AACnD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sensemaking",
3
- "version": "0.28.0",
3
+ "version": "0.28.2",
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",
@@ -68,7 +68,6 @@
68
68
  },
69
69
  "files": [
70
70
  "dist",
71
- "skills",
72
71
  "schema.json"
73
72
  ],
74
73
  "scripts": {
@@ -77,7 +76,7 @@
77
76
  "format": "tsds format",
78
77
  "prepublishOnly": "tsds validate",
79
78
  "test": "tsds test:node --no-timeouts",
80
- "test:benchmark-framework": "tsds test:node --no-timeouts test/integration/benchmark-workload-identity.test.ts test/integration/benchmark-row-classes.test.ts test/integration/gate-dependencies.test.ts test/integration/gate-profile.test.ts test/integration/gate-scheduling.test.ts test/integration/quality-retrieval-identity.test.ts test/integration/quality-validity.test.ts test/integration/portable-quality.test.ts test/integration/portable-quality-stage.test.ts test/integration/retained-quality.test.ts test/integration/benchmark-worker-lifetime.test.ts test/integration/benchmark-harness.test.ts test/integration/quality-cache.test.ts",
79
+ "test:benchmark-framework": "tsds test:node --no-timeouts test/integration/benchmark-workload-identity.test.ts test/integration/benchmark-row-classes.test.ts test/integration/gate-dependencies.test.ts test/integration/gate-profile.test.ts test/integration/gate-scheduling.test.ts test/integration/quality-retrieval-identity.test.ts test/integration/quality-validity.test.ts test/integration/portable-quality.test.ts test/integration/portable-quality-stage.test.ts test/integration/retained-quality.test.ts test/integration/benchmark-worker-lifetime.test.ts test/integration/benchmark-harness.test.ts test/integration/quality-cache.test.ts test/integration/benchmark-cache.test.ts",
81
80
  "test:engines": "nvu engines tsds test:node --no-timeouts",
82
81
  "version": "tsds version"
83
82
  },
@@ -104,6 +103,7 @@
104
103
  "fs-remove-compat": "^1.0.4",
105
104
  "node-version-use": "*",
106
105
  "portable-env": "^1.4.0",
106
+ "staged-cache": "^0.1.0",
107
107
  "ts-dev-stack": "*",
108
108
  "tsds-config": "*"
109
109
  },
@@ -1,99 +0,0 @@
1
- # sense: worked examples
2
-
3
- Outputs below are illustrative. Every result is a reference; reading happens afterward, through the filesystem, on the paths that earned it.
4
-
5
- ## A. "Do the notes say anything about X?"
6
-
7
- ```
8
- sense search "pricing OR billing OR invoicing" --k 10 --format json
9
- ```
10
-
11
- ```json
12
- [
13
- { "path": "notes/pricing-model.md", "title": "Pricing model",
14
- "summary": "Tiered per-seat pricing; floor and discount rules", "snippets": ["«Pricing» floor for annual…"], "via": "match+link", "score": 0.0333, "lines": null },
15
- { "path": "notes/renewal-playbook.md", "title": "Renewal playbook",
16
- "summary": "Renewal sequence and owners", "snippets": ["…«billing» contact confirms the PO…"], "via": "match", "score": 0.0313, "lines": "L81-140" }
17
- ]
18
- ```
19
-
20
- Tens of tokens per row; often the `summary` answers the question with no read at all. A row with `via: "link"` has link evidence rather than a word match. `lines`, when set, is a section or embedding chunk's line range, a direct `Read` range. See [Sense terminology](references/terminology.md) for these distinctions.
21
-
22
- ## B. Known-field filtering (no search)
23
-
24
- ```
25
- sense sql "SELECT path, title, status FROM frontmatter WHERE status = 'active' AND has(tags, ?)" pricing --format json
26
- ```
27
-
28
- Plain SQL on discovered columns. Combine with search by joining `content` and adding `AND content MATCH ?`: filter and rank in one query.
29
-
30
- Per-member counts on an array field (GROUP BY on the raw column would split `["a","b"]` from `["b","a"]`):
31
-
32
- ```
33
- sense sql "SELECT j.value AS tag, COUNT(*) n FROM frontmatter, json_each(frontmatter.tags) j GROUP BY j.value ORDER BY n DESC"
34
- ```
35
-
36
- ## C. Structure before reading
37
-
38
- ```
39
- sense peek notes/architecture-decisions.md
40
- ```
41
-
42
- ```
43
- notes/architecture-decisions.md (~4400 tokens)
44
- title: Architecture decisions
45
- sections:
46
- ## Storage layer: why SQLite [L41-88, ~610t]
47
- ## Queue: rejected options [L89-120, ~380t]
48
- ...
49
- links out (7): notes/pricing-model.md, ...
50
- backlinks (2): notes/_index.md, notes/roadmap.md
51
- ```
52
-
53
- The note is ~4,400 tokens; the peek is ~500. If only one section matters, `Read` its line range (~400 tokens), a tenth of the file.
54
-
55
- ## D. The graph
56
-
57
- ```
58
- sense sql "SELECT src FROM links WHERE dst = ?" notes/pricing-model.md # who cites this
59
- sense sql "SELECT src, target FROM links WHERE dst IS NULL" # unresolved links
60
- sense sql "SELECT path, round(_rank*100,2) r FROM frontmatter ORDER BY _rank DESC LIMIT 5" # load-bearing notes
61
- ```
62
-
63
- `sense map` prints the hub list without SQL; use these when you need it filtered or joined.
64
-
65
- ## E. Cold start on an unknown notes tree
66
-
67
- ```
68
- sense map # fields, hubs, recent. Read this first
69
- sense --list # named queries someone already saved
70
- sense sql "SELECT DISTINCT type FROM frontmatter" # what a field's values are
71
- ```
72
-
73
- ## F. "The notes say it in different words"
74
-
75
- ```
76
- sense search "children dying from poor nutrition" --k 3 --format json
77
- ```
78
-
79
- ```json
80
- [
81
- { "path": "notes/malnutrition-outcomes.md", "title": "Malnutrition outcomes",
82
- "summary": "Stunting and mortality by region", "snippets": [], "via": "vector", "score": 0.0167, "similarity": 0.61, "lines": "L14-52" }
83
- ]
84
- ```
85
-
86
- A `via: "vector"` row has vector evidence rather than a word match. `similarity` is the cosine against the chunk identified by `lines`, a direct `Read` range. Vector search requires a configured model, enabled vector signal and prepared embeddings. Vector-only results do not prove the query words are absent; use the word-search guidance when absence matters.
87
-
88
- ## Consequences
89
-
90
- | query | what happens | bounded alternative |
91
- |---|---|---|
92
- | `SELECT text FROM content` | returns the tree's entire prose | `snippet(content, -1, '«', '»', '…', 10)` excerpts the match |
93
- | `snippet()` on a tree holding a megabyte-scale note | re-tokenizes the whole document per matched row: seconds per query | bound it: `CASE WHEN length(content.text) <= 16384 THEN snippet(...) END`, or select `summary` instead |
94
- | `sense search "pricing"` | lexically matches only that word's stem (vector rows still widen by meaning) | OR-in synonyms and instances: `"pricing OR billing OR invoicing"` |
95
- | `sense search "pricing model details"` | bare words AND-join; one absent word = zero lexical rows | OR the words, or quote an exact phrase |
96
- | `sense search "customer-facing OR on-site"` | bare punctuation is FTS5 syntax (`-` reads as a column filter) | double-quote: `"customer-facing" OR "on-site"` |
97
- | `Read` of a large file for one section | costs the whole file | `peek`, then `Read` the line range |
98
- | row queries without `LIMIT` | unbounded output (aggregates are already bounded) | `LIMIT n` |
99
- | saving one-off queries to config | config churn | ad-hoc `sense sql`; save reusable views |
@@ -1,145 +0,0 @@
1
- ---
2
- name: sense
3
- description: "Query a markdown tree with the sense CLI: filter notes by frontmatter, search prose, follow wikilinks and backlinks, trace link paths, find similar but unlinked notes, and inspect note outlines. Use when a task needs to query, filter, count, search, or report on a markdown directory; when a directory has sense.config.json; or when adding a saved sense query."
4
- ---
5
-
6
- # sense
7
-
8
- Use sense to locate evidence in a markdown tree before reading files. With the config default `"build": true`, CLI queries incrementally scan the configured tree for the capabilities they need; vector preparation is limited to the eligible scope. Config `"build": false` or a one-query `--no-build` reads the last completed indexed generation, checks requested readiness and does not scan live files. Explicit build and watch prepare it regardless of that default. Results contain paths, metadata, snippets, and line ranges. Read the returned files or ranges when the task needs their prose.
9
-
10
- Setup, store selection, presets, and note design belong to the `sense-setup` skill. Translating an Obsidian Bases file belongs to `sense-bases`.
11
-
12
- Use the shared [Sense terminology](references/terminology.md) when explaining results or output controls. Read it when distinguishing a snippet, section, section description, outline, chunk or link type; those names are not interchangeable.
13
-
14
- ## Start with the tree
15
-
16
- Run these when the tree or its configuration is unfamiliar:
17
-
18
- ```sh
19
- sense status # config, store, cache, document count, preset coverage
20
- sense map # fields, hubs, recent notes
21
- sense --list # saved queries
22
- ```
23
-
24
- If a command reports a missing config, run `sense init` only when the user wants the tree configured. A one-off query does not authorize changing the tree.
25
-
26
- ## Choose the command
27
-
28
- | Need | Command |
29
- |---|---|
30
- | Exact count, filter, grouping, or known-field report | `sense sql` or a saved SQL query |
31
- | Notes about a subject | `sense search` |
32
- | One note's frontmatter, outline, links, and backlinks | `sense peek` |
33
- | Shortest link chain between two notes | `sense path` |
34
- | Similar notes that a note does not link to | `sense related` |
35
- | Tree shape and available fields | `sense map` |
36
-
37
- Start with a bounded result. Raise `--k`, widen the preset, or broaden the words only when the first result does not answer the question.
38
-
39
- ```sh
40
- sense search "pricing" --k 10
41
- sense search "sourcing quotes" --preset raw
42
- sense peek notes/pricing-model.md
43
- sense path onboarding.md pricing-model.md
44
- sense related notes/pricing-model.md --k 10
45
- sense sql "SELECT path FROM frontmatter WHERE status = ? LIMIT 50" active
46
- ```
47
-
48
- ## Read the store guide before composing syntax
49
-
50
- The config's `store` key selects the SQL dialect and text-search grammar. An omitted key means `sqlite`. Bare words and quoted phrases work in `sense search` on every store. Advanced operators and raw text-index SQL differ.
51
-
52
- Read the matching guide before writing raw SQL that uses engine functions, dates, JSON, text matching, or native types. Also read it before using advanced search operators.
53
-
54
- - [SQLite query guide](references/stores/sqlite.md)
55
- - [DuckDB query guide](references/stores/duckdb.md)
56
- - [Turso query guide](references/stores/turso.md)
57
-
58
- The tables, `?` placeholders, quoted identifiers, `has()`, `basename()`, and preset `scope` binding are shared. [Portable SQL](references/sql.md) documents the schema and queries that work without depending on one engine.
59
-
60
- ## Search and evidence
61
-
62
- `search` combines the signals enabled by the selected preset:
63
-
64
- | Signal | Evidence |
65
- |---|---|
66
- | `match` | The note contains the search words. `snippets` shows the matching passages. |
67
- | `link` | A note that matched links to this note. |
68
- | `vector` | The embedding model placed this note near the query. The search words may be absent. |
69
-
70
- Combinations such as `match+link` mean that more than one signal produced the row. `score` ranks rows within that result only. Do not compare it across searches. `similarity` ranks vector evidence within the current result and model. Do not carry a fixed similarity cutoff between trees.
71
-
72
- The `lines` value gives a line range in the indexed note. It can identify a section around a word match or an embedding chunk. Read that range when it is present. A null range means the whole note is the reference. A vector-only row has no lexical snippet and is a lead, not proof that the note contains the query terms.
73
-
74
- Read [search evidence and troubleshooting](references/search.md) when a search will support a factual claim, when absence matters, when results look noisy, or when tuning signal weights.
75
-
76
- `sense search --explain --format json` adds the actual ranking contributions for returned notes. It does not change ranking or explain every missing result. The search guide describes how contributions differ from the `via` evidence label.
77
-
78
- ## Scope and output
79
-
80
- Bare commands use the `default` preset. `--preset <name>` chooses another. For `search`, `map`, `peek`, `path`, and `related`, `--include`, `--exclude`, and `--no-exclude` change the query scope for one invocation, but cannot reach files that no preset indexes. `sense status` shows actual coverage. Scope selects results; presets are not a security boundary.
81
-
82
- `peek` rejects an exact path outside scope before trying a basename, resolves basenames within scope, and shows only scoped resolved links and backlinks; unresolved targets remain as written. `path` resolves its endpoints across the indexed tree and scopes intermediate notes. `related` resolves its seed across the indexed tree and scopes result candidates.
83
-
84
- `peek --section-count-limit n` bounds section descriptions. `--link-count-limit n` independently bounds each group of outbound links, backlinks and unresolved links. Both default to 20 and require positive safe integers. Request more when the outline or links you need are truncated, or fewer for triage. Totals still describe the full selected groups; the limits do not widen scope. Section descriptions identify where to read; they do not return section prose.
85
-
86
- `--where` filters search and graph commands against frontmatter alias `f`:
87
-
88
- ```sh
89
- sense search "pricing" --where "f.status = 'active' AND has(f.tags, 'sales')"
90
- ```
91
-
92
- `sense sql` is index-wide by default. With `--preset`, the command binds a temporary `scope(path)` table. The SQL must join it:
93
-
94
- ```sh
95
- sense sql "SELECT f.path FROM frontmatter f JOIN scope ON scope.path = f.path" --preset default
96
- ```
97
-
98
- Table output is for people. Use `--format json` when code or an agent will parse rows. Use `--format csv` when redirecting a large row set to a file. `sql`, `search`, `related`, and saved queries support all three formats. `map`, `peek`, `status`, and `path` support table and JSON.
99
-
100
- ## Saved queries
101
-
102
- Save a query in `sense.config.json` only when it will be reused:
103
-
104
- ```json
105
- {
106
- "queries": {
107
- "by-tag": { "sql": "SELECT path, title FROM frontmatter WHERE has(tags, ?) ORDER BY path" },
108
- "hot": { "search": "pricing", "preset": "raw", "k": 20 }
109
- }
110
- }
111
- ```
112
-
113
- Run these as `sense by-tag urgent` and `sense hot`. Invocation flags override a saved search's `preset`, `k`, or `where` value.
114
-
115
- Running a saved entry validates it. Exit code 0 means it ran, 6 means the invocation needs different arguments, and 4 means an operational failure, such as a query, store or CLI bootstrap failure. An empty result can be valid data, so interpret it from the query's purpose.
116
-
117
- ## Tables
118
-
119
- | Table | Holds |
120
- |---|---|
121
- | `frontmatter` | One discovered column per frontmatter key, plus `path`, `_mtime`, `_ctime`, `_size`, `_rank`, and `_parse_error` |
122
- | `content` | `path`, `title`, `summary`, and authored text, plus store-owned search columns |
123
- | `links` | `src`, written `target`, resolved `dst`, and `embed` |
124
- | `tags` | Merged and deduplicated frontmatter and inline tags |
125
- | `sections` | Heading, level, line range, and token estimate |
126
- | `preset_files` | Paths covered by each preset |
127
-
128
- Features can add tables. `sense map` and `sense status` show which features are active.
129
-
130
- A non-null `_parse_error` means the file has no recovered frontmatter values. To distinguish a missing field from invalid frontmatter, include `_parse_error IS NULL` in the filter. Fixes appear on the next command because reconciliation runs first.
131
-
132
- ## Reading discipline
133
-
134
- Select only the columns needed for the answer. Use `LIMIT` for row-returning exploration. Prefer `path`, `title`, `summary`, and bounded snippets over `content.text`. Aggregates such as `COUNT` and `GROUP BY` are already bounded by their result shape.
135
-
136
- When a result identifies a large note, use `peek` and then read the relevant line range. Small files are often cheaper to read whole.
137
-
138
- Worked command traces are in [EXAMPLES.md](EXAMPLES.md).
139
-
140
- ## Upkeep
141
-
142
- - Install a missing CLI with `npm install -g sensemaking`.
143
- - `sense status` prints the cache path and watcher state.
144
- - Use `sense build --force` to recreate a derived index whose state is in doubt; source files, configuration, and the watcher ownership claim remain in place.
145
- - Use `sense watch` when another process should keep all configured capabilities prepared during frequent edits. A default query scans the configured tree for its needed capabilities and limits vector preparation to eligible paths; `--no-build` reads the completed generation only.
@@ -1,63 +0,0 @@
1
- # Search evidence and troubleshooting
2
-
3
- Read this guide when search results will support a factual claim, when absence matters, when results look noisy, or when changing signal weights.
4
-
5
- [Sense terminology](terminology.md) defines the result objects. In particular, snippets, sections and embedding chunks are different units.
6
-
7
- ## What each signal establishes
8
-
9
- `words` ranks literal occurrences after stemming. It is the right signal for identifiers, error strings, names, and quoted phrases. A `match` row is lexical evidence because its `snippets` show the occurrence.
10
-
11
- `links` expands from matching notes through links written by the authors. A `link` row establishes that relationship, but does not establish that the row contains the query words.
12
-
13
- `vectors` ranks the meaning of chunks. It can find paraphrases and related concepts with no shared vocabulary. A `vector` row is a lead to read. It cannot prove that a word or claim appears in the note.
14
-
15
- Search uses every signal named by the preset. If `signals` is absent, every signal whose prerequisites hold has weight 1. A number changes that signal's contribution to reciprocal-rank fusion:
16
-
17
- ```json
18
- "signals": { "words": 1, "links": 1, "vectors": 4 }
19
- ```
20
-
21
- Weights are corpus and model choices. Compare representative queries before changing them. One weight does not transfer reliably between unrelated trees or embedding models.
22
-
23
- ## Reading the rows
24
-
25
- - `via` names the evidence that produced the row.
26
- - `snippets` contains marked lexical passages. It is empty when no word matched.
27
- - `lines` is the selected section or embedding chunk's line range in the indexed note. Null means the whole note is the reference.
28
- - `score` orders the fused result. Its scale changes with the participating signals and ranks, so compare rows only inside one result.
29
- - `similarity` is cosine similarity against the best chunk. Compare it inside one result and one model. Small trees can give unrelated text a moderately close nearest neighbor.
30
-
31
- Relay the evidence label when reporting a result. "The note contains these words" and "the note is semantically related" support different claims.
32
-
33
- ## Finite retrieval and paging
34
-
35
- `k` is the maximum number of notes returned by one finite retrieval. Changing `k` can change the candidate pools, link seeds and fused ranking, including the earlier rows. It starts a new retrieval rather than continuing a stable result set. When you need pages, retain one returned array or JSON result and page that locally.
36
-
37
- ## Explain a ranking
38
-
39
- Add `--explain` to a direct `sense search` invocation when you need to inspect how the configured signals contributed. With `--format json`, each returned row adds an `explanation` array containing `signal`, `rank`, `weight` and `contribution`. Entries follow words, links, vectors order and include only signals that contributed to that candidate. Without the flag, ordinary output is unchanged.
40
-
41
- Ranks are one-based within each signal's candidate list. A contribution is `weight / (60 + rank - 1)`, using the actual unrounded value accumulated during ranking. The sum is the fused score before its public display rounding. These values are not native BM25 scores and do not make lexical rankings comparable across stores.
42
-
43
- An isolated word-match seed can receive link-signal restart mass while its `via` label remains `match`. The explanation reports the numeric contribution; `via` remains the evidence label, not an exhaustive score breakdown. An explanation does not establish that a claim is true or describe why an absent note failed to enter the candidate set.
44
-
45
- Table and CSV formats encode the explanation cell as JSON text. Table output follows the existing cell clipping rules; use JSON or CSV for the complete values. Explanation reuses the current search and does not make an additional embedding request. It is not a saved-query configuration field.
46
-
47
- ## When a search misses
48
-
49
- For word search, try concrete terms that the notes may use, widen the selected preset, or raise `--k`. Search grammar depends on the selected store. Read its guide before adding operators.
50
-
51
- For vector search, restate the concept in different words. Then use `related <path>` on the nearest useful hit to inspect its semantic neighborhood.
52
-
53
- Each widening step adds candidates and can dilute the ranking. Inspect the new rows before widening again.
54
-
55
- ## Absence
56
-
57
- A words-only preset returns no rows when the terms do not occur in its indexed scope. With vectors enabled, nearest-neighbor search can still return vector-only rows for any input. Those rows show conceptual proximity, not lexical presence.
58
-
59
- When absence matters, use a preset whose `signals` excludes `vectors`, or query the selected store's text index as described in its guide. Confirm the preset's coverage with `sense status` before concluding that the terms are absent from the tree.
60
-
61
- ## Template-heavy trees
62
-
63
- Vectors rank whole chunks, including repeated boilerplate. In a tree whose notes share a large template and contain little unique prose, unrelated seeds can return the same neighbors with almost identical similarities. Compare two unlike seed notes. If their neighbor lists barely change, search the fields or words that distinguish the notes instead.