sensemaking 0.9.4 → 0.10.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.
- package/README.md +50 -100
- package/dist/cjs/cli/check.js +7 -13
- package/dist/cjs/cli/check.js.map +1 -1
- package/dist/cjs/cli/download.d.cts +3 -0
- package/dist/cjs/cli/download.d.ts +3 -0
- package/dist/cjs/cli/download.js +214 -0
- package/dist/cjs/cli/download.js.map +1 -0
- package/dist/cjs/cli/index.d.cts +6 -3
- package/dist/cjs/cli/index.d.ts +6 -3
- package/dist/cjs/cli/index.js +23 -5
- package/dist/cjs/cli/index.js.map +1 -1
- package/dist/cjs/cli/init.js +4 -1
- package/dist/cjs/cli/init.js.map +1 -1
- package/dist/cjs/cli/map.js +2 -2
- package/dist/cjs/cli/map.js.map +1 -1
- package/dist/cjs/cli/named.js +10 -18
- package/dist/cjs/cli/named.js.map +1 -1
- package/dist/cjs/cli/path.d.cts +3 -0
- package/dist/cjs/cli/path.d.ts +3 -0
- package/dist/cjs/cli/path.js +161 -0
- package/dist/cjs/cli/path.js.map +1 -0
- package/dist/cjs/cli/peek.js +3 -2
- package/dist/cjs/cli/peek.js.map +1 -1
- package/dist/cjs/cli/related.d.cts +3 -0
- package/dist/cjs/cli/related.d.ts +3 -0
- package/dist/cjs/cli/related.js +279 -0
- package/dist/cjs/cli/related.js.map +1 -0
- package/dist/cjs/cli/search.js +3 -7
- package/dist/cjs/cli/search.js.map +1 -1
- package/dist/cjs/cli/shared.d.cts +3 -1
- package/dist/cjs/cli/shared.d.ts +3 -1
- package/dist/cjs/cli/shared.js +28 -5
- package/dist/cjs/cli/shared.js.map +1 -1
- package/dist/cjs/cli/sql.d.cts +3 -0
- package/dist/cjs/cli/sql.d.ts +3 -0
- package/dist/cjs/cli/{query.js → sql.js} +4 -4
- package/dist/cjs/cli/sql.js.map +1 -0
- package/dist/cjs/cli/status.js +9 -2
- package/dist/cjs/cli/status.js.map +1 -1
- package/dist/cjs/cli.js +14 -15
- package/dist/cjs/cli.js.map +1 -1
- package/dist/cjs/commands.d.cts +12 -4
- package/dist/cjs/commands.d.ts +12 -4
- package/dist/cjs/commands.js +138 -58
- package/dist/cjs/commands.js.map +1 -1
- package/dist/cjs/config.d.cts +6 -4
- package/dist/cjs/config.d.ts +6 -4
- package/dist/cjs/config.js +137 -58
- package/dist/cjs/config.js.map +1 -1
- package/dist/cjs/db.js +14 -34
- package/dist/cjs/db.js.map +1 -1
- package/dist/cjs/errors.d.cts +1 -1
- package/dist/cjs/errors.d.ts +1 -1
- package/dist/cjs/errors.js.map +1 -1
- package/dist/cjs/features/embed.d.cts +14 -0
- package/dist/cjs/features/embed.d.ts +14 -0
- package/dist/cjs/features/embed.js +248 -54
- package/dist/cjs/features/embed.js.map +1 -1
- package/dist/cjs/features/links.js +7 -16
- package/dist/cjs/features/links.js.map +1 -1
- package/dist/cjs/features/rank.js +2 -6
- package/dist/cjs/features/rank.js.map +1 -1
- package/dist/cjs/index.d.cts +1 -1
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/output.js +11 -14
- package/dist/cjs/output.js.map +1 -1
- package/dist/cjs/progress.js +2 -4
- package/dist/cjs/progress.js.map +1 -1
- package/dist/cjs/scan.d.cts +1 -0
- package/dist/cjs/scan.d.ts +1 -0
- package/dist/cjs/scan.js +67 -32
- package/dist/cjs/scan.js.map +1 -1
- package/dist/cjs/search-error.js +4 -6
- package/dist/cjs/search-error.js.map +1 -1
- package/dist/cjs/traverse.d.cts +8 -0
- package/dist/cjs/traverse.d.ts +8 -0
- package/dist/cjs/traverse.js +97 -0
- package/dist/cjs/traverse.js.map +1 -0
- package/dist/esm/cli/check.js +7 -13
- package/dist/esm/cli/check.js.map +1 -1
- package/dist/esm/cli/download.d.ts +3 -0
- package/dist/esm/cli/download.js +27 -0
- package/dist/esm/cli/download.js.map +1 -0
- package/dist/esm/cli/index.d.ts +6 -3
- package/dist/esm/cli/index.js +13 -7
- package/dist/esm/cli/index.js.map +1 -1
- package/dist/esm/cli/init.js +4 -1
- package/dist/esm/cli/init.js.map +1 -1
- package/dist/esm/cli/map.js +3 -2
- package/dist/esm/cli/map.js.map +1 -1
- package/dist/esm/cli/named.js +10 -16
- package/dist/esm/cli/named.js.map +1 -1
- package/dist/esm/cli/path.d.ts +3 -0
- package/dist/esm/cli/path.js +51 -0
- package/dist/esm/cli/path.js.map +1 -0
- package/dist/esm/cli/peek.js +4 -2
- package/dist/esm/cli/peek.js.map +1 -1
- package/dist/esm/cli/related.d.ts +3 -0
- package/dist/esm/cli/related.js +26 -0
- package/dist/esm/cli/related.js.map +1 -0
- package/dist/esm/cli/search.js +2 -5
- package/dist/esm/cli/search.js.map +1 -1
- package/dist/esm/cli/shared.d.ts +3 -1
- package/dist/esm/cli/shared.js +28 -5
- package/dist/esm/cli/shared.js.map +1 -1
- package/dist/esm/cli/sql.d.ts +3 -0
- package/dist/esm/cli/{query.js → sql.js} +4 -4
- package/dist/esm/cli/sql.js.map +1 -0
- package/dist/esm/cli/status.js +8 -1
- package/dist/esm/cli/status.js.map +1 -1
- package/dist/esm/cli.js +13 -10
- package/dist/esm/cli.js.map +1 -1
- package/dist/esm/commands.d.ts +12 -4
- package/dist/esm/commands.js +111 -68
- package/dist/esm/commands.js.map +1 -1
- package/dist/esm/config.d.ts +6 -4
- package/dist/esm/config.js +126 -75
- package/dist/esm/config.js.map +1 -1
- package/dist/esm/db.js +16 -38
- package/dist/esm/db.js.map +1 -1
- package/dist/esm/errors.d.ts +1 -1
- package/dist/esm/errors.js.map +1 -1
- package/dist/esm/features/embed.d.ts +14 -0
- package/dist/esm/features/embed.js +110 -35
- package/dist/esm/features/embed.js.map +1 -1
- package/dist/esm/features/links.js +8 -17
- package/dist/esm/features/links.js.map +1 -1
- package/dist/esm/features/rank.js +2 -6
- package/dist/esm/features/rank.js.map +1 -1
- package/dist/esm/features/types.js.map +1 -1
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/output.js +13 -16
- package/dist/esm/output.js.map +1 -1
- package/dist/esm/progress.js +2 -4
- package/dist/esm/progress.js.map +1 -1
- package/dist/esm/scan.d.ts +1 -0
- package/dist/esm/scan.js +41 -34
- package/dist/esm/scan.js.map +1 -1
- package/dist/esm/search-error.js +4 -6
- package/dist/esm/search-error.js.map +1 -1
- package/dist/esm/traverse.d.ts +8 -0
- package/dist/esm/traverse.js +71 -0
- package/dist/esm/traverse.js.map +1 -0
- package/package.json +18 -5
- package/schema.json +12 -16
- package/skills/sense/EXAMPLES.md +13 -22
- package/skills/sense/SKILL.md +65 -140
- package/skills/sense-setup/EXAMPLES.md +30 -46
- package/skills/sense-setup/SKILL.md +22 -83
- package/dist/cjs/cli/query.d.cts +0 -3
- package/dist/cjs/cli/query.d.ts +0 -3
- package/dist/cjs/cli/query.js.map +0 -1
- package/dist/esm/cli/query.d.ts +0 -3
- package/dist/esm/cli/query.js.map +0 -1
package/dist/esm/scan.js
CHANGED
|
@@ -1,14 +1,11 @@
|
|
|
1
|
-
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
-
import { join } from 'node:path';
|
|
3
|
-
import fastGlob from 'fast-glob';
|
|
1
|
+
import { globSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { join, sep } from 'node:path';
|
|
4
3
|
import removeMarkdown from 'remove-markdown';
|
|
5
4
|
import { parseDocument } from 'yaml';
|
|
6
|
-
import { presetNames, presetSemanticEnabled } from './config.js';
|
|
5
|
+
import { embedEnabled, presetNames, presetSemanticEnabled } from './config.js';
|
|
7
6
|
// Filesystem -> rows. Pure data in, data + warnings out; db.ts does the SQL.
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
// can tell a feature-owned column (e.g. rank's `_rank`) apart from a parsed frontmatter
|
|
11
|
-
// column and leave the former alone on reparse.
|
|
7
|
+
// Frontmatter keys that would collide with table columns. Exported so db.ts's upsert can tell
|
|
8
|
+
// a feature-owned column (`_rank`) from a parsed one and leave it alone on reparse.
|
|
12
9
|
export const RESERVED_COLUMNS = new Set([
|
|
13
10
|
'path',
|
|
14
11
|
'_mtime',
|
|
@@ -22,60 +19,70 @@ function normalizeText(value) {
|
|
|
22
19
|
if (value === null || value === undefined) return '';
|
|
23
20
|
return String(value).replace(/\s+/g, ' ').trim();
|
|
24
21
|
}
|
|
25
|
-
//
|
|
26
|
-
//
|
|
22
|
+
// Keeps URL query strings, asset filenames, and HTML attributes out of the index: rare terms
|
|
23
|
+
// carry high IDF, so they outrank prose. remove-markdown misses wikilinks and tables.
|
|
27
24
|
function stripText(value) {
|
|
28
25
|
const withoutWikilinks = value.replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2').replace(/\[\[([^\]]+)\]\]/g, '$1');
|
|
29
26
|
const withoutMarkdown = removeMarkdown(withoutWikilinks);
|
|
30
27
|
const withoutTables = withoutMarkdown.replace(/^\s*\|?[-\s|:]+\|\s*$/gm, '').replace(/\|/g, ' ');
|
|
31
28
|
return normalizeText(withoutTables);
|
|
32
29
|
}
|
|
33
|
-
// Presets are
|
|
34
|
-
//
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
30
|
+
// Presets are views, not partitions: they overlap freely, and a file's covering set (not one
|
|
31
|
+
// owner) drives indexing. Globs resolve relative to baseDir; unmatched files are not indexed.
|
|
32
|
+
export function toPosixPath(relPath, separator = sep) {
|
|
33
|
+
return separator === '\\' ? relPath.split(separator).join('/') : relPath;
|
|
34
|
+
}
|
|
35
|
+
// Every command pays listFiles before it answers (the freshness check stats each file), so
|
|
36
|
+
// per-file work here is the hottest path in the package. Everything derivable from the config
|
|
37
|
+
// alone is computed once, above the loop.
|
|
38
|
+
const NO_THROW = {
|
|
39
|
+
throwIfNoEntry: false
|
|
40
|
+
};
|
|
38
41
|
export function listFiles(cfg, baseDir) {
|
|
39
42
|
const coverage = new Map();
|
|
43
|
+
const posixNeeded = sep === '\\';
|
|
40
44
|
for (const name of presetNames(cfg)){
|
|
41
|
-
var _preset_exclude;
|
|
42
45
|
const preset = cfg.presets[name];
|
|
43
|
-
const matched
|
|
46
|
+
for (const matched of globSync(preset.include, {
|
|
44
47
|
cwd: baseDir,
|
|
45
|
-
|
|
46
|
-
})
|
|
47
|
-
for (const relPath of matched){
|
|
48
|
+
exclude: preset.exclude
|
|
49
|
+
})){
|
|
48
50
|
var _coverage_get;
|
|
51
|
+
const relPath = posixNeeded ? toPosixPath(matched) : matched;
|
|
49
52
|
const set = (_coverage_get = coverage.get(relPath)) !== null && _coverage_get !== void 0 ? _coverage_get : new Set();
|
|
50
53
|
set.add(name);
|
|
51
54
|
coverage.set(relPath, set);
|
|
52
55
|
}
|
|
53
56
|
}
|
|
54
|
-
|
|
57
|
+
// Which presets want vectors is a property of the config, not of any file.
|
|
58
|
+
const embedding = embedEnabled(cfg);
|
|
59
|
+
const semanticPresets = embedding ? new Set(presetNames(cfg).filter((name)=>presetSemanticEnabled(cfg, name))) : null;
|
|
60
|
+
const files = [];
|
|
61
|
+
for (const relPath of [
|
|
55
62
|
...coverage.keys()
|
|
56
|
-
].sort()
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
63
|
+
].sort()){
|
|
64
|
+
const absPath = join(baseDir, relPath); // join re-applies the platform separator for fs calls
|
|
65
|
+
// node:fs glob matches directories and dangling symlinks; fast-glob returned neither, so
|
|
66
|
+
// one stat filters both back out (throwIfNoEntry keeps a dangling link from throwing).
|
|
67
|
+
const st = statSync(absPath, NO_THROW);
|
|
68
|
+
if (!(st === null || st === void 0 ? void 0 : st.isFile())) continue;
|
|
60
69
|
const presets = [
|
|
61
70
|
...coverage.get(relPath)
|
|
62
71
|
].sort();
|
|
63
|
-
const embed = presets.some((name)=>
|
|
64
|
-
|
|
72
|
+
const embed = semanticPresets !== null && presets.some((name)=>semanticPresets.has(name));
|
|
73
|
+
files.push({
|
|
65
74
|
relPath,
|
|
66
75
|
absPath,
|
|
67
76
|
mtimeMs: st.mtimeMs,
|
|
68
77
|
size: st.size,
|
|
69
78
|
presets,
|
|
70
79
|
embed
|
|
71
|
-
};
|
|
72
|
-
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
return files;
|
|
73
83
|
}
|
|
74
|
-
//
|
|
75
|
-
//
|
|
76
|
-
// Booleans have no SQLite type of their own; 1/0 is the convention, so `WHERE flag = 1`
|
|
77
|
-
// matches and `WHERE flag = 'true'` cannot -- `map` prints the observed type per field so
|
|
78
|
-
// that mismatch is visible rather than a silent zero-row answer.
|
|
84
|
+
// Storage class follows the YAML scalar. Booleans store as 1/0, so `WHERE flag = 1` matches
|
|
85
|
+
// and `WHERE flag = 'true'` cannot; `map` prints observed types so the mismatch is visible.
|
|
79
86
|
function mapValue(value) {
|
|
80
87
|
if (value === null || value === undefined) return null;
|
|
81
88
|
if (typeof value === 'boolean') return BigInt(value ? 1 : 0);
|
package/dist/esm/scan.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/scan.ts"],"sourcesContent":["import { readFileSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\nimport fastGlob from 'fast-glob';\nimport removeMarkdown from 'remove-markdown';\nimport { parseDocument } from 'yaml';\nimport type { Config } from './config.ts';\nimport { presetNames, presetSemanticEnabled } from './config.ts';\nimport type { Feature } from './features/types.ts';\n\n// Filesystem -> rows. Pure data in, data + warnings out; db.ts does the SQL.\n\n// Reserved: colliding with these would clash with the `frontmatter` table's own columns or\n// the other tables (`content`, `links`, `sections`). Exported so db.ts's frontmatter upsert\n// can tell a feature-owned column (e.g. rank's `_rank`) apart from a parsed frontmatter\n// column and leave the former alone on reparse.\nexport const RESERVED_COLUMNS = new Set(['path', '_mtime', '_size', '_rank', 'content', 'links', 'sections']);\n\nfunction normalizeText(value: unknown): string {\n if (value === null || value === undefined) return '';\n return String(value).replace(/\\s+/g, ' ').trim();\n}\n\n// Markdown is stripped at index time so snippets read as clean prose (also improves matching, e.g. `**bold**` indexes as `bold`).\n// remove-markdown doesn't cover Obsidian wikilinks or table scaffolding, so those are handled first/after.\nfunction stripText(value: string): string {\n const withoutWikilinks = value.replace(/\\[\\[([^\\]|]+)\\|([^\\]]+)\\]\\]/g, '$2').replace(/\\[\\[([^\\]]+)\\]\\]/g, '$1');\n const withoutMarkdown = removeMarkdown(withoutWikilinks);\n const withoutTables = withoutMarkdown.replace(/^\\s*\\|?[-\\s|:]+\\|\\s*$/gm, '').replace(/\\|/g, ' ');\n return normalizeText(withoutTables);\n}\n\nexport interface FileStat {\n relPath: string;\n absPath: string;\n mtimeMs: number;\n size: number;\n presets: string[]; // every declared preset covering this file (>= 1; union, overlap allowed)\n embed: boolean; // true iff any covering preset has semantic !== false\n}\n\n// Presets are the file selection: each preset's include/exclude picks its files (fast-glob,\n// tsconfig-standard semantics, resolved relative to baseDir). Unlike the old layer model,\n// presets are views, not partitions -- they may overlap freely, and a file's set of covering\n// presets (not a single owner) is what indexing and embedding derive from. A preset whose\n// globs match nothing is valid. Files matched by no preset at all are simply not indexed.\nexport function listFiles(cfg: Config, baseDir: string): FileStat[] {\n const coverage = new Map<string, Set<string>>();\n for (const name of presetNames(cfg)) {\n const preset = cfg.presets[name];\n const matched = fastGlob.sync(preset.include, { cwd: baseDir, ignore: preset.exclude ?? [] });\n for (const relPath of matched) {\n const set = coverage.get(relPath) ?? new Set<string>();\n set.add(name);\n coverage.set(relPath, set);\n }\n }\n\n const relPaths = [...coverage.keys()].sort();\n return relPaths.map((relPath) => {\n const absPath = join(baseDir, relPath);\n const st = statSync(absPath);\n const presets = [...(coverage.get(relPath) as Set<string>)].sort();\n const embed = presets.some((name) => presetSemanticEnabled(cfg, name));\n return { relPath, absPath, mtimeMs: st.mtimeMs, size: st.size, presets, embed };\n });\n}\n\nexport interface ParsedDoc {\n relPath: string;\n mtimeMs: number;\n size: number;\n presets: string[];\n data: Record<string, string | number | bigint | null>;\n // title/summary are duplicated from frontmatter so bm25() can weight them above the body text.\n search: { title: string; summary: string; text: string };\n // Per-feature extraction results, keyed by feature name; features store them at reconcile.\n extracted: Record<string, unknown>;\n}\n\n// SQLite storage classes follow the YAML scalar: strings -> TEXT, booleans and whole\n// numbers -> INTEGER, fractions -> REAL, everything else (lists, maps) -> JSON TEXT.\n// Booleans have no SQLite type of their own; 1/0 is the convention, so `WHERE flag = 1`\n// matches and `WHERE flag = 'true'` cannot -- `map` prints the observed type per field so\n// that mismatch is visible rather than a silent zero-row answer.\nfunction mapValue(value: unknown): string | number | bigint | null {\n if (value === null || value === undefined) return null;\n if (typeof value === 'boolean') return BigInt(value ? 1 : 0);\n if (typeof value === 'number') return Number.isSafeInteger(value) ? BigInt(value) : value;\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n}\n\n// The delimiter split is all this package used gray-matter for.\nfunction splitFrontmatter(raw: string): { fm: string | null; body: string } {\n const open = raw.match(/^---\\r?\\n/);\n if (!open) return { fm: null, body: raw };\n const rest = raw.slice(open[0].length);\n const close = rest.match(/^---\\r?(\\n|$)/m);\n if (!close || close.index === undefined) return { fm: null, body: raw };\n return { fm: rest.slice(0, close.index), body: rest.slice(close.index + close[0].length) };\n}\n\n// Lenient by design: parseDocument collects syntax errors as data and still yields values,\n// so Obsidian-style frontmatter (e.g. an alias starting with @) survives with a warning.\nfunction parseFrontmatter(relPath: string, fm: string, warnings: string[]): Record<string, unknown> {\n const doc = parseDocument(fm);\n if (doc.errors.length > 0) {\n warnings.push(`warning: ${relPath} frontmatter has ${doc.errors.length} syntax error(s) (${doc.errors[0].message.split('\\n')[0]}); parsed leniently`);\n }\n let data: unknown;\n try {\n data = doc.toJS();\n } catch (err) {\n warnings.push(`warning: ${relPath} has unparseable frontmatter (${(err as Error).message.split('\\n')[0]}); indexing without it`);\n return {};\n }\n if (data === null || data === undefined) return {};\n if (typeof data !== 'object' || Array.isArray(data)) {\n warnings.push(`warning: ${relPath} frontmatter is not a key-value mapping; ignoring it`);\n return {};\n }\n return data as Record<string, unknown>;\n}\n\nexport function parseFile(file: FileStat, extractors: Feature[] = []): { doc: ParsedDoc; warnings: string[] } {\n const raw = readFileSync(file.absPath, 'utf8');\n const warnings: string[] = [];\n\n const { fm, body: content } = splitFrontmatter(raw);\n const data = fm === null ? {} : parseFrontmatter(file.relPath, fm, warnings);\n const mapped: Record<string, string | number | bigint | null> = {};\n\n for (const key of Object.keys(data)) {\n if (RESERVED_COLUMNS.has(key)) {\n warnings.push(`warning: ${file.relPath} has a frontmatter key named \"${key}\", which is reserved; ignoring it`);\n continue;\n }\n mapped[key] = mapValue(data[key]);\n }\n\n // title/summary are plain YAML strings -- whitespace-collapse only;\n // the prose gets the full markdown strip.\n const search = { title: normalizeText(data.title), summary: normalizeText(data.summary), text: stripText(content) };\n\n return {\n doc: {\n relPath: file.relPath,\n mtimeMs: file.mtimeMs,\n size: file.size,\n presets: file.presets,\n data: mapped,\n search,\n extracted: Object.fromEntries(extractors.filter((f) => f.extract).map((f) => [f.name, f.extract?.(raw, content, search)])),\n },\n warnings,\n };\n}\n"],"names":["readFileSync","statSync","join","fastGlob","removeMarkdown","parseDocument","presetNames","presetSemanticEnabled","RESERVED_COLUMNS","Set","normalizeText","value","undefined","String","replace","trim","stripText","withoutWikilinks","withoutMarkdown","withoutTables","listFiles","cfg","baseDir","coverage","Map","name","preset","presets","matched","sync","include","cwd","ignore","exclude","relPath","set","get","add","relPaths","keys","sort","map","absPath","st","embed","some","mtimeMs","size","mapValue","BigInt","Number","isSafeInteger","JSON","stringify","splitFrontmatter","raw","open","match","fm","body","rest","slice","length","close","index","parseFrontmatter","warnings","doc","errors","push","message","split","data","toJS","err","Array","isArray","parseFile","file","extractors","content","mapped","key","Object","has","search","title","summary","text","extracted","fromEntries","filter","f","extract"],"mappings":"AAAA,SAASA,YAAY,EAAEC,QAAQ,QAAQ,UAAU;AACjD,SAASC,IAAI,QAAQ,YAAY;AACjC,OAAOC,cAAc,YAAY;AACjC,OAAOC,oBAAoB,kBAAkB;AAC7C,SAASC,aAAa,QAAQ,OA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AEjE,KAAK,MAAMC,OAAOC,OAAO5C,IAAI,CAACiC,MAAO;QACnC,IAAIhE,iBAAiB4E,GAAG,CAACF,MAAM;YAC7BhB,SAASG,IAAI,CAAC,CAAC,SAAS,EAAES,KAAK5C,OAAO,CAAC,8BAA8B,EAAEgD,IAAI,iCAAiC,CAAC;YAC7G;QACF;QACAD,MAAM,CAACC,IAAI,GAAGlC,SAASwB,IAAI,CAACU,IAAI;IAClC;IAEA,oEAAoE;IACpE,0CAA0C;IAC1C,MAAMG,SAAS;QAAEC,OAAO5E,cAAc8D,KAAKc,KAAK;QAAGC,SAAS7E,cAAc8D,KAAKe,OAAO;QAAGC,MAAMxE,UAAUgE;IAAS;IAElH,OAAO;QACLb,KAAK;YACHjC,SAAS4C,KAAK5C,OAAO;YACrBY,SAASgC,KAAKhC,OAAO;YACrBC,MAAM+B,KAAK/B,IAAI;YACfpB,SAASmD,KAAKnD,OAAO;YACrB6C,MAAMS;YACNI;YACAI,WAAWN,OAAOO,WAAW,CAACX,WAAWY,MAAM,CAAC,CAACC,IAAMA,EAAEC,OAAO,EAAEpD,GAAG,CAAC,CAACmD;oBAAeA;uBAAT;oBAACA,EAAEnE,IAAI;qBAAEmE,aAAAA,EAAEC,OAAO,cAATD,iCAAAA,gBAAAA,GAAYrC,KAAKyB,SAASK;iBAAQ;;QAC1H;QACAnB;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/scan.ts"],"sourcesContent":["import { globSync, readFileSync, statSync } from 'node:fs';\nimport { join, sep } from 'node:path';\nimport removeMarkdown from 'remove-markdown';\nimport { parseDocument } from 'yaml';\nimport type { Config } from './config.ts';\nimport { embedEnabled, presetNames, presetSemanticEnabled } from './config.ts';\nimport type { Feature } from './features/types.ts';\n\n// Filesystem -> rows. Pure data in, data + warnings out; db.ts does the SQL.\n\n// Frontmatter keys that would collide with table columns. Exported so db.ts's upsert can tell\n// a feature-owned column (`_rank`) from a parsed one and leave it alone on reparse.\nexport const RESERVED_COLUMNS = new Set(['path', '_mtime', '_size', '_rank', 'content', 'links', 'sections']);\n\nfunction normalizeText(value: unknown): string {\n if (value === null || value === undefined) return '';\n return String(value).replace(/\\s+/g, ' ').trim();\n}\n\n// Keeps URL query strings, asset filenames, and HTML attributes out of the index: rare terms\n// carry high IDF, so they outrank prose. remove-markdown misses wikilinks and tables.\nfunction stripText(value: string): string {\n const withoutWikilinks = value.replace(/\\[\\[([^\\]|]+)\\|([^\\]]+)\\]\\]/g, '$2').replace(/\\[\\[([^\\]]+)\\]\\]/g, '$1');\n const withoutMarkdown = removeMarkdown(withoutWikilinks);\n const withoutTables = withoutMarkdown.replace(/^\\s*\\|?[-\\s|:]+\\|\\s*$/gm, '').replace(/\\|/g, ' ');\n return normalizeText(withoutTables);\n}\n\nexport interface FileStat {\n relPath: string;\n absPath: string;\n mtimeMs: number;\n size: number;\n presets: string[]; // every declared preset covering this file (>= 1; union, overlap allowed)\n embed: boolean; // true iff a model is named and some covering preset has semantic on\n}\n\n// Presets are views, not partitions: they overlap freely, and a file's covering set (not one\n// owner) drives indexing. Globs resolve relative to baseDir; unmatched files are not indexed.\nexport function toPosixPath(relPath: string, separator: string = sep): string {\n return separator === '\\\\' ? relPath.split(separator).join('/') : relPath;\n}\n\n// Every command pays listFiles before it answers (the freshness check stats each file), so\n// per-file work here is the hottest path in the package. Everything derivable from the config\n// alone is computed once, above the loop.\nconst NO_THROW = { throwIfNoEntry: false } as const;\n\nexport function listFiles(cfg: Config, baseDir: string): FileStat[] {\n const coverage = new Map<string, Set<string>>();\n const posixNeeded = sep === '\\\\';\n for (const name of presetNames(cfg)) {\n const preset = cfg.presets[name];\n for (const matched of globSync(preset.include, { cwd: baseDir, exclude: preset.exclude })) {\n const relPath = posixNeeded ? toPosixPath(matched) : matched;\n const set = coverage.get(relPath) ?? new Set<string>();\n set.add(name);\n coverage.set(relPath, set);\n }\n }\n\n // Which presets want vectors is a property of the config, not of any file.\n const embedding = embedEnabled(cfg);\n const semanticPresets = embedding ? new Set(presetNames(cfg).filter((name) => presetSemanticEnabled(cfg, name))) : null;\n\n const files: FileStat[] = [];\n for (const relPath of [...coverage.keys()].sort()) {\n const absPath = join(baseDir, relPath); // join re-applies the platform separator for fs calls\n // node:fs glob matches directories and dangling symlinks; fast-glob returned neither, so\n // one stat filters both back out (throwIfNoEntry keeps a dangling link from throwing).\n const st = statSync(absPath, NO_THROW);\n if (!st?.isFile()) continue;\n const presets = [...(coverage.get(relPath) as Set<string>)].sort();\n const embed = semanticPresets !== null && presets.some((name) => semanticPresets.has(name));\n files.push({ relPath, absPath, mtimeMs: st.mtimeMs, size: st.size, presets, embed });\n }\n return files;\n}\n\nexport interface ParsedDoc {\n relPath: string;\n mtimeMs: number;\n size: number;\n presets: string[];\n data: Record<string, string | number | bigint | null>;\n // title/summary are duplicated from frontmatter so bm25() can weight them above the body text.\n search: { title: string; summary: string; text: string };\n // Per-feature extraction results, keyed by feature name; features store them at reconcile.\n extracted: Record<string, unknown>;\n}\n\n// Storage class follows the YAML scalar. Booleans store as 1/0, so `WHERE flag = 1` matches\n// and `WHERE flag = 'true'` cannot; `map` prints observed types so the mismatch is visible.\nfunction mapValue(value: unknown): string | number | bigint | null {\n if (value === null || value === undefined) return null;\n if (typeof value === 'boolean') return BigInt(value ? 1 : 0);\n if (typeof value === 'number') return Number.isSafeInteger(value) ? BigInt(value) : value;\n if (typeof value === 'string') return value;\n return JSON.stringify(value);\n}\n\n// The delimiter split is all this package used gray-matter for.\nfunction splitFrontmatter(raw: string): { fm: string | null; body: string } {\n const open = raw.match(/^---\\r?\\n/);\n if (!open) return { fm: null, body: raw };\n const rest = raw.slice(open[0].length);\n const close = rest.match(/^---\\r?(\\n|$)/m);\n if (!close || close.index === undefined) return { fm: null, body: raw };\n return { fm: rest.slice(0, close.index), body: rest.slice(close.index + close[0].length) };\n}\n\n// Lenient by design: parseDocument collects syntax errors as data and still yields values,\n// so Obsidian-style frontmatter (e.g. an alias starting with @) survives with a warning.\nfunction parseFrontmatter(relPath: string, fm: string, warnings: string[]): Record<string, unknown> {\n const doc = parseDocument(fm);\n if (doc.errors.length > 0) {\n warnings.push(`warning: ${relPath} frontmatter has ${doc.errors.length} syntax error(s) (${doc.errors[0].message.split('\\n')[0]}); parsed leniently`);\n }\n let data: unknown;\n try {\n data = doc.toJS();\n } catch (err) {\n warnings.push(`warning: ${relPath} has unparseable frontmatter (${(err as Error).message.split('\\n')[0]}); indexing without it`);\n return {};\n }\n if (data === null || data === undefined) return {};\n if (typeof data !== 'object' || Array.isArray(data)) {\n warnings.push(`warning: ${relPath} frontmatter is not a key-value mapping; ignoring it`);\n return {};\n }\n return data as Record<string, unknown>;\n}\n\nexport function parseFile(file: FileStat, extractors: Feature[] = []): { doc: ParsedDoc; warnings: string[] } {\n const raw = readFileSync(file.absPath, 'utf8');\n const warnings: string[] = [];\n\n const { fm, body: content } = splitFrontmatter(raw);\n const data = fm === null ? {} : parseFrontmatter(file.relPath, fm, warnings);\n const mapped: Record<string, string | number | bigint | null> = {};\n\n for (const key of Object.keys(data)) {\n if (RESERVED_COLUMNS.has(key)) {\n warnings.push(`warning: ${file.relPath} has a frontmatter key named \"${key}\", which is reserved; ignoring it`);\n continue;\n }\n mapped[key] = mapValue(data[key]);\n }\n\n // title/summary are plain YAML strings -- whitespace-collapse only;\n // the prose gets the full markdown strip.\n const search = { title: normalizeText(data.title), summary: normalizeText(data.summary), text: stripText(content) };\n\n return {\n doc: {\n relPath: file.relPath,\n mtimeMs: file.mtimeMs,\n size: file.size,\n presets: file.presets,\n data: mapped,\n search,\n extracted: Object.fromEntries(extractors.filter((f) => f.extract).map((f) => [f.name, f.extract?.(raw, content, search)])),\n },\n warnings,\n };\n}\n"],"names":["globSync","readFileSync","statSync","join","sep","removeMarkdown","parseDocument","embedEnabled","presetNames","presetSemanticEnabled","RESERVED_COLUMNS","Set","normalizeText","value","undefined","String","replace","trim","stripText","withoutWikilinks","withoutMarkdown","withoutTables","toPosixPath","relPath","separator","split","NO_THROW","throwIfNoEntry","listFiles","cfg","baseDir","coverage","Map","posixNeeded","name","preset","presets","matched","include","cwd","exclude","set","get","add","embedding","semanticPresets","filter","files","keys","sort","absPath","st","isFile","embed","some","has","push","mtimeMs","size","mapValue","BigInt","Number","isSafeInteger","JSON","stringify","splitFrontmatter","raw","open","match","fm","body","rest","slice","length","close","index","parseFrontmatter","warnings","doc","errors","message","data","toJS","err","Array","isArray","parseFile","file","extractors","content","mapped","key","Object","search","title","summary","text","extracted","fromEntries","f","extract","map"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,YAAY,EAAEC,QAAQ,QAAQ,UAAU;AAC3D,SAASC,IAAI,EAAEC,GAAG,QAAQ,YAAY;AACtC,OAAOC,oBAAoB,kBAAkB;AAC7C,SAASC,aAAa,QAAQ,OAAO;AAErC,SAASC,YAAY,EAAEC,WAAW,EAAEC,qBAAqB,QAAQ,cAAc;AAG/E,6EAA6E;AAE7E,8FAA8F;AAC9F,oFAAoF;AACpF,OAAO,MAAMC,mBAAmB,IAAIC,IAAI;IAAC;IAAQ;IAAU;IAAS;IAAS;IAAW;IAAS;CAAW,EAAE;AAE9G,SAASC,cAAcC,KAAc;IACnC,IAAIA,UAAU,QAAQA,UAAUC,WAAW,OAAO;IAClD,OAAOC,OAAOF,OAAOG,OAAO,CAAC,QAAQ,KAAKC,IAAI;AAChD;AAEA,6FAA6F;AAC7F,sFAAsF;AACtF,SAASC,UAAUL,KAAa;IAC9B,MAAMM,mBAAmBN,MAAMG,OAAO,CAAC,gCAAgC,MAAMA,OAAO,CAAC,qBAAqB;IAC1G,MAAMI,kBAAkBf,eAAec;IACvC,MAAME,gBAAgBD,gBAAgBJ,OAAO,CAAC,2BAA2B,IAAIA,OAAO,CAAC,OAAO;IAC5F,OAAOJ,cAAcS;AACvB;AAWA,6FAA6F;AAC7F,8FAA8F;AAC9F,OAAO,SAASC,YAAYC,OAAe,EAAEC,YAAoBpB,GAAG;IAClE,OAAOoB,cAAc,OAAO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oE;IACpE,0CAA0C;IAC1C,MAAME,SAAS;QAAEC,OAAOlF,cAAcqE,KAAKa,KAAK;QAAGC,SAASnF,cAAcqE,KAAKc,OAAO;QAAGC,MAAM9E,UAAUuE;IAAS;IAElH,OAAO;QACLX,KAAK;YACHvD,SAASgE,KAAKhE,OAAO;YACrBkC,SAAS8B,KAAK9B,OAAO;YACrBC,MAAM6B,KAAK7B,IAAI;YACftB,SAASmD,KAAKnD,OAAO;YACrB6C,MAAMS;YACNG;YACAI,WAAWL,OAAOM,WAAW,CAACV,WAAW1C,MAAM,CAAC,CAACqD,IAAMA,EAAEC,OAAO,EAAEC,GAAG,CAAC,CAACF;oBAAeA;uBAAT;oBAACA,EAAEjE,IAAI;qBAAEiE,aAAAA,EAAEC,OAAO,cAATD,iCAAAA,gBAAAA,GAAYjC,KAAKuB,SAASI;iBAAQ;;QAC1H;QACAhB;IACF;AACF"}
|
package/dist/esm/search-error.js
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { SenseError } from './errors.js';
|
|
2
|
-
// FTS5 reads these as operators, so
|
|
3
|
-
//
|
|
4
|
-
// reports `no such column: to`, which is a true statement about the parse and a false
|
|
5
|
-
// one about the input. Both field reports on 0.6.0 misdiagnosed that message.
|
|
2
|
+
// FTS5 reads these as operators, so `end-to-end` parses as a filter on column `to` and errors
|
|
3
|
+
// `no such column: to` -- true about the parse, misleading about the input.
|
|
6
4
|
const FTS5_OPERATORS = /[-'"/.:^*()]/;
|
|
7
5
|
export function searchError(err, terms, scope) {
|
|
8
6
|
var _terms_match;
|
|
@@ -19,7 +17,7 @@ export function searchError(err, terms, scope) {
|
|
|
19
17
|
return new SenseError('SEARCH_SYNTAX', `${message} -- the punctuation in ${suspects.map((t)=>`\`${t}\``).join(', ')} is FTS5 syntax, not literal text; search for it literally by double-quoting: '"${suspects[0]}"'. Searchable columns are title, summary, text.`);
|
|
20
18
|
}
|
|
21
19
|
if (col !== undefined && scope !== undefined) {
|
|
22
|
-
return new SenseError('SEARCH_SYNTAX', `${message} -- the where condition (${scope}) references it; frontmatter columns are listed by sense
|
|
20
|
+
return new SenseError('SEARCH_SYNTAX', `${message} -- the where condition (${scope}) references it; frontmatter columns are listed by sense sql "SELECT name FROM pragma_table_info('frontmatter')".`);
|
|
23
21
|
}
|
|
24
|
-
return new SenseError('SEARCH_SYNTAX', `${message} -- searchable columns are title, summary, text; frontmatter fields are queried with --where or sense
|
|
22
|
+
return new SenseError('SEARCH_SYNTAX', `${message} -- searchable columns are title, summary, text; frontmatter fields are queried with --where or sense sql (list them with pragma_table_info('frontmatter')).`);
|
|
25
23
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/search-error.ts"],"sourcesContent":["import { SenseError } from './errors.ts';\n\n// FTS5 reads these as operators, so
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/search-error.ts"],"sourcesContent":["import { SenseError } from './errors.ts';\n\n// FTS5 reads these as operators, so `end-to-end` parses as a filter on column `to` and errors\n// `no such column: to` -- true about the parse, misleading about the input.\nconst FTS5_OPERATORS = /[-'\"/.:^*()]/;\n\nexport function searchError(err: Error, terms: string, scope?: string): Error {\n const message = err.message;\n if (!/no such column|fts5: syntax error|malformed MATCH/.test(message)) return err;\n const suspects = (terms.match(/\\S+/g) ?? []).filter((t) => !t.startsWith('\"') && FTS5_OPERATORS.test(t));\n // Blame the terms only when the failing token actually came from one -- a typo'd column\n // in --where (or the tree's default scope) raises \"no such column\" through this same\n // statement, and naming a term for it would state a false fact about the input.\n const col = /no such column: (\\S+)/.exec(message)?.[1];\n const fromTerms = col === undefined ? suspects.length > 0 : suspects.some((t) => t.split(/[^\\p{L}\\p{N}]+/u).includes(col));\n if (fromTerms && suspects.length > 0) {\n return new SenseError('SEARCH_SYNTAX', `${message} -- the punctuation in ${suspects.map((t) => `\\`${t}\\``).join(', ')} is FTS5 syntax, not literal text; search for it literally by double-quoting: '\"${suspects[0]}\"'. Searchable columns are title, summary, text.`);\n }\n if (col !== undefined && scope !== undefined) {\n return new SenseError('SEARCH_SYNTAX', `${message} -- the where condition (${scope}) references it; frontmatter columns are listed by sense sql \"SELECT name FROM pragma_table_info('frontmatter')\".`);\n }\n return new SenseError('SEARCH_SYNTAX', `${message} -- searchable columns are title, summary, text; frontmatter fields are queried with --where or sense sql (list them with pragma_table_info('frontmatter')).`);\n}\n"],"names":["SenseError","FTS5_OPERATORS","searchError","err","terms","scope","message","test","suspects","match","filter","t","startsWith","col","exec","fromTerms","undefined","length","some","split","includes","map","join"],"mappings":"AAAA,SAASA,UAAU,QAAQ,cAAc;AAEzC,8FAA8F;AAC9F,4EAA4E;AAC5E,MAAMC,iBAAiB;AAEvB,OAAO,SAASC,YAAYC,GAAU,EAAEC,KAAa,EAAEC,KAAc;QAGjDD;QAIN;IANZ,MAAME,UAAUH,IAAIG,OAAO;IAC3B,IAAI,CAAC,oDAAoDC,IAAI,CAACD,UAAU,OAAOH;IAC/E,MAAMK,WAAW,EAACJ,eAAAA,MAAMK,KAAK,CAAC,qBAAZL,0BAAAA,eAAuB,EAAE,EAAEM,MAAM,CAAC,CAACC,IAAM,CAACA,EAAEC,UAAU,CAAC,QAAQX,eAAeM,IAAI,CAACI;IACrG,wFAAwF;IACxF,qFAAqF;IACrF,gFAAgF;IAChF,MAAME,OAAM,QAAA,wBAAwBC,IAAI,CAACR,sBAA7B,4BAAA,KAAuC,CAAC,EAAE;IACtD,MAAMS,YAAYF,QAAQG,YAAYR,SAASS,MAAM,GAAG,IAAIT,SAASU,IAAI,CAAC,CAACP,IAAMA,EAAEQ,KAAK,CAAC,mBAAmBC,QAAQ,CAACP;IACrH,IAAIE,aAAaP,SAASS,MAAM,GAAG,GAAG;QACpC,OAAO,IAAIjB,WAAW,iBAAiB,GAAGM,QAAQ,uBAAuB,EAAEE,SAASa,GAAG,CAAC,CAACV,IAAM,CAAC,EAAE,EAAEA,EAAE,EAAE,CAAC,EAAEW,IAAI,CAAC,MAAM,gFAAgF,EAAEd,QAAQ,CAAC,EAAE,CAAC,gDAAgD,CAAC;IACvQ;IACA,IAAIK,QAAQG,aAAaX,UAAUW,WAAW;QAC5C,OAAO,IAAIhB,WAAW,iBAAiB,GAAGM,QAAQ,yBAAyB,EAAED,MAAM,iHAAiH,CAAC;IACvM;IACA,OAAO,IAAIL,WAAW,iBAAiB,GAAGM,QAAQ,4JAA4J,CAAC;AACjN"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { DatabaseSync } from 'node:sqlite';
|
|
2
|
+
interface FindPathOptions {
|
|
3
|
+
directed?: boolean;
|
|
4
|
+
maxDepth?: number;
|
|
5
|
+
allowed?: Set<string>;
|
|
6
|
+
}
|
|
7
|
+
export declare function findPath(db: DatabaseSync, from: string, to: string, opts?: FindPathOptions): string[] | null;
|
|
8
|
+
export {};
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Frontier-by-frontier BFS through a temp visited table, one indexed anti-join per ring: a
|
|
2
|
+
// local question touches a neighborhood, never the whole edge list.
|
|
3
|
+
function resetVisited(db) {
|
|
4
|
+
db.exec('DROP TABLE IF EXISTS temp.visited');
|
|
5
|
+
db.exec('CREATE TEMP TABLE visited (path TEXT PRIMARY KEY, depth INTEGER NOT NULL, pred TEXT)');
|
|
6
|
+
}
|
|
7
|
+
// Materializes the caller-resolved scope Set into a temp table so it joins like any other
|
|
8
|
+
// indexed column. `extra`, when given, is always in scope -- findPath's `to` endpoint.
|
|
9
|
+
function setupAllowed(db, allowed, extra) {
|
|
10
|
+
db.exec('DROP TABLE IF EXISTS temp.allowed_nodes');
|
|
11
|
+
db.exec('CREATE TEMP TABLE allowed_nodes (path TEXT PRIMARY KEY)');
|
|
12
|
+
db.prepare('INSERT INTO allowed_nodes SELECT DISTINCT value FROM json_each(?1)').run(JSON.stringify([
|
|
13
|
+
...allowed
|
|
14
|
+
]));
|
|
15
|
+
if (extra !== undefined) db.prepare('INSERT OR IGNORE INTO allowed_nodes VALUES (?)').run(extra);
|
|
16
|
+
}
|
|
17
|
+
// Only resolved links (dst IS NOT NULL) are followed, in either direction.
|
|
18
|
+
function candidateSelect(direction) {
|
|
19
|
+
const forward = 'SELECT l.dst AS path, l.src AS pred FROM links l JOIN visited v ON v.path = l.src AND v.depth = ?1 WHERE l.dst IS NOT NULL';
|
|
20
|
+
const reverse = 'SELECT l.src AS path, l.dst AS pred FROM links l JOIN visited v ON v.path = l.dst AND v.depth = ?1 WHERE l.dst IS NOT NULL';
|
|
21
|
+
if (direction === 'forward') return forward;
|
|
22
|
+
if (direction === 'reverse') return reverse;
|
|
23
|
+
return `${forward} UNION ALL ${reverse}`;
|
|
24
|
+
}
|
|
25
|
+
// One ring: candidates adjacent to the previous ring's frontier (?1), anti-joined against
|
|
26
|
+
// everything already visited, optionally filtered to the allowed set, capped (?3) and
|
|
27
|
+
// inserted at the new depth (?2). RETURNING hands back exactly what this ring newly reached.
|
|
28
|
+
function ringSql(direction, hasAllowed) {
|
|
29
|
+
return `
|
|
30
|
+
INSERT INTO visited (path, depth, pred)
|
|
31
|
+
SELECT cand.path, ?2, MIN(cand.pred)
|
|
32
|
+
FROM (${candidateSelect(direction)}) cand
|
|
33
|
+
WHERE NOT EXISTS (SELECT 1 FROM visited v2 WHERE v2.path = cand.path)
|
|
34
|
+
${hasAllowed ? 'AND EXISTS (SELECT 1 FROM allowed_nodes a WHERE a.path = cand.path)' : ''}
|
|
35
|
+
GROUP BY cand.path
|
|
36
|
+
ORDER BY cand.path
|
|
37
|
+
LIMIT ?3
|
|
38
|
+
RETURNING path`;
|
|
39
|
+
}
|
|
40
|
+
function reconstructPath(db, to) {
|
|
41
|
+
const lookup = db.prepare('SELECT pred FROM visited WHERE path = ?');
|
|
42
|
+
const path = [];
|
|
43
|
+
let cur = to;
|
|
44
|
+
while(cur !== null){
|
|
45
|
+
path.push(cur);
|
|
46
|
+
const row = lookup.get(cur);
|
|
47
|
+
cur = row ? row.pred : null;
|
|
48
|
+
}
|
|
49
|
+
return path.reverse();
|
|
50
|
+
}
|
|
51
|
+
// One BFS from `from`, tracking a predecessor per node. Undirected by default, matching
|
|
52
|
+
// personalizedRank; null when `to` is unreached within `maxDepth`.
|
|
53
|
+
export function findPath(db, from, to, opts = {}) {
|
|
54
|
+
var _opts_maxDepth;
|
|
55
|
+
if (from === to) return [
|
|
56
|
+
from
|
|
57
|
+
];
|
|
58
|
+
const direction = opts.directed ? 'forward' : 'both';
|
|
59
|
+
const maxDepth = (_opts_maxDepth = opts.maxDepth) !== null && _opts_maxDepth !== void 0 ? _opts_maxDepth : Infinity;
|
|
60
|
+
if (maxDepth <= 0) return null;
|
|
61
|
+
resetVisited(db);
|
|
62
|
+
db.prepare('INSERT INTO visited (path, depth, pred) VALUES (?, 0, NULL)').run(from);
|
|
63
|
+
if (opts.allowed) setupAllowed(db, opts.allowed, to);
|
|
64
|
+
const stmt = db.prepare(ringSql(direction, !!opts.allowed));
|
|
65
|
+
for(let ring = 1; ring <= maxDepth; ring++){
|
|
66
|
+
const rows = stmt.all(ring - 1, ring, -1);
|
|
67
|
+
if (rows.length === 0) break;
|
|
68
|
+
if (rows.some((row)=>row.path === to)) return reconstructPath(db, to);
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/traverse.ts"],"sourcesContent":["// Frontier-by-frontier BFS through a temp visited table, one indexed anti-join per ring: a\n// local question touches a neighborhood, never the whole edge list.\nimport type { DatabaseSync } from 'node:sqlite';\n\ntype Direction = 'forward' | 'reverse' | 'both';\n\ninterface FindPathOptions {\n directed?: boolean;\n maxDepth?: number;\n allowed?: Set<string>;\n}\n\nfunction resetVisited(db: DatabaseSync): void {\n db.exec('DROP TABLE IF EXISTS temp.visited');\n db.exec('CREATE TEMP TABLE visited (path TEXT PRIMARY KEY, depth INTEGER NOT NULL, pred TEXT)');\n}\n\n// Materializes the caller-resolved scope Set into a temp table so it joins like any other\n// indexed column. `extra`, when given, is always in scope -- findPath's `to` endpoint.\nfunction setupAllowed(db: DatabaseSync, allowed: Set<string>, extra?: string): void {\n db.exec('DROP TABLE IF EXISTS temp.allowed_nodes');\n db.exec('CREATE TEMP TABLE allowed_nodes (path TEXT PRIMARY KEY)');\n db.prepare('INSERT INTO allowed_nodes SELECT DISTINCT value FROM json_each(?1)').run(JSON.stringify([...allowed]));\n if (extra !== undefined) db.prepare('INSERT OR IGNORE INTO allowed_nodes VALUES (?)').run(extra);\n}\n\n// Only resolved links (dst IS NOT NULL) are followed, in either direction.\nfunction candidateSelect(direction: Direction): string {\n const forward = 'SELECT l.dst AS path, l.src AS pred FROM links l JOIN visited v ON v.path = l.src AND v.depth = ?1 WHERE l.dst IS NOT NULL';\n const reverse = 'SELECT l.src AS path, l.dst AS pred FROM links l JOIN visited v ON v.path = l.dst AND v.depth = ?1 WHERE l.dst IS NOT NULL';\n if (direction === 'forward') return forward;\n if (direction === 'reverse') return reverse;\n return `${forward} UNION ALL ${reverse}`;\n}\n\n// One ring: candidates adjacent to the previous ring's frontier (?1), anti-joined against\n// everything already visited, optionally filtered to the allowed set, capped (?3) and\n// inserted at the new depth (?2). RETURNING hands back exactly what this ring newly reached.\nfunction ringSql(direction: Direction, hasAllowed: boolean): string {\n return `\nINSERT INTO visited (path, depth, pred)\nSELECT cand.path, ?2, MIN(cand.pred)\nFROM (${candidateSelect(direction)}) cand\nWHERE NOT EXISTS (SELECT 1 FROM visited v2 WHERE v2.path = cand.path)\n${hasAllowed ? 'AND EXISTS (SELECT 1 FROM allowed_nodes a WHERE a.path = cand.path)' : ''}\nGROUP BY cand.path\nORDER BY cand.path\nLIMIT ?3\nRETURNING path`;\n}\n\nfunction reconstructPath(db: DatabaseSync, to: string): string[] {\n const lookup = db.prepare('SELECT pred FROM visited WHERE path = ?');\n const path: string[] = [];\n let cur: string | null = to;\n while (cur !== null) {\n path.push(cur);\n const row = lookup.get(cur) as { pred: string | null } | undefined;\n cur = row ? row.pred : null;\n }\n return path.reverse();\n}\n\n// One BFS from `from`, tracking a predecessor per node. Undirected by default, matching\n// personalizedRank; null when `to` is unreached within `maxDepth`.\nexport function findPath(db: DatabaseSync, from: string, to: string, opts: FindPathOptions = {}): string[] | null {\n if (from === to) return [from];\n\n const direction: Direction = opts.directed ? 'forward' : 'both';\n const maxDepth = opts.maxDepth ?? Infinity;\n if (maxDepth <= 0) return null;\n\n resetVisited(db);\n db.prepare('INSERT INTO visited (path, depth, pred) VALUES (?, 0, NULL)').run(from);\n if (opts.allowed) setupAllowed(db, opts.allowed, to);\n\n const stmt = db.prepare(ringSql(direction, !!opts.allowed));\n for (let ring = 1; ring <= maxDepth; ring++) {\n const rows = stmt.all(ring - 1, ring, -1) as Array<{ path: string }>;\n if (rows.length === 0) break;\n if (rows.some((row) => row.path === to)) return reconstructPath(db, to);\n }\n return null;\n}\n"],"names":["resetVisited","db","exec","setupAllowed","allowed","extra","prepare","run","JSON","stringify","undefined","candidateSelect","direction","forward","reverse","ringSql","hasAllowed","reconstructPath","to","lookup","path","cur","push","row","get","pred","findPath","from","opts","directed","maxDepth","Infinity","stmt","ring","rows","all","length","some"],"mappings":"AAAA,2FAA2F;AAC3F,oEAAoE;AAWpE,SAASA,aAAaC,EAAgB;IACpCA,GAAGC,IAAI,CAAC;IACRD,GAAGC,IAAI,CAAC;AACV;AAEA,0FAA0F;AAC1F,uFAAuF;AACvF,SAASC,aAAaF,EAAgB,EAAEG,OAAoB,EAAEC,KAAc;IAC1EJ,GAAGC,IAAI,CAAC;IACRD,GAAGC,IAAI,CAAC;IACRD,GAAGK,OAAO,CAAC,sEAAsEC,GAAG,CAACC,KAAKC,SAAS,CAAC;WAAIL;KAAQ;IAChH,IAAIC,UAAUK,WAAWT,GAAGK,OAAO,CAAC,kDAAkDC,GAAG,CAACF;AAC5F;AAEA,2EAA2E;AAC3E,SAASM,gBAAgBC,SAAoB;IAC3C,MAAMC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AC3C,MAAMC,OAAOF,KAAKG,GAAG,CAACF,OAAO,GAAGA,MAAM,CAAC;QACvC,IAAIC,KAAKE,MAAM,KAAK,GAAG;QACvB,IAAIF,KAAKG,IAAI,CAAC,CAACd,MAAQA,IAAIH,IAAI,KAAKF,KAAK,OAAOD,gBAAgBhB,IAAIiB;IACtE;IACA,OAAO;AACT"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sensemaking",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Query and search
|
|
3
|
+
"version": "0.10.0",
|
|
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",
|
|
7
7
|
"frontmatter",
|
|
@@ -11,10 +11,24 @@
|
|
|
11
11
|
"query",
|
|
12
12
|
"search",
|
|
13
13
|
"semantic-search",
|
|
14
|
+
"hybrid-search",
|
|
14
15
|
"knowledge-base",
|
|
15
16
|
"rag",
|
|
16
|
-
"
|
|
17
|
+
"progressive-disclosure",
|
|
18
|
+
"graph-traversal",
|
|
19
|
+
"link-graph",
|
|
20
|
+
"wikilinks",
|
|
21
|
+
"backlinks",
|
|
22
|
+
"markdown-database",
|
|
23
|
+
"document-os",
|
|
17
24
|
"notes",
|
|
25
|
+
"obsidian",
|
|
26
|
+
"markdowndb",
|
|
27
|
+
"iwe",
|
|
28
|
+
"silverbullet",
|
|
29
|
+
"logseq",
|
|
30
|
+
"anytype",
|
|
31
|
+
"zk",
|
|
18
32
|
"agent",
|
|
19
33
|
"agent-memory",
|
|
20
34
|
"memory-consolidation",
|
|
@@ -58,7 +72,6 @@
|
|
|
58
72
|
},
|
|
59
73
|
"dependencies": {
|
|
60
74
|
"@huggingface/tokenizers": "^0.1.3",
|
|
61
|
-
"fast-glob": "^3.3.3",
|
|
62
75
|
"remove-markdown": "^0.6.4",
|
|
63
76
|
"yaml": "^2.9.0"
|
|
64
77
|
},
|
|
@@ -70,6 +83,6 @@
|
|
|
70
83
|
"tsds-config": "*"
|
|
71
84
|
},
|
|
72
85
|
"engines": {
|
|
73
|
-
"node": ">=22.
|
|
86
|
+
"node": ">=22.20"
|
|
74
87
|
}
|
|
75
88
|
}
|
package/schema.json
CHANGED
|
@@ -12,12 +12,12 @@
|
|
|
12
12
|
},
|
|
13
13
|
"version": {
|
|
14
14
|
"type": "integer",
|
|
15
|
-
"enum": [1, 2, 3],
|
|
15
|
+
"enum": [1, 2, 3, 4],
|
|
16
16
|
"description": "Config format version. Older versions are auto-migrated (and the file rewritten) on load; a version newer than this sense build supports makes it exit with an error rather than misinterpret the file. Omit to default to 1."
|
|
17
17
|
},
|
|
18
18
|
"presets": {
|
|
19
19
|
"type": "object",
|
|
20
|
-
"description": "File selection, index-time, and named search defaults. A preset is self-contained: no inheritance between presets, and no ordering -- presets may overlap freely (they are views, not partitions), and a preset whose globs match nothing is valid. A file is indexed iff any preset's include/exclude covers it (union across presets);
|
|
20
|
+
"description": "File selection, index-time, and named search defaults. A preset is self-contained: no inheritance between presets, and no ordering -- presets may overlap freely (they are views, not partitions), and a preset whose globs match nothing is valid. A file is indexed iff any preset's include/exclude covers it (union across presets); `default` is used when a command names no preset, and must be declared. A file is embedded when the top-level `embed` block names a model and some covering preset has `semantic` on. `sense init` generates `default` plus one `large` example.",
|
|
21
21
|
"minProperties": 1,
|
|
22
22
|
"additionalProperties": {
|
|
23
23
|
"type": "object",
|
|
@@ -36,15 +36,15 @@
|
|
|
36
36
|
"minItems": 1,
|
|
37
37
|
"description": "Glob patterns excluded from this preset's `include`, tsconfig-standard semantics."
|
|
38
38
|
},
|
|
39
|
+
"semantic": {
|
|
40
|
+
"type": "boolean",
|
|
41
|
+
"description": "Vectors for the files this preset covers, and for searches scoped to it. Absent or true means on; only ever meaningfully written as false. A layer searched for exact wording (ingested sources, archives, generated output) sets it false: its files cost no embedding, and searches under it run on words and links. Requires the top-level `embed` block to name a model before any preset can use vectors."
|
|
42
|
+
},
|
|
39
43
|
"k": {
|
|
40
44
|
"type": "integer",
|
|
41
45
|
"minimum": 1,
|
|
42
46
|
"description": "Default result count for `search` when this preset is in effect (named, or `default` when none is). A --k on the invocation, or a saved search's own `k`, overrides it. Defaults to 10 when the preset omits it too."
|
|
43
47
|
},
|
|
44
|
-
"semantic": {
|
|
45
|
-
"type": "boolean",
|
|
46
|
-
"description": "Vector participation for files this preset covers. Absent or true means on (the default); only ever meaningfully written as false. A file covered only by semantic-false presets is indexed but never embedded, so it searches lexically automatically -- no error, just fewer signals."
|
|
47
|
-
},
|
|
48
48
|
"where": {
|
|
49
49
|
"type": "string",
|
|
50
50
|
"description": "Standing SQL condition against frontmatter alias `f`, applied when `search` runs under this preset without an explicit --where. An explicit --where (or a saved search's own `where`) replaces it rather than ANDing with it, so a caller can always widen back to the preset's whole scope."
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"features": {
|
|
56
56
|
"type": "object",
|
|
57
57
|
"additionalProperties": false,
|
|
58
|
-
"description": "Global feature defaults. Absent block or key means enabled. `embed` is not a member of this block --
|
|
58
|
+
"description": "Global feature defaults. Absent block or key means enabled. `embed` is not a member of this block -- vectors are on exactly when the top-level \"embed\" block names a model. Toggling a feature rebuilds the cache. Commands degrade rather than fail: `search` without links is BM25-only, `map` without rank omits hubs, `peek` without sections omits the outline.",
|
|
59
59
|
"properties": {
|
|
60
60
|
"links": {
|
|
61
61
|
"type": "boolean",
|
|
@@ -74,7 +74,8 @@
|
|
|
74
74
|
"embed": {
|
|
75
75
|
"type": "object",
|
|
76
76
|
"additionalProperties": false,
|
|
77
|
-
"description": "
|
|
77
|
+
"description": "The vector switch and the model it uses. Present with a `model` means every indexed file gets vectors; omit the block entirely to index without vectors. `model` (required: Hugging Face id or local path), `type` (`static` = built-in pure-JS Model2Vec loader, default; `api` = OpenAI-compatible POST /embeddings), `url` (api base, e.g. http://localhost:11434/v1), `key` (name of the env var holding the bearer token). Nothing downloads the model implicitly -- run `sense download` once per machine. Changing model or type rebuilds the cache like a feature toggle.",
|
|
78
|
+
"required": ["model"],
|
|
78
79
|
"properties": {
|
|
79
80
|
"model": { "type": "string" },
|
|
80
81
|
"type": { "type": "string", "enum": ["static", "api"] },
|
|
@@ -84,16 +85,15 @@
|
|
|
84
85
|
},
|
|
85
86
|
"queries": {
|
|
86
87
|
"type": "object",
|
|
87
|
-
"description": "
|
|
88
|
+
"description": "Saved queries runnable as `sense <name> [params...]`, each naming the verb it runs, one to one with the two commands: `{ sql }` runs like `sense sql`, `{ search }` like `sense search`. A bare string is rejected -- it silently meant SQL. `{ sql }`: `?` placeholders bind to CLI positional args in order; deterministic and enumerating, including raw FTS5 `MATCH` for word search under your own SQL -- \"0 rows = not in the tree\" lives here. Tables: `frontmatter` (one row per file, one column per discovered frontmatter key, plus `path`/`_mtime`/`_size`/`_rank`), `content` (FTS5: `title`, `summary`, `text`, `path`), `links` (`src`, `target`, `dst`), `sections` (`path`, `idx`, `level`, `heading`, `start_line`, `end_line`, `tokens`), and `preset_files` (`preset`, `path`) -- which presets cover which files. `has(field, value)`: array membership on a JSON-array field, substring match on a string (so has(f.status, 'active') also matches 'inactive'), false on NULL. Exact matches: `=` for scalars, `EXISTS (SELECT 1 FROM json_each(f.tags) WHERE value = ?)` for array members. Canonical query: `SELECT f.path, content.title, content.summary, CASE WHEN length(content.text) <= 16384 THEN snippet(content, -1, '«', '»', '…', 10) END AS hit FROM frontmatter f JOIN content ON content.path = f.path WHERE content MATCH ? ORDER BY bm25(content, 10.0, 5.0, 1.0) LIMIT 10`. The CASE bounds snippet(), which re-tokenizes each matched document and costs seconds per query once a tree holds a megabyte-scale note; `search` applies the same bound internally. Saved search object: one text driving every engine the scoped preset has -- word match, links, vectors -- fused into one ranked list, `via` labeling which engine produced each row; `search` text must be non-empty (a saved query saves a question -- a scope without one is just flags). `preset` names one declared preset (defaults to `default`); `include` is an ad hoc glob scope that replaces the preset's include/exclude entirely, same as `search --include`; `where` and `k` behave like the `search` command's flags. `sense <name>` behaves like `sense search <search> [--preset] [--include] [--where] [--k]` with zero flags; it takes no positional parameters. `sense check` probes every saved query (k=1 for searches) so a broken one fails loudly at check time -- it makes no assertion about the result itself; a returned row set is the reader's judgment. Reserved frontmatter keys: `path`, `_mtime`, `_size`, `_rank`, `content`, `links`, `sections`. Reserved names (unreachable as saved queries, any shape): `init`, `sql`, `search`, `map`, `peek`, `path`, `related`, `download`, `watch`, `status`, `rebuild`, `check`.",
|
|
88
89
|
"additionalProperties": {
|
|
89
90
|
"oneOf": [
|
|
90
|
-
{ "type": "string" },
|
|
91
91
|
{
|
|
92
92
|
"type": "object",
|
|
93
93
|
"additionalProperties": false,
|
|
94
94
|
"required": ["sql"],
|
|
95
95
|
"properties": {
|
|
96
|
-
"sql": { "type": "string", "description": "Raw SQL,
|
|
96
|
+
"sql": { "type": "string", "description": "Raw SQL, run like `sense sql`. `?` placeholders bind to CLI positional args in order." }
|
|
97
97
|
}
|
|
98
98
|
},
|
|
99
99
|
{
|
|
@@ -117,11 +117,7 @@
|
|
|
117
117
|
"description": "Ad hoc glob scope, same as `search --include`. Replaces the preset's include/exclude entirely rather than layering on top of it."
|
|
118
118
|
},
|
|
119
119
|
"k": { "type": "integer", "minimum": 1, "description": "Result count, same as `search --k`. Defaults to the preset's own `k`, then 10. A --k on the invocation overrides this." },
|
|
120
|
-
"where": { "type": "string", "description": "SQL condition against frontmatter alias `f`, same as `search --where`. A --where on the invocation replaces this rather than ANDing with it." }
|
|
121
|
-
"semantic": {
|
|
122
|
-
"type": "boolean",
|
|
123
|
-
"description": "false opts this query down to lexical-only, same as `search --lexical` -- the rare precision opt-out. Semantic participation otherwise follows the scoped preset's `semantic` automatically, so true is redundant with the default."
|
|
124
|
-
}
|
|
120
|
+
"where": { "type": "string", "description": "SQL condition against frontmatter alias `f`, same as `search --where`. A --where on the invocation replaces this rather than ANDing with it." }
|
|
125
121
|
}
|
|
126
122
|
}
|
|
127
123
|
]
|
package/skills/sense/EXAMPLES.md
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
# sense: worked examples
|
|
2
2
|
|
|
3
|
-
Outputs below are illustrative. Every result is a reference; reading happens afterward, through
|
|
4
|
-
the filesystem, on the paths that earned it.
|
|
3
|
+
Outputs below are illustrative. Every result is a reference; reading happens afterward, through the filesystem, on the paths that earned it.
|
|
5
4
|
|
|
6
5
|
## A. "Do the notes say anything about X?"
|
|
7
6
|
|
|
@@ -18,24 +17,20 @@ sense search "pricing OR billing OR invoicing" --k 10 --format json
|
|
|
18
17
|
]
|
|
19
18
|
```
|
|
20
19
|
|
|
21
|
-
Tens of tokens per row; often the `summary` answers the question with no read at all. A row with
|
|
22
|
-
`via: "link"` never contained the terms — it is linked from notes that did. `lines`, when
|
|
23
|
-
set, is the section that earned the row, a direct `Read` range.
|
|
20
|
+
Tens of tokens per row; often the `summary` answers the question with no read at all. A row with `via: "link"` never contained the terms. It is linked from notes that did. `lines`, when set, is the section that earned the row, a direct `Read` range.
|
|
24
21
|
|
|
25
22
|
## B. Known-field filtering (no search)
|
|
26
23
|
|
|
27
24
|
```
|
|
28
|
-
sense
|
|
25
|
+
sense sql "SELECT path, title, status FROM frontmatter WHERE status = 'active' AND has(tags, ?)" pricing --format json
|
|
29
26
|
```
|
|
30
27
|
|
|
31
|
-
Plain SQL on discovered columns. Combine with search by joining `content` and adding
|
|
32
|
-
`AND content MATCH ?` — filter and rank in one query.
|
|
28
|
+
Plain SQL on discovered columns. Combine with search by joining `content` and adding `AND content MATCH ?`: filter and rank in one query.
|
|
33
29
|
|
|
34
|
-
Per-member counts on an array field (GROUP BY on the raw column would split `["a","b"]` from
|
|
35
|
-
`["b","a"]`):
|
|
30
|
+
Per-member counts on an array field (GROUP BY on the raw column would split `["a","b"]` from `["b","a"]`):
|
|
36
31
|
|
|
37
32
|
```
|
|
38
|
-
sense
|
|
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"
|
|
39
34
|
```
|
|
40
35
|
|
|
41
36
|
## C. Structure before reading
|
|
@@ -55,15 +50,14 @@ links out (7): notes/pricing-model.md, ...
|
|
|
55
50
|
backlinks (2): notes/_index.md, notes/roadmap.md
|
|
56
51
|
```
|
|
57
52
|
|
|
58
|
-
The note is ~4,400 tokens; the peek is ~500. If only one section matters, `Read` its line range
|
|
59
|
-
(~400 tokens) — a tenth of the file.
|
|
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.
|
|
60
54
|
|
|
61
55
|
## D. The graph
|
|
62
56
|
|
|
63
57
|
```
|
|
64
|
-
sense
|
|
65
|
-
sense
|
|
66
|
-
sense
|
|
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" # dead links
|
|
60
|
+
sense sql "SELECT path, round(_rank*100,2) r FROM frontmatter ORDER BY _rank DESC LIMIT 5" # load-bearing notes
|
|
67
61
|
```
|
|
68
62
|
|
|
69
63
|
`sense map` prints the hub list without SQL; use these when you need it filtered or joined.
|
|
@@ -73,7 +67,7 @@ sense query "SELECT path, round(_rank*100,2) r FROM frontmatter ORDER BY _rank D
|
|
|
73
67
|
```
|
|
74
68
|
sense map # fields, hubs, recent — read this first
|
|
75
69
|
sense --list # named queries someone already saved
|
|
76
|
-
sense
|
|
70
|
+
sense sql "SELECT DISTINCT type FROM frontmatter" # what a field's values are
|
|
77
71
|
```
|
|
78
72
|
|
|
79
73
|
## F. "The notes say it in different words"
|
|
@@ -89,10 +83,7 @@ sense search "children dying from poor nutrition" --k 3 --format json
|
|
|
89
83
|
]
|
|
90
84
|
```
|
|
91
85
|
|
|
92
|
-
A `via: "vector"` row never contained the terms
|
|
93
|
-
the cosine against the chunk `lines` names, a direct `Read` range. Vector rows appear whenever
|
|
94
|
-
the scope's preset has semantic on (the default); a result of only vector rows means the words
|
|
95
|
-
themselves are nowhere in the scope.
|
|
86
|
+
A `via: "vector"` row never contained the terms. It is semantically near them; `similarity` is the cosine against the chunk `lines` names, a direct `Read` range. Vector rows appear whenever the config names an `embed` model and it is downloaded; a result of only vector rows means the words themselves are nowhere in the scope.
|
|
96
87
|
|
|
97
88
|
## Consequences
|
|
98
89
|
|
|
@@ -105,4 +96,4 @@ themselves are nowhere in the scope.
|
|
|
105
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"` |
|
|
106
97
|
| `Read` of a large file for one section | costs the whole file | `peek`, then `Read` the line range |
|
|
107
98
|
| row queries without `LIMIT` | unbounded output (aggregates are already bounded) | `LIMIT n` |
|
|
108
|
-
| saving one-off queries to config | config churn | ad-hoc `sense
|
|
99
|
+
| saving one-off queries to config | config churn | ad-hoc `sense sql`; save reusable views |
|