sensemaking 0.19.2 → 0.20.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/dist/cjs/chunk/extract.d.cts +1 -0
- package/dist/cjs/chunk/extract.d.ts +1 -0
- package/dist/cjs/chunk/extract.js +23 -5
- package/dist/cjs/chunk/extract.js.map +1 -1
- package/dist/cjs/chunk/index.d.cts +1 -1
- package/dist/cjs/chunk/index.d.ts +1 -1
- package/dist/cjs/chunk/index.js +3 -0
- package/dist/cjs/chunk/index.js.map +1 -1
- package/dist/cjs/scan/pool.d.cts +15 -0
- package/dist/cjs/scan/pool.d.ts +15 -0
- package/dist/cjs/scan/pool.js +263 -0
- package/dist/cjs/scan/pool.js.map +1 -0
- package/dist/cjs/scan/reparse.d.cts +2 -0
- package/dist/cjs/scan/reparse.d.ts +2 -0
- package/dist/cjs/scan/reparse.js +15 -76
- package/dist/cjs/scan/reparse.js.map +1 -1
- package/dist/cjs/store/builder.d.cts +11 -0
- package/dist/cjs/store/builder.d.ts +11 -0
- package/dist/cjs/store/builder.js +27 -0
- package/dist/cjs/store/builder.js.map +1 -0
- package/dist/cjs/store/duckdb/lexical.d.cts +1 -0
- package/dist/cjs/store/duckdb/lexical.d.ts +1 -0
- package/dist/cjs/store/duckdb/lexical.js +21 -5
- package/dist/cjs/store/duckdb/lexical.js.map +1 -1
- package/dist/cjs/store/duckdb/open.d.cts +9 -8
- package/dist/cjs/store/duckdb/open.d.ts +9 -8
- package/dist/cjs/store/duckdb/open.js +70 -122
- package/dist/cjs/store/duckdb/open.js.map +1 -1
- package/dist/cjs/store/duckdb/reconcile.js +4 -0
- package/dist/cjs/store/duckdb/reconcile.js.map +1 -1
- package/dist/cjs/store/duckdb/store.d.cts +1 -2
- package/dist/cjs/store/duckdb/store.d.ts +1 -2
- package/dist/cjs/store/duckdb/store.js +1 -26
- package/dist/cjs/store/duckdb/store.js.map +1 -1
- package/dist/cjs/store/index.d.cts +8 -3
- package/dist/cjs/store/index.d.ts +8 -3
- package/dist/cjs/store/index.js +36 -7
- package/dist/cjs/store/index.js.map +1 -1
- package/dist/cjs/store/open.d.cts +15 -0
- package/dist/cjs/store/open.d.ts +15 -0
- package/dist/cjs/store/open.js +516 -0
- package/dist/cjs/store/open.js.map +1 -0
- package/dist/cjs/store/reconcile.d.cts +2 -1
- package/dist/cjs/store/reconcile.d.ts +2 -1
- package/dist/cjs/store/reconcile.js +4 -2
- package/dist/cjs/store/reconcile.js.map +1 -1
- package/dist/cjs/store/{sqlite/signature.d.cts → signature.d.cts} +0 -3
- package/dist/cjs/store/{sqlite/signature.d.ts → signature.d.ts} +0 -3
- package/dist/cjs/store/signature.js +162 -0
- package/dist/cjs/store/signature.js.map +1 -0
- package/dist/cjs/store/sqlite/open.d.cts +9 -9
- package/dist/cjs/store/sqlite/open.d.ts +9 -9
- package/dist/cjs/store/sqlite/open.js +189 -201
- package/dist/cjs/store/sqlite/open.js.map +1 -1
- package/dist/cjs/store/sqlite/store.d.cts +1 -1
- package/dist/cjs/store/sqlite/store.d.ts +1 -1
- package/dist/cjs/store/sqlite/store.js +1 -13
- package/dist/cjs/store/sqlite/store.js.map +1 -1
- package/dist/cjs/store/turso/open.d.cts +6 -11
- package/dist/cjs/store/turso/open.d.ts +6 -11
- package/dist/cjs/store/turso/open.js +79 -171
- package/dist/cjs/store/turso/open.js.map +1 -1
- package/dist/cjs/store/turso/reconcile.d.cts +2 -0
- package/dist/cjs/store/turso/reconcile.d.ts +2 -0
- package/dist/cjs/store/turso/reconcile.js +16 -5
- package/dist/cjs/store/turso/reconcile.js.map +1 -1
- package/dist/cjs/store/turso/store.d.cts +1 -2
- package/dist/cjs/store/turso/store.d.ts +1 -2
- package/dist/cjs/store/turso/store.js +1 -13
- package/dist/cjs/store/turso/store.js.map +1 -1
- package/dist/cjs/store/types.d.cts +17 -5
- package/dist/cjs/store/types.d.ts +17 -5
- package/dist/cjs/store/types.js.map +1 -1
- package/dist/cjs/text/strip.js +3 -6
- package/dist/cjs/text/strip.js.map +1 -1
- package/dist/cjs/watch.js +28 -16
- package/dist/cjs/watch.js.map +1 -1
- package/dist/esm/chunk/extract.d.ts +1 -0
- package/dist/esm/chunk/extract.js +10 -2
- package/dist/esm/chunk/extract.js.map +1 -1
- package/dist/esm/chunk/index.d.ts +1 -1
- package/dist/esm/chunk/index.js +1 -1
- package/dist/esm/chunk/index.js.map +1 -1
- package/dist/esm/scan/pool.d.ts +15 -0
- package/dist/esm/scan/pool.js +77 -0
- package/dist/esm/scan/pool.js.map +1 -0
- package/dist/esm/scan/reparse.d.ts +2 -0
- package/dist/esm/scan/reparse.js +11 -58
- package/dist/esm/scan/reparse.js.map +1 -1
- package/dist/esm/store/builder.d.ts +11 -0
- package/dist/esm/store/builder.js +14 -0
- package/dist/esm/store/builder.js.map +1 -0
- package/dist/esm/store/duckdb/lexical.d.ts +1 -0
- package/dist/esm/store/duckdb/lexical.js +22 -9
- package/dist/esm/store/duckdb/lexical.js.map +1 -1
- package/dist/esm/store/duckdb/open.d.ts +9 -8
- package/dist/esm/store/duckdb/open.js +31 -57
- package/dist/esm/store/duckdb/open.js.map +1 -1
- package/dist/esm/store/duckdb/reconcile.js +4 -0
- package/dist/esm/store/duckdb/reconcile.js.map +1 -1
- package/dist/esm/store/duckdb/store.d.ts +1 -2
- package/dist/esm/store/duckdb/store.js +2 -11
- package/dist/esm/store/duckdb/store.js.map +1 -1
- package/dist/esm/store/index.d.ts +8 -3
- package/dist/esm/store/index.js +22 -7
- package/dist/esm/store/index.js.map +1 -1
- package/dist/esm/store/open.d.ts +15 -0
- package/dist/esm/store/open.js +137 -0
- package/dist/esm/store/open.js.map +1 -0
- package/dist/esm/store/reconcile.d.ts +2 -1
- package/dist/esm/store/reconcile.js +4 -2
- package/dist/esm/store/reconcile.js.map +1 -1
- package/dist/esm/store/{sqlite/signature.d.ts → signature.d.ts} +0 -3
- package/dist/esm/store/{sqlite/signature.js → signature.js} +3 -26
- package/dist/esm/store/signature.js.map +1 -0
- package/dist/esm/store/sqlite/open.d.ts +9 -9
- package/dist/esm/store/sqlite/open.js +81 -113
- package/dist/esm/store/sqlite/open.js.map +1 -1
- package/dist/esm/store/sqlite/store.d.ts +1 -1
- package/dist/esm/store/sqlite/store.js +2 -7
- package/dist/esm/store/sqlite/store.js.map +1 -1
- package/dist/esm/store/turso/open.d.ts +6 -11
- package/dist/esm/store/turso/open.js +30 -78
- package/dist/esm/store/turso/open.js.map +1 -1
- package/dist/esm/store/turso/reconcile.d.ts +2 -0
- package/dist/esm/store/turso/reconcile.js +12 -1
- package/dist/esm/store/turso/reconcile.js.map +1 -1
- package/dist/esm/store/turso/store.d.ts +1 -2
- package/dist/esm/store/turso/store.js +2 -7
- package/dist/esm/store/turso/store.js.map +1 -1
- package/dist/esm/store/types.d.ts +17 -5
- package/dist/esm/store/types.js.map +1 -1
- package/dist/esm/text/strip.js +3 -4
- package/dist/esm/text/strip.js.map +1 -1
- package/dist/esm/watch.js +5 -3
- package/dist/esm/watch.js.map +1 -1
- package/package.json +2 -2
- package/dist/cjs/store/sqlite/signature.js +0 -380
- package/dist/cjs/store/sqlite/signature.js.map +0 -1
- package/dist/esm/store/sqlite/signature.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/turso/store.ts"],"sourcesContent":["import type { Database } from '@tursodatabase/database';\nimport
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/turso/store.ts"],"sourcesContent":["import type { Database } from '@tursodatabase/database';\nimport { STORE_DIMS } from '../../embed/types.ts';\nimport { getColumns } from '../shared.ts';\nimport { withTransaction } from '../transaction.ts';\nimport type { Capability, Connection, Statement, Store } from '../types.ts';\nimport { hasVectorRow, pendingRows } from '../vectors.ts';\nimport { fieldStats } from './fieldStats.ts';\nimport { queryLexical } from './lexical.ts';\nimport { scanCandidates, scanSimilar, writeVectorBatch } from './vectors.ts';\n\n// No 'snippets': fts_highlight returns the whole column, not a bounded window, so hits use\n// the caller's JS excerpt. No 'watch-concurrency': single-process by default, as on duckdb.\nexport const CAPABILITIES: ReadonlySet<Capability> = new Set(['lexical', 'phrases', 'vectors']);\n\n// Shares one Connection instance (conn) with the builder's own reconcile call so transaction depth\n// (see transaction.ts) is tracked against the same object everywhere.\nexport function createStore(db: Database, conn: Connection): Store {\n return {\n name: 'turso',\n capabilities: CAPABILITIES,\n async exec(sql: string): Promise<void> {\n await conn.exec(sql);\n },\n async prepare(sql: string): Promise<Statement> {\n return conn.prepare(sql);\n },\n async runBatch(sql: string, paramRows: unknown[][]): Promise<void> {\n await conn.runBatch(sql, paramRows);\n },\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n return withTransaction(conn, fn);\n },\n docs: {\n async columns() {\n return [...(await getColumns(conn))];\n },\n fieldStats: (columns, scopeWhere) => fieldStats(conn, columns, scopeWhere),\n },\n lexical: {\n query: (terms, opts) => queryLexical(conn, terms, opts),\n },\n // The column's fixed DDL width (STORE_DIMS) is what every scan binds against, not the\n // interface's per-call storeDims -- see vectors.ts's padded() for why a shorter vector is still correct against a wider column.\n vectors: {\n pending: () => pendingRows(conn),\n writeVectors: (rows) => writeVectorBatch(conn, STORE_DIMS, rows),\n candidates: (qv, _storeDims, fetch, allowed) => scanCandidates(conn, qv, STORE_DIMS, fetch, allowed),\n similar: (path, opts) => scanSimilar(conn, STORE_DIMS, path, opts),\n hasVector: (path) => hasVectorRow(conn, path),\n },\n async engineStatus() {\n // Read back rather than recomputed: this is what open() actually set (3x the largest\n // recorded reconcile, floored at 30s, capped at 10min). Turso's PRAGMA busy_timeout names its column \"busy_timeout\" (spike-verified), not \"timeout\" like real SQLite.\n const row = (await (await db.prepare('PRAGMA busy_timeout')).get()) as { busy_timeout: number };\n return { busy_timeout: `${row.busy_timeout}ms (derived: 3x the largest reconcile this cache has recorded, floored at 30000ms)` };\n },\n raw: {\n async prepare(sql: string) {\n const stmt = await db.prepare(sql);\n stmt.safeIntegers(true); // int64 past 2^53 arrives as BigInt instead of losing precision\n return {\n columns: () => stmt.columns(),\n // sense sql streams through the client's own async generator.\n iterate: async function* (...params: unknown[]) {\n yield* stmt.iterate(...params);\n },\n };\n },\n },\n async close() {\n await db.close();\n },\n };\n}\n"],"names":["CAPABILITIES","createStore","Set","db","conn","name","capabilities","exec","sql","prepare","runBatch","paramRows","transaction","fn","withTransaction","docs","columns","getColumns","fieldStats","scopeWhere","lexical","query","terms","opts","queryLexical","vectors","pending","pendingRows","writeVectors","rows","writeVectorBatch","STORE_DIMS","candidates","qv","_storeDims","fetch","allowed","scanCandidates","similar","path","scanSimilar","hasVector","hasVectorRow","engineStatus","row","get","busy_timeout","raw","stmt","safeIntegers","iterate","params","close"],"mappings":";;;;;;;;;;;QAYaA;eAAAA;;QAIGC;eAAAA;;;uBAfW;wBACA;6BACK;yBAEU;4BACf;yBACE;0BACiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIvD,IAAMD,eAAwC,IAAIE,IAAI;IAAC;IAAW;IAAW;CAAU;AAIvF,SAASD,YAAYE,EAAY,EAAEC,IAAgB;IACxD,OAAO;QACLC,MAAM;QACNC,cAAcN;QACRO,MAAN,SAAMA,KAAKC,GAAW;;;;;4BACpB;;gCAAMJ,KAAKG,IAAI,CAACC;;;4BAAhB;;;;;;YACF;;QACMC,SAAN,SAAMA,Q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;;;;YACjI;;QACAC,KAAK;YACGtC,SAAN,SAAMA,QAAQD,GAAW;;wBACjBwC;;;;gCAAO;;oCAAM7C,GAAGM,OAAO,CAACD;;;gCAAxBwC,OAAO;gCACbA,KAAKC,YAAY,CAAC,OAAO,gEAAgE;gCACzF;;oCAAO;wCACLjC,SAAS,SAATA;mDAAegC,KAAKhC,OAAO;;wCAC3B,8DAA8D;wCAC9DkC,SAAS,SAATA;4CAA0B,IAAA,IAAA,OAAA,UAAA,QAAA,AAAGC,SAAH,UAAA,OAAA,OAAA,GAAA,OAAA,MAAA;gDAAGA,OAAH,QAAA,SAAA,CAAA,KAAoB;;;oDACrCH;;;;4DAAP;;2EAAA,0CAAOA,CAAAA,QAAAA,MAAKE,OAAO,OAAZF,OAAa,qBAAGG;;;4DAAvB;;;;;;4CACF;;oCACF;;;;gBACF;;QACF;QACMC,OAAN,SAAMA;;;;;4BACJ;;gCAAMjD,GAAGiD,KAAK;;;4BAAd;;;;;;YACF;;IACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Config, StoreName } from '../config/index.js';
|
|
1
|
+
import type { Config, ResolvedConfig, StoreName } from '../config/index.js';
|
|
2
2
|
import type { ReconcileDelta } from '../features/types.js';
|
|
3
3
|
import type { ParsedDoc } from '../scan/index.js';
|
|
4
4
|
export declare const CAPABILITY_NAMES: readonly ["phrases", "snippets", "watch-concurrency", "lexical", "vectors", "sql-functions"];
|
|
@@ -29,6 +29,22 @@ export interface ReconcileDialect {
|
|
|
29
29
|
reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;
|
|
30
30
|
recordDuration?(conn: Connection, ms: number): Promise<void>;
|
|
31
31
|
}
|
|
32
|
+
export interface OpenDialect<Handle> {
|
|
33
|
+
filename: string;
|
|
34
|
+
schemaVersion: string;
|
|
35
|
+
reconcileDialect: ReconcileDialect;
|
|
36
|
+
connect(dbPath: string, cfg: ResolvedConfig): Promise<{
|
|
37
|
+
handle: Handle;
|
|
38
|
+
conn: Connection;
|
|
39
|
+
}>;
|
|
40
|
+
close(handle: Handle): Promise<void>;
|
|
41
|
+
partialRebuild?(handle: Handle, conn: Connection, cfg: Config, changedKeys: Set<string>): Promise<boolean>;
|
|
42
|
+
postSchemaRebuild?(handle: Handle, conn: Connection, cfg: Config, baseDir: string, wantFeatures: string): Promise<string[]>;
|
|
43
|
+
extraRebuildReason?(handle: Handle): string | null;
|
|
44
|
+
ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;
|
|
45
|
+
setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;
|
|
46
|
+
createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;
|
|
47
|
+
}
|
|
32
48
|
export interface FieldStat {
|
|
33
49
|
field: string;
|
|
34
50
|
coverage: number;
|
|
@@ -96,10 +112,6 @@ export interface Store {
|
|
|
96
112
|
prepare(sql: string): Promise<Statement>;
|
|
97
113
|
runBatch(sql: string, paramRows: unknown[][]): Promise<void>;
|
|
98
114
|
transaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
99
|
-
reconcile(): Promise<{
|
|
100
|
-
parsed: number;
|
|
101
|
-
warnings: string[];
|
|
102
|
-
}>;
|
|
103
115
|
docs: DocumentStore;
|
|
104
116
|
lexical: LexicalIndex;
|
|
105
117
|
vectors: VectorStore;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Config, StoreName } from '../config/index.js';
|
|
1
|
+
import type { Config, ResolvedConfig, StoreName } from '../config/index.js';
|
|
2
2
|
import type { ReconcileDelta } from '../features/types.js';
|
|
3
3
|
import type { ParsedDoc } from '../scan/index.js';
|
|
4
4
|
export declare const CAPABILITY_NAMES: readonly ["phrases", "snippets", "watch-concurrency", "lexical", "vectors", "sql-functions"];
|
|
@@ -29,6 +29,22 @@ export interface ReconcileDialect {
|
|
|
29
29
|
reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;
|
|
30
30
|
recordDuration?(conn: Connection, ms: number): Promise<void>;
|
|
31
31
|
}
|
|
32
|
+
export interface OpenDialect<Handle> {
|
|
33
|
+
filename: string;
|
|
34
|
+
schemaVersion: string;
|
|
35
|
+
reconcileDialect: ReconcileDialect;
|
|
36
|
+
connect(dbPath: string, cfg: ResolvedConfig): Promise<{
|
|
37
|
+
handle: Handle;
|
|
38
|
+
conn: Connection;
|
|
39
|
+
}>;
|
|
40
|
+
close(handle: Handle): Promise<void>;
|
|
41
|
+
partialRebuild?(handle: Handle, conn: Connection, cfg: Config, changedKeys: Set<string>): Promise<boolean>;
|
|
42
|
+
postSchemaRebuild?(handle: Handle, conn: Connection, cfg: Config, baseDir: string, wantFeatures: string): Promise<string[]>;
|
|
43
|
+
extraRebuildReason?(handle: Handle): string | null;
|
|
44
|
+
ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;
|
|
45
|
+
setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;
|
|
46
|
+
createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;
|
|
47
|
+
}
|
|
32
48
|
export interface FieldStat {
|
|
33
49
|
field: string;
|
|
34
50
|
coverage: number;
|
|
@@ -96,10 +112,6 @@ export interface Store {
|
|
|
96
112
|
prepare(sql: string): Promise<Statement>;
|
|
97
113
|
runBatch(sql: string, paramRows: unknown[][]): Promise<void>;
|
|
98
114
|
transaction<T>(fn: () => Promise<T>): Promise<T>;
|
|
99
|
-
reconcile(): Promise<{
|
|
100
|
-
parsed: number;
|
|
101
|
-
warnings: string[];
|
|
102
|
-
}>;
|
|
103
115
|
docs: DocumentStore;
|
|
104
116
|
lexical: LexicalIndex;
|
|
105
117
|
vectors: VectorStore;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/types.ts"],"sourcesContent":["// The backing-store interface: a minimal portable statement surface (exec/prepare), plus\n// dedicated interfaces exactly where engines diverge (lexical index, vector scan, raw sql).\n\nimport type { Config, StoreName } from '../config/index.ts';\nimport type { ReconcileDelta } from '../features/types.ts';\nimport type { ParsedDoc } from '../scan/index.ts';\n\n// 'lexical'/'vectors': the store's LexicalIndex/VectorStore is functionally implemented, not\n// present-but-inert. 'sql-functions': the engine can register has/basename/segment as UDFs at all,\n// which turso's client cannot. The rest are finer FTS5-only behaviors; a missing one fails at open\n// or first use. An array, not a bare union, so a runtime check reads the same list the type does.\nexport const CAPABILITY_NAMES = ['phrases', 'snippets', 'watch-concurrency', 'lexical', 'vectors', 'sql-functions'] as const;\nexport type Capability = (typeof CAPABILITY_NAMES)[number];\n\nexport interface RunResult {\n changes: number | bigint;\n lastInsertRowid: number | bigint;\n}\n\n// A prepared statement's async surface: every supported engine crosses a real async boundary\n// for a query (DuckDB has no synchronous client), so run/get/all return Promises.\nexport interface Statement {\n run(...params: unknown[]): Promise<RunResult>;\n get(...params: unknown[]): Promise<unknown>;\n all(...params: unknown[]): Promise<unknown[]>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n columns(): Array<{ name: string }>;\n setReadBigInts(enabled: boolean): void;\n}\n\n// Connection surface feature-owned SQL runs against inside a store's hot loops (schema,\n// reconcile), portable so a feature never imports an engine-specific client type.\nexport interface Connection {\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n}\n\n// One reconcile algorithm (src/store/reconcile.ts), parameterised per engine. reconcileContent is\n// the load-bearing member: it lands every content-table change and owns its own multi-step\n// strategy (sqlite FTS5 incremental, duckdb combined delete/insert, turso incremental-or-rebuild).\nexport interface ReconcileDialect {\n // BEGIN mode for the whole reconcile: sqlite/turso 'BEGIN IMMEDIATE', duckdb 'BEGIN'.\n beginMode(): string;\n // Throws SenseError('COLUMN_LIMIT', ...) past this store's own column ceiling and reasoning.\n checkColumnLimit(count: number): void;\n // Type suffix for ALTER TABLE ADD COLUMN: '' for sqlite/turso, ' VARIANT' for duckdb.\n columnTypeSuffix(): string;\n // Deletes content rows for `touched`, inserts rows for `docs`; `delta` carries the tree state a\n // strategy may need. Must not open its own transaction, and must not return before its own\n // multi-step strategy (e.g. turso's DROP/rebuild) completes.\n reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;\n // Records this reconcile's write-transaction duration. sqlite/turso use it for open()'s derived\n // busy_timeout; duckdb has no such PRAGMA and omits it.\n recordDuration?(conn: Connection, ms: number): Promise<void>;\n}\n\nexport interface FieldStat {\n field: string;\n coverage: number;\n type: string;\n}\n\nexport interface DocumentStore {\n // Frontmatter column names (including internal ones; callers filter).\n columns(): Promise<string[]>;\n // Per-column coverage (non-null count) and observed type set, aggregated in one SQL query,\n // never one row per note. `scopeWhere` is a caller-built WHERE fragment, per LexicalQueryOptions.\n fieldStats(columns: string[], scopeWhere: string): Promise<FieldStat[]>;\n}\n\nexport interface LexicalHit {\n path: string;\n hit: string | null;\n}\n\nexport interface LexicalQueryOptions {\n whereJoin: string;\n whereCond: string;\n scopeCond: string;\n limit: number;\n}\n\nexport interface LexicalIndex {\n // Ranked word-match query with excerpt, scoped by the caller-built SQL fragments (the same\n // fragments narrowByWhere/materializeScope produce elsewhere).\n query(terms: string, opts: LexicalQueryOptions): Promise<LexicalHit[]>;\n}\n\nexport interface VectorCandidate {\n path: string;\n lines: string;\n similarity: number;\n}\n\nexport interface VectorSimilar {\n path: string;\n similarity: number;\n}\n\nexport interface VectorWriteRow {\n path: string;\n chunk: number;\n scale: number;\n vector: Buffer;\n}\n\nexport interface VectorStore {\n // Rows whose vector is NULL: never embedded, or added since.\n pending(): Promise<Array<{ path: string; chunk: number }>>;\n // One batch write per call (never per row) so a provider's embedding batch stays inside a\n // single store method.\n writeVectors(rows: VectorWriteRow[]): Promise<void>;\n candidates(queryVector: Float32Array, storeDims: number, fetch: number, allowed?: Set<string>): Promise<VectorCandidate[]>;\n similar(path: string, opts: { exclude: Set<string>; allowed?: Set<string>; k: number }): Promise<VectorSimilar[]>;\n hasVector(path: string): Promise<boolean>;\n}\n\n// The `sense sql` passthrough: string in, streamed rows out. Each store registers the same\n// sense-supplied functions and applies its own read-bigints/error-translation behavior.\nexport interface RawStatement {\n columns(): Array<{ name: string }>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n}\n\nexport interface SqlSession {\n prepare(sql: string): Promise<RawStatement>;\n}\n\nexport interface Store {\n readonly name: StoreName;\n readonly capabilities: ReadonlySet<Capability>;\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n // One crossing, N rows: every external write loop (search's candidate insert, graph ring's\n // temp-table writes) goes through this instead of looping over `run()`. Same contract as Connection.runBatch.\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Pins one snapshot across multi-statement reads; `map` and `peek` use it. A network-bound\n // write (search's embedding top-up) must stay outside it. Nesting joins the enclosing transaction.\n transaction<T>(fn: () => Promise<T>): Promise<T>;\n
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/store/types.ts"],"sourcesContent":["// The backing-store interface: a minimal portable statement surface (exec/prepare), plus\n// dedicated interfaces exactly where engines diverge (lexical index, vector scan, raw sql).\n\nimport type { Config, ResolvedConfig, StoreName } from '../config/index.ts';\nimport type { ReconcileDelta } from '../features/types.ts';\nimport type { ParsedDoc } from '../scan/index.ts';\n\n// 'lexical'/'vectors': the store's LexicalIndex/VectorStore is functionally implemented, not\n// present-but-inert. 'sql-functions': the engine can register has/basename/segment as UDFs at all,\n// which turso's client cannot. The rest are finer FTS5-only behaviors; a missing one fails at open\n// or first use. An array, not a bare union, so a runtime check reads the same list the type does.\nexport const CAPABILITY_NAMES = ['phrases', 'snippets', 'watch-concurrency', 'lexical', 'vectors', 'sql-functions'] as const;\nexport type Capability = (typeof CAPABILITY_NAMES)[number];\n\nexport interface RunResult {\n changes: number | bigint;\n lastInsertRowid: number | bigint;\n}\n\n// A prepared statement's async surface: every supported engine crosses a real async boundary\n// for a query (DuckDB has no synchronous client), so run/get/all return Promises.\nexport interface Statement {\n run(...params: unknown[]): Promise<RunResult>;\n get(...params: unknown[]): Promise<unknown>;\n all(...params: unknown[]): Promise<unknown[]>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n columns(): Array<{ name: string }>;\n setReadBigInts(enabled: boolean): void;\n}\n\n// Connection surface feature-owned SQL runs against inside a store's hot loops (schema,\n// reconcile), portable so a feature never imports an engine-specific client type.\nexport interface Connection {\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n}\n\n// One reconcile algorithm (src/store/reconcile.ts), parameterised per engine. reconcileContent is\n// the load-bearing member: it lands every content-table change and owns its own multi-step\n// strategy (sqlite FTS5 incremental, duckdb combined delete/insert, turso incremental-or-rebuild).\nexport interface ReconcileDialect {\n // BEGIN mode for the whole reconcile: sqlite/turso 'BEGIN IMMEDIATE', duckdb 'BEGIN'.\n beginMode(): string;\n // Throws SenseError('COLUMN_LIMIT', ...) past this store's own column ceiling and reasoning.\n checkColumnLimit(count: number): void;\n // Type suffix for ALTER TABLE ADD COLUMN: '' for sqlite/turso, ' VARIANT' for duckdb.\n columnTypeSuffix(): string;\n // Deletes content rows for `touched`, inserts rows for `docs`; `delta` carries the tree state a\n // strategy may need. Must not open its own transaction, and must not return before its own\n // multi-step strategy (e.g. turso's DROP/rebuild) completes.\n reconcileContent(conn: Connection, touched: string[], docs: ParsedDoc[], delta: ReconcileDelta, cfg: Config): Promise<void>;\n // Records this reconcile's write-transaction duration. sqlite/turso use it for open()'s derived\n // busy_timeout; duckdb has no such PRAGMA and omits it.\n recordDuration?(conn: Connection, ms: number): Promise<void>;\n}\n\n// One open algorithm (src/store/open.ts), parameterised per engine. `Handle` is whatever this\n// store needs to close the connection and construct its Store (sqlite: {db, tokenize}; duckdb:\n// {instance, duckdb}; turso: db) -- opaque to the shared orchestration, threaded through unchanged.\nexport interface OpenDialect<Handle> {\n // Cache filename under STATE_DIR, e.g. 'cache.db'.\n filename: string;\n // Cache shape version, independent of the config's own `version`; bumping it rebuilds an existing tree.\n schemaVersion: string;\n reconcileDialect: ReconcileDialect;\n // Opens the physical connection and applies pragmas due before any SQL runs (sqlite: busy_timeout\n // + WAL; turso: connect-time timeout; duckdb: none).\n connect(dbPath: string, cfg: ResolvedConfig): Promise<{ handle: Handle; conn: Connection }>;\n // Releases the handle, for both the rebuild-and-reopen branch and error cleanup on this attempt.\n close(handle: Handle): Promise<void>;\n // A signature change fully explained by this dialect's own carve-out (sqlite's tokenize-only\n // partial rebuild): performs the DDL swap and returns true, or false when this change isn't one.\n // Absent for duckdb/turso, which have no such carve-out.\n partialRebuild?(handle: Handle, conn: Connection, cfg: Config, changedKeys: Set<string>): Promise<boolean>;\n // Runs after ensureSchema when partialRebuild returned true this attempt: repopulates whatever\n // the DDL swap emptied and records the adopted signature. sqlite-only.\n postSchemaRebuild?(handle: Handle, conn: Connection, cfg: Config, baseDir: string, wantFeatures: string): Promise<string[]>;\n // A rebuild trigger independent of the schema/feature signature (sqlite: the content table's own\n // tokenizer no longer matches meta). Returns the rebuild reason, or null when none applies.\n extraRebuildReason?(handle: Handle): string | null;\n // Schema DDL beyond frontmatter/preset_files/meta (content table, feature hooks); sole owner of\n // whether it wraps itself in a write transaction (sqlite: yes, guards a cold-open ALTER race; duckdb/turso: no).\n ensureSchema(handle: Handle, conn: Connection, cfg: Config): Promise<void>;\n // Installs the derived busy_timeout PRAGMA right before reconcile (sqlite/turso); absent for\n // duckdb, which has no such PRAGMA.\n setDerivedBusyTimeout?(handle: Handle, conn: Connection, ms: number): Promise<void>;\n createStore(handle: Handle, conn: Connection, cfg: ResolvedConfig): Store;\n}\n\nexport interface FieldStat {\n field: string;\n coverage: number;\n type: string;\n}\n\nexport interface DocumentStore {\n // Frontmatter column names (including internal ones; callers filter).\n columns(): Promise<string[]>;\n // Per-column coverage (non-null count) and observed type set, aggregated in one SQL query,\n // never one row per note. `scopeWhere` is a caller-built WHERE fragment, per LexicalQueryOptions.\n fieldStats(columns: string[], scopeWhere: string): Promise<FieldStat[]>;\n}\n\nexport interface LexicalHit {\n path: string;\n hit: string | null;\n}\n\nexport interface LexicalQueryOptions {\n whereJoin: string;\n whereCond: string;\n scopeCond: string;\n limit: number;\n}\n\nexport interface LexicalIndex {\n // Ranked word-match query with excerpt, scoped by the caller-built SQL fragments (the same\n // fragments narrowByWhere/materializeScope produce elsewhere).\n query(terms: string, opts: LexicalQueryOptions): Promise<LexicalHit[]>;\n}\n\nexport interface VectorCandidate {\n path: string;\n lines: string;\n similarity: number;\n}\n\nexport interface VectorSimilar {\n path: string;\n similarity: number;\n}\n\nexport interface VectorWriteRow {\n path: string;\n chunk: number;\n scale: number;\n vector: Buffer;\n}\n\nexport interface VectorStore {\n // Rows whose vector is NULL: never embedded, or added since.\n pending(): Promise<Array<{ path: string; chunk: number }>>;\n // One batch write per call (never per row) so a provider's embedding batch stays inside a\n // single store method.\n writeVectors(rows: VectorWriteRow[]): Promise<void>;\n candidates(queryVector: Float32Array, storeDims: number, fetch: number, allowed?: Set<string>): Promise<VectorCandidate[]>;\n similar(path: string, opts: { exclude: Set<string>; allowed?: Set<string>; k: number }): Promise<VectorSimilar[]>;\n hasVector(path: string): Promise<boolean>;\n}\n\n// The `sense sql` passthrough: string in, streamed rows out. Each store registers the same\n// sense-supplied functions and applies its own read-bigints/error-translation behavior.\nexport interface RawStatement {\n columns(): Array<{ name: string }>;\n iterate(...params: unknown[]): AsyncIterable<unknown>;\n}\n\nexport interface SqlSession {\n prepare(sql: string): Promise<RawStatement>;\n}\n\nexport interface Store {\n readonly name: StoreName;\n readonly capabilities: ReadonlySet<Capability>;\n exec(sql: string): Promise<void>;\n prepare(sql: string): Promise<Statement>;\n // One crossing, N rows: every external write loop (search's candidate insert, graph ring's\n // temp-table writes) goes through this instead of looping over `run()`. Same contract as Connection.runBatch.\n runBatch(sql: string, paramRows: unknown[][]): Promise<void>;\n // Pins one snapshot across multi-statement reads; `map` and `peek` use it. A network-bound\n // write (search's embedding top-up) must stay outside it. Nesting joins the enclosing transaction.\n transaction<T>(fn: () => Promise<T>): Promise<T>;\n docs: DocumentStore;\n lexical: LexicalIndex;\n vectors: VectorStore;\n raw: SqlSession;\n // Engine-level facts for `sense status` (e.g. a derived busy_timeout PRAGMA reading); each\n // store owns what it reports and how it is worded. Empty when there is nothing to report.\n engineStatus(): Promise<Record<string, string>>;\n close(): Promise<void>;\n}\n"],"names":["CAPABILITY_NAMES"],"mappings":"AAAA,yFAAyF;AACzF,4FAA4F;;;;;+BAU/EA;;;eAAAA;;;AAAN,IAAMA,mBAAmB;IAAC;IAAW;IAAY;IAAqB;IAAW;IAAW;CAAgB"}
|
package/dist/cjs/text/strip.js
CHANGED
|
@@ -19,12 +19,9 @@ _export(exports, {
|
|
|
19
19
|
var _indexts = require("../chunk/index.js");
|
|
20
20
|
var _frontmatterts = require("../scan/frontmatter.js");
|
|
21
21
|
function textFromBlocks(blocks) {
|
|
22
|
-
|
|
23
|
-
return
|
|
24
|
-
})
|
|
25
|
-
return s.length > 0;
|
|
26
|
-
}).join('\n');
|
|
27
|
-
return (0, _frontmatterts.normalizeText)(text);
|
|
22
|
+
return (0, _frontmatterts.normalizeText)((0, _indexts.extractTexts)(blocks.map(function(block) {
|
|
23
|
+
return block.node;
|
|
24
|
+
})));
|
|
28
25
|
}
|
|
29
26
|
function stripText(value) {
|
|
30
27
|
return textFromBlocks((0, _indexts.parse)(value));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/text/strip.ts"],"sourcesContent":["import type { Block } from '../chunk/index.ts';\nimport {
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/text/strip.ts"],"sourcesContent":["import type { Block } from '../chunk/index.ts';\nimport { extractTexts, parse } from '../chunk/index.ts';\nimport { normalizeText } from '../scan/frontmatter.ts';\n\n// Flat prose from blocks a caller already parsed, via the same extractor the chunker uses\n// (src/chunk) -- words and vectors read one definition of \"the prose of this note\".\nexport function textFromBlocks(blocks: Block[]): string {\n return normalizeText(extractTexts(blocks.map((block) => block.node)));\n}\n\n// Thin parse + delegate, for callers with no blocks of their own already.\nexport function stripText(value: string): string {\n return textFromBlocks(parse(value));\n}\n"],"names":["stripText","textFromBlocks","blocks","normalizeText","extractTexts","map","block","node","value","parse"],"mappings":";;;;;;;;;;;QAWgBA;eAAAA;;QALAC;eAAAA;;;uBALoB;6BACN;AAIvB,SAASA,eAAeC,MAAe;IAC5C,OAAOC,IAAAA,4BAAa,EAACC,IAAAA,qBAAY,EAACF,OAAOG,GAAG,CAAC,SAACC;eAAUA,MAAMC,IAAI;;AACpE;AAGO,SAASP,UAAUQ,KAAa;IACrC,OAAOP,eAAeQ,IAAAA,cAAK,EAACD;AAC9B"}
|
package/dist/cjs/watch.js
CHANGED
|
@@ -144,7 +144,7 @@ var HEARTBEAT_INTERVAL_MS = 5000;
|
|
|
144
144
|
var STALE_HEARTBEAT_MS = 15000;
|
|
145
145
|
function runWatch(_0) {
|
|
146
146
|
return _async_to_generator(function(cfg) {
|
|
147
|
-
var opts, _opts_onEvent, _opts_debounceMs, _opts_heartbeatIntervalMs, onEvent, debounceMs, heartbeatIntervalMs, _ref, store, dbPath, initialWarnings, initialParsed, baseDir, existingHeartbeat, age, _tmp, stopping, touchHeartbeat, debounceTimer, inFlight, scheduleReconcile, watcher, heartbeatTimer;
|
|
147
|
+
var opts, _opts_onEvent, _opts_debounceMs, _opts_heartbeatIntervalMs, onEvent, debounceMs, heartbeatIntervalMs, _ref, store, builder, dbPath, initialWarnings, initialParsed, baseDir, existingHeartbeat, age, _tmp, stopping, touchHeartbeat, debounceTimer, inFlight, scheduleReconcile, watcher, heartbeatTimer;
|
|
148
148
|
var _arguments = arguments;
|
|
149
149
|
return _ts_generator(this, function(_state) {
|
|
150
150
|
switch(_state.label){
|
|
@@ -156,10 +156,10 @@ function runWatch(_0) {
|
|
|
156
156
|
heartbeatIntervalMs = (_opts_heartbeatIntervalMs = opts.heartbeatIntervalMs) !== null && _opts_heartbeatIntervalMs !== void 0 ? _opts_heartbeatIntervalMs : HEARTBEAT_INTERVAL_MS;
|
|
157
157
|
return [
|
|
158
158
|
4,
|
|
159
|
-
(0, _indexts1.
|
|
159
|
+
(0, _indexts1.openStoreForWatch)(cfg)
|
|
160
160
|
];
|
|
161
161
|
case 1:
|
|
162
|
-
_ref = _state.sent(), store = _ref.store, dbPath = _ref.dbPath, initialWarnings = _ref.warnings, initialParsed = _ref.parsed;
|
|
162
|
+
_ref = _state.sent(), store = _ref.store, builder = _ref.builder, dbPath = _ref.dbPath, initialWarnings = _ref.warnings, initialParsed = _ref.parsed;
|
|
163
163
|
baseDir = cfg.baseDir;
|
|
164
164
|
return [
|
|
165
165
|
4,
|
|
@@ -169,21 +169,27 @@ function runWatch(_0) {
|
|
|
169
169
|
existingHeartbeat = _state.sent();
|
|
170
170
|
if (!(existingHeartbeat && !opts.force)) return [
|
|
171
171
|
3,
|
|
172
|
-
|
|
172
|
+
5
|
|
173
173
|
];
|
|
174
174
|
age = Date.now() - Date.parse(existingHeartbeat);
|
|
175
175
|
if (!(age >= 0 && age < STALE_HEARTBEAT_MS)) return [
|
|
176
176
|
3,
|
|
177
|
-
|
|
177
|
+
5
|
|
178
178
|
];
|
|
179
179
|
return [
|
|
180
180
|
4,
|
|
181
|
-
|
|
181
|
+
builder.close()
|
|
182
182
|
];
|
|
183
183
|
case 3:
|
|
184
184
|
_state.sent();
|
|
185
|
-
|
|
185
|
+
return [
|
|
186
|
+
4,
|
|
187
|
+
store.close()
|
|
188
|
+
];
|
|
186
189
|
case 4:
|
|
190
|
+
_state.sent();
|
|
191
|
+
throw new _errorsts.SenseError('WATCH_ACTIVE', "another watcher appears active (heartbeat ".concat(Math.round(age / 1000), "s ago); use --force to override"));
|
|
192
|
+
case 5:
|
|
187
193
|
onEvent({
|
|
188
194
|
type: 'started',
|
|
189
195
|
baseDir: baseDir,
|
|
@@ -191,7 +197,7 @@ function runWatch(_0) {
|
|
|
191
197
|
});
|
|
192
198
|
if (!(initialWarnings.length > 0 || initialParsed > 0)) return [
|
|
193
199
|
3,
|
|
194
|
-
|
|
200
|
+
7
|
|
195
201
|
];
|
|
196
202
|
_tmp = {
|
|
197
203
|
type: 'reconciled',
|
|
@@ -201,12 +207,12 @@ function runWatch(_0) {
|
|
|
201
207
|
4,
|
|
202
208
|
(0, _indexts1.docCount)(store)
|
|
203
209
|
];
|
|
204
|
-
case
|
|
210
|
+
case 6:
|
|
205
211
|
onEvent.apply(void 0, [
|
|
206
212
|
(_tmp.total = _state.sent(), _tmp.warnings = initialWarnings, _tmp)
|
|
207
213
|
]);
|
|
208
|
-
_state.label =
|
|
209
|
-
case
|
|
214
|
+
_state.label = 7;
|
|
215
|
+
case 7:
|
|
210
216
|
stopping = false;
|
|
211
217
|
touchHeartbeat = function touchHeartbeat() {
|
|
212
218
|
return _async_to_generator(function() {
|
|
@@ -236,7 +242,7 @@ function runWatch(_0) {
|
|
|
236
242
|
4,
|
|
237
243
|
touchHeartbeat()
|
|
238
244
|
];
|
|
239
|
-
case
|
|
245
|
+
case 8:
|
|
240
246
|
_state.sent();
|
|
241
247
|
debounceTimer = null;
|
|
242
248
|
// A reconcile that has already started owns the store, and on a bulk reparse a live worker
|
|
@@ -260,7 +266,7 @@ function runWatch(_0) {
|
|
|
260
266
|
]);
|
|
261
267
|
return [
|
|
262
268
|
4,
|
|
263
|
-
|
|
269
|
+
builder.build()
|
|
264
270
|
];
|
|
265
271
|
case 1:
|
|
266
272
|
_ref = _state.sent(), parsed = _ref.parsed, warnings = _ref.warnings;
|
|
@@ -346,21 +352,27 @@ function runWatch(_0) {
|
|
|
346
352
|
_state.sent();
|
|
347
353
|
return [
|
|
348
354
|
4,
|
|
349
|
-
|
|
355
|
+
builder.close()
|
|
350
356
|
];
|
|
351
357
|
case 2:
|
|
352
358
|
_state.sent();
|
|
353
359
|
return [
|
|
354
360
|
4,
|
|
355
|
-
(0, _indexts1.setMeta)(store, '
|
|
361
|
+
(0, _indexts1.setMeta)(store, 'watch_heartbeat', null)
|
|
356
362
|
];
|
|
357
363
|
case 3:
|
|
358
364
|
_state.sent();
|
|
359
365
|
return [
|
|
360
366
|
4,
|
|
361
|
-
|
|
367
|
+
(0, _indexts1.setMeta)(store, 'watch_pid', null)
|
|
362
368
|
];
|
|
363
369
|
case 4:
|
|
370
|
+
_state.sent();
|
|
371
|
+
return [
|
|
372
|
+
4,
|
|
373
|
+
store.close()
|
|
374
|
+
];
|
|
375
|
+
case 5:
|
|
364
376
|
_state.sent();
|
|
365
377
|
resolveShutdown();
|
|
366
378
|
return [
|
package/dist/cjs/watch.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/watch.ts"],"sourcesContent":["import { watch as fsWatch } from 'node:fs';\nimport type { ResolvedConfig } from './config/index.ts';\nimport { STATE_DIR } from './config/index.ts';\nimport { SenseError } from './errors.ts';\nimport { guardedTick } from './lib/guarded-tick.ts';\nimport { docCount, getMeta,
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/watch.ts"],"sourcesContent":["import { watch as fsWatch } from 'node:fs';\nimport type { ResolvedConfig } from './config/index.ts';\nimport { STATE_DIR } from './config/index.ts';\nimport { SenseError } from './errors.ts';\nimport { guardedTick } from './lib/guarded-tick.ts';\nimport { docCount, getMeta, openStoreForWatch, requireWatchConcurrency, setMeta } from './store/index.ts';\n\n// Watch is a cache pre-warmer, not a correctness mechanism: open() always reconciles anyway, so any fs event just triggers a debounced full reconcile.\nconst DEBOUNCE_MS = 200;\nconst HEARTBEAT_INTERVAL_MS = 5000;\nconst STALE_HEARTBEAT_MS = 15000;\n\nexport type WatchEvent = { type: 'started'; baseDir: string; dbPath: string } | { type: 'reconciled'; parsed: number; total: number; warnings: string[] } | { type: 'reconcile-error'; message: string };\n\nexport interface WatchOptions {\n force?: boolean;\n onEvent?: (event: WatchEvent) => void;\n // Aborting runs the same shutdown path as SIGINT/SIGTERM.\n signal?: AbortSignal;\n debounceMs?: number;\n heartbeatIntervalMs?: number;\n}\n\n// Runs in the foreground until SIGINT/SIGTERM/signal abort. Throws WATCH_ACTIVE if another watcher's heartbeat is still fresh and --force wasn't given.\nexport async function runWatch(cfg: ResolvedConfig, opts: WatchOptions = {}): Promise<void> {\n requireWatchConcurrency(cfg);\n const onEvent = opts.onEvent ?? (() => {});\n const debounceMs = opts.debounceMs ?? DEBOUNCE_MS;\n const heartbeatIntervalMs = opts.heartbeatIntervalMs ?? HEARTBEAT_INTERVAL_MS;\n const { store, builder, dbPath, warnings: initialWarnings, parsed: initialParsed } = await openStoreForWatch(cfg);\n const baseDir = cfg.baseDir;\n\n const existingHeartbeat = await getMeta(store, 'watch_heartbeat');\n if (existingHeartbeat && !opts.force) {\n const age = Date.now() - Date.parse(existingHeartbeat);\n if (age >= 0 && age < STALE_HEARTBEAT_MS) {\n await builder.close();\n await store.close();\n throw new SenseError('WATCH_ACTIVE', `another watcher appears active (heartbeat ${Math.round(age / 1000)}s ago); use --force to override`);\n }\n }\n\n onEvent({ type: 'started', baseDir, dbPath });\n if (initialWarnings.length > 0 || initialParsed > 0) {\n onEvent({ type: 'reconciled', parsed: initialParsed, total: await docCount(store), warnings: initialWarnings });\n }\n\n let stopping = false;\n const touchHeartbeat = async () => {\n await setMeta(store, 'watch_heartbeat', new Date().toISOString());\n await setMeta(store, 'watch_pid', String(process.pid));\n };\n await touchHeartbeat();\n\n let debounceTimer: NodeJS.Timeout | null = null;\n // A reconcile that has already started owns the store, and on a bulk reparse a live worker\n // pool as well. Shutdown waits on this rather than closing the connection underneath it.\n let inFlight: Promise<void> | null = null;\n const scheduleReconcile = () => {\n if (debounceTimer) clearTimeout(debounceTimer);\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n inFlight = (async () => {\n try {\n const { parsed, warnings } = await builder.build();\n onEvent({ type: 'reconciled', parsed, total: await docCount(store), warnings });\n } catch (err) {\n onEvent({ type: 'reconcile-error', message: (err as Error).message });\n } finally {\n inFlight = null;\n }\n })();\n }, debounceMs);\n };\n\n // Ignore our own state dir, or the heartbeat write would retrigger itself forever. An event with\n // an unresolvable filename (null, which fs.watch delivers under load) reconciles: parsing nothing costs less than missing a real edit.\n const watcher = fsWatch(baseDir, { recursive: true }, (_event, filename) => {\n if (typeof filename === 'string' && filename.startsWith(STATE_DIR)) return;\n scheduleReconcile();\n });\n const heartbeatTimer = setInterval(\n guardedTick(touchHeartbeat, () => stopping),\n heartbeatIntervalMs\n );\n\n return new Promise<void>((resolveShutdown) => {\n // SIGINT/SIGTERM and an aborted signal all run this same path exactly once; each is\n // unregistered here too so a second runWatch call in the same process starts clean.\n const shutdown = async () => {\n if (stopping) return;\n stopping = true;\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n opts.signal?.removeEventListener('abort', shutdown);\n clearInterval(heartbeatTimer);\n if (debounceTimer) clearTimeout(debounceTimer);\n watcher.close();\n await inFlight;\n await builder.close();\n await setMeta(store, 'watch_heartbeat', null);\n await setMeta(store, 'watch_pid', null);\n await store.close();\n resolveShutdown();\n };\n process.once('SIGINT', shutdown);\n process.once('SIGTERM', shutdown);\n if (opts.signal?.aborted) shutdown();\n else opts.signal?.addEventListener('abort', shutdown, { once: true });\n });\n}\n"],"names":["runWatch","DEBOUNCE_MS","HEARTBEAT_INTERVAL_MS","STALE_HEARTBEAT_MS","cfg","opts","onEvent","debounceMs","heartbeatIntervalMs","store","builder","dbPath","initialWarnings","initialParsed","baseDir","existingHeartbeat","age","stopping","touchHeartbeat","debounceTimer","inFlight","scheduleReconcile","watcher","heartbeatTimer","requireWatchConcurrency","openStoreForWatch","warnings","parsed","getMeta","force","Date","now","parse","close","SenseError","Math","round","type","length","docCount","total","setMeta","toISOString","String","process","pid","clearTimeout","setTimeout","err","build","message","fsWatch","recursive","_event","filename","startsWith","STATE_DIR","setInterval","guardedTick","Promise","resolveShutdown","shutdown","off","signal","removeEventListener","clearInterval","once","aborted","addEventListener"],"mappings":";;;;+BAwBsBA;;;eAAAA;;;sBAxBW;uBAEP;wBACC;6BACC;wBAC2D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvF,uJAAuJ;AACvJ,IAAMC,cAAc;AACpB,IAAMC,wBAAwB;AAC9B,IAAMC,qBAAqB;AAcpB,SAAeH;wCAASI,GAAmB;YAAEC,MAElCA,eACGA,kBACSA,2BAFtBC,SACAC,YACAC,qBAC+E,MAA7EC,OAAOC,SAASC,QAAkBC,iBAAyBC,eAC7DC,SAEAC,mBAEEC,WAaJC,UACEC,gBAMFC,eAGAC,UACEC,mBAmBAC,SAIAC;;;;;oBAzD4ClB,OAAAA,oEAAqB,CAAC;oBACxEmB,IAAAA,iCAAuB,EAACpB;oBAClBE,WAAUD,gBAAAA,KAAKC,OAAO,cAAZD,2BAAAA,gBAAiB,YAAO;oBAClCE,cAAaF,mBAAAA,KAAKE,UAAU,cAAfF,8BAAAA,mBAAmBJ;oBAChCO,uBAAsBH,4BAAAA,KAAKG,mBAAmB,cAAxBH,uCAAAA,4BAA4BH;oBAC6B;;wBAAMuB,IAAAA,2BAAiB,EAACrB;;;oBAAxB,OAAA,eAA7EK,QAA6E,KAA7EA,OAAOC,UAAsE,KAAtEA,SAASC,SAA6D,KAA7DA,QAAkBC,kBAA2C,KAArDc,UAAmCb,gBAAkB,KAA1Bc;oBACrDb,UAAUV,IAAIU,OAAO;oBAED;;wBAAMc,IAAAA,iBAAO,EAACnB,OAAO;;;oBAAzCM,oBAAoB;yBACtBA,CAAAA,qBAAqB,CAACV,KAAKwB,KAAK,AAAD,GAA/Bd;;;;oBACIC,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AM,cAAX1D,oCAAAA,cAAa+D,gBAAgB,CAAC,SAASP,UAAU;gCAAEK,MAAM;4BAAK;wBACrE;;;;IACF"}
|
|
@@ -36,7 +36,7 @@ function embedText(inner) {
|
|
|
36
36
|
return anchorText(pipeIdx === -1 ? inner : inner.slice(0, pipeIdx));
|
|
37
37
|
}
|
|
38
38
|
function resolveFlavor(text) {
|
|
39
|
-
return text.replace(COMMENT_PAIR, '').replace(EMBED, (_, inner)=>embedText(inner)).replace(WIKILINK, (_, inner)=>wikilinkText(inner)).replace(BLOCK_ID, '');
|
|
39
|
+
return text.replace(HTML_COMMENT, '').replace(COMMENT_PAIR, '').replace(EMBED, (_, inner)=>embedText(inner)).replace(WIKILINK, (_, inner)=>wikilinkText(inner)).replace(BLOCK_ID, '');
|
|
40
40
|
}
|
|
41
41
|
// Sibling blocks (list items, blockquote content, footnote bodies) joined one per line;
|
|
42
42
|
// empties dropped so a blank child never widens the gap between its neighbors.
|
|
@@ -108,7 +108,15 @@ const CODE_PLACEHOLDER = /\uE000(\d+)\uE000/g;
|
|
|
108
108
|
// Plain text of one mdast node (or a whole tree): heading/list/table structure is kept as text,
|
|
109
109
|
// markup (emphasis, link targets, task and callout markers) is dropped. Pure, synchronous.
|
|
110
110
|
export function extractText(node) {
|
|
111
|
+
return extractTexts([
|
|
112
|
+
node
|
|
113
|
+
]);
|
|
114
|
+
}
|
|
115
|
+
// Blocks resolved together: a blank line inside %%...%% splits it across blocks, and a per-block
|
|
116
|
+
// strip then never sees the closing %%. Code stays placeholder-held across all of them.
|
|
117
|
+
export function extractTexts(nodes) {
|
|
111
118
|
const code = [];
|
|
112
|
-
const
|
|
119
|
+
const joined = nodes.map((n)=>extractNode(n, code)).filter((s)=>s.length > 0).join('\n');
|
|
120
|
+
const resolved = resolveFlavor(joined);
|
|
113
121
|
return code.length === 0 ? resolved : resolved.replace(CODE_PLACEHOLDER, (_, i)=>code[Number(i)]);
|
|
114
122
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/chunk/extract.ts"],"sourcesContent":["import type { Nodes } from 'mdast';\n\n// mdast has no wikilink, embed, or %%comment%% node -- literal text resolved by regex passes\n// over non-code text (code/inlineCode is placeholder-held and spliced back verbatim, below).\nconst COMMENT_PAIR = /%%[\\s\\S]*?%%/g;\n// An embed always yields its target, whatever follows a pipe (a resize suffix, never an alias);\n// must run before the wikilink regex below, bang included, or that regex matches first.\nconst EMBED = /!\\[\\[([^\\]]+)\\]\\]/g;\nconst WIKILINK = /\\[\\[([^\\]]+)\\]\\]/g;\n// A trailing \" ^id\" is an Obsidian block anchor, valid only at a line's end; a caret elsewhere\n// (mid-line) is ordinary text and is left alone.\nconst BLOCK_ID = / \\^[A-Za-z0-9-]+$/gm;\n// A callout marker is only ever the first thing in a blockquote's text (Obsidian's grammar),\n// so this anchors to blockquote output alone -- never applied to prose in general.\nconst CALLOUT_MARKER = /^\\[!\\w[\\w-]*\\][+-]?[ \\t]?/;\n// An html node's value is raw HTML, block or inline: a full <!-- --> comment is dropped, any\n// remaining tags are stripped, and the text a browser would still render survives.\nconst HTML_COMMENT = /<!--[\\s\\S]*?-->/g;\nconst HTML_TAG = /<[^>]+>/g;\n\nfunction stripHtml(value: string): string {\n return value.replace(HTML_COMMENT, '').replace(HTML_TAG, '');\n}\n\n// A `#anchor` keeps its text (hash dropped), unlike links.ts's parseWikilinkInner (the resolver\n// authority), which discards it entirely -- replicated here since that return value doesn't fit.\nfunction anchorText(base: string): string {\n const hashIdx = base.indexOf('#');\n if (hashIdx === -1) return base.trim();\n const target = base.slice(0, hashIdx).trim();\n const anchor = base.slice(hashIdx + 1).trim();\n return target ? `${target} ${anchor}` : anchor;\n}\n\nfunction wikilinkText(inner: string): string {\n const pipeIdx = inner.indexOf('|');\n return pipeIdx === -1 ? anchorText(inner) : inner.slice(pipeIdx + 1).trim();\n}\n\nfunction embedText(inner: string): string {\n const pipeIdx = inner.indexOf('|');\n return anchorText(pipeIdx === -1 ? inner : inner.slice(0, pipeIdx));\n}\n\nfunction resolveFlavor(text: string): string {\n return text\n .replace(COMMENT_PAIR, '')\n .replace(EMBED, (_, inner: string) => embedText(inner))\n .replace(WIKILINK, (_, inner: string) => wikilinkText(inner))\n .replace(BLOCK_ID, '');\n}\n\n// Sibling blocks (list items, blockquote content, footnote bodies) joined one per line;\n// empties dropped so a blank child never widens the gap between its neighbors.\nfunction joinBlocks(nodes: Nodes[], code: string[]): string {\n return nodes\n .map((n) => extractNode(n, code))\n .filter((s) => s.length > 0)\n .join('\\n');\n}\n\n// Inline content (headings, paragraphs, emphasis, links) concatenated with no separator: the\n// source text nodes already carry whatever spacing separates them.\nfunction joinInline(nodes: Nodes[], code: string[]): string {\n return nodes.map((n) => extractNode(n, code)).join('');\n}\n\n// U+E000 (Private Use Area) never appears in real markdown text, so it is a collision-free\n// placeholder delimiter, spliced back to the literal code value after flavor resolution.\nfunction codePlaceholder(value: string, code: string[]): string {\n const idx = code.push(value) - 1;\n return `\\uE000${idx}\\uE000`;\n}\n\n// A GFM autolink's display text is its own target, missing only the scheme\n// mdast-util-gfm-autolink-literal fills into node.url (http:// for www., mailto: for an email).\nconst SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:\\/{0,2}/i;\nfunction isAutolink(url: string, text: string): boolean {\n return url === text || url.replace(SCHEME_PREFIX, '') === text;\n}\n\nfunction extractNode(node: Nodes, code: string[]): string {\n switch (node.type) {\n case 'root':\n case 'list':\n case 'listItem':\n case 'footnoteDefinition':\n return joinBlocks(node.children, code);\n case 'blockquote':\n return joinBlocks(node.children, code).replace(CALLOUT_MARKER, '');\n case 'link': {\n const text = joinInline(node.children, code);\n return isAutolink(node.url, text) ? '' : text;\n }\n case 'heading':\n case 'paragraph':\n case 'linkReference':\n case 'emphasis':\n case 'strong':\n case 'delete':\n return joinInline(node.children, code);\n case 'table':\n return node.children.map((n) => extractNode(n, code)).join('\\n');\n case 'tableRow':\n return node.children.map((n) => extractNode(n, code)).join(' ');\n case 'tableCell':\n return joinInline(node.children, code);\n case 'image':\n case 'imageReference':\n return node.alt ?? '';\n case 'text':\n return node.value;\n case 'inlineCode':\n case 'code':\n return codePlaceholder(node.value, code);\n case 'html':\n return stripHtml(node.value);\n case 'break':\n return ' ';\n default:\n return '';\n }\n}\n\nconst CODE_PLACEHOLDER = /\\uE000(\\d+)\\uE000/g;\n\n// Plain text of one mdast node (or a whole tree): heading/list/table structure is kept as text,\n// markup (emphasis, link targets, task and callout markers) is dropped. Pure, synchronous.\nexport function extractText(node: Nodes): string {\n const code: string[] = [];\n const
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/chunk/extract.ts"],"sourcesContent":["import type { Nodes } from 'mdast';\n\n// mdast has no wikilink, embed, or %%comment%% node -- literal text resolved by regex passes\n// over non-code text (code/inlineCode is placeholder-held and spliced back verbatim, below).\nconst COMMENT_PAIR = /%%[\\s\\S]*?%%/g;\n// An embed always yields its target, whatever follows a pipe (a resize suffix, never an alias);\n// must run before the wikilink regex below, bang included, or that regex matches first.\nconst EMBED = /!\\[\\[([^\\]]+)\\]\\]/g;\nconst WIKILINK = /\\[\\[([^\\]]+)\\]\\]/g;\n// A trailing \" ^id\" is an Obsidian block anchor, valid only at a line's end; a caret elsewhere\n// (mid-line) is ordinary text and is left alone.\nconst BLOCK_ID = / \\^[A-Za-z0-9-]+$/gm;\n// A callout marker is only ever the first thing in a blockquote's text (Obsidian's grammar),\n// so this anchors to blockquote output alone -- never applied to prose in general.\nconst CALLOUT_MARKER = /^\\[!\\w[\\w-]*\\][+-]?[ \\t]?/;\n// An html node's value is raw HTML, block or inline: a full <!-- --> comment is dropped, any\n// remaining tags are stripped, and the text a browser would still render survives.\nconst HTML_COMMENT = /<!--[\\s\\S]*?-->/g;\nconst HTML_TAG = /<[^>]+>/g;\n\nfunction stripHtml(value: string): string {\n return value.replace(HTML_COMMENT, '').replace(HTML_TAG, '');\n}\n\n// A `#anchor` keeps its text (hash dropped), unlike links.ts's parseWikilinkInner (the resolver\n// authority), which discards it entirely -- replicated here since that return value doesn't fit.\nfunction anchorText(base: string): string {\n const hashIdx = base.indexOf('#');\n if (hashIdx === -1) return base.trim();\n const target = base.slice(0, hashIdx).trim();\n const anchor = base.slice(hashIdx + 1).trim();\n return target ? `${target} ${anchor}` : anchor;\n}\n\nfunction wikilinkText(inner: string): string {\n const pipeIdx = inner.indexOf('|');\n return pipeIdx === -1 ? anchorText(inner) : inner.slice(pipeIdx + 1).trim();\n}\n\nfunction embedText(inner: string): string {\n const pipeIdx = inner.indexOf('|');\n return anchorText(pipeIdx === -1 ? inner : inner.slice(0, pipeIdx));\n}\n\nfunction resolveFlavor(text: string): string {\n return text\n .replace(HTML_COMMENT, '')\n .replace(COMMENT_PAIR, '')\n .replace(EMBED, (_, inner: string) => embedText(inner))\n .replace(WIKILINK, (_, inner: string) => wikilinkText(inner))\n .replace(BLOCK_ID, '');\n}\n\n// Sibling blocks (list items, blockquote content, footnote bodies) joined one per line;\n// empties dropped so a blank child never widens the gap between its neighbors.\nfunction joinBlocks(nodes: Nodes[], code: string[]): string {\n return nodes\n .map((n) => extractNode(n, code))\n .filter((s) => s.length > 0)\n .join('\\n');\n}\n\n// Inline content (headings, paragraphs, emphasis, links) concatenated with no separator: the\n// source text nodes already carry whatever spacing separates them.\nfunction joinInline(nodes: Nodes[], code: string[]): string {\n return nodes.map((n) => extractNode(n, code)).join('');\n}\n\n// U+E000 (Private Use Area) never appears in real markdown text, so it is a collision-free\n// placeholder delimiter, spliced back to the literal code value after flavor resolution.\nfunction codePlaceholder(value: string, code: string[]): string {\n const idx = code.push(value) - 1;\n return `\\uE000${idx}\\uE000`;\n}\n\n// A GFM autolink's display text is its own target, missing only the scheme\n// mdast-util-gfm-autolink-literal fills into node.url (http:// for www., mailto: for an email).\nconst SCHEME_PREFIX = /^[a-z][a-z0-9+.-]*:\\/{0,2}/i;\nfunction isAutolink(url: string, text: string): boolean {\n return url === text || url.replace(SCHEME_PREFIX, '') === text;\n}\n\nfunction extractNode(node: Nodes, code: string[]): string {\n switch (node.type) {\n case 'root':\n case 'list':\n case 'listItem':\n case 'footnoteDefinition':\n return joinBlocks(node.children, code);\n case 'blockquote':\n return joinBlocks(node.children, code).replace(CALLOUT_MARKER, '');\n case 'link': {\n const text = joinInline(node.children, code);\n return isAutolink(node.url, text) ? '' : text;\n }\n case 'heading':\n case 'paragraph':\n case 'linkReference':\n case 'emphasis':\n case 'strong':\n case 'delete':\n return joinInline(node.children, code);\n case 'table':\n return node.children.map((n) => extractNode(n, code)).join('\\n');\n case 'tableRow':\n return node.children.map((n) => extractNode(n, code)).join(' ');\n case 'tableCell':\n return joinInline(node.children, code);\n case 'image':\n case 'imageReference':\n return node.alt ?? '';\n case 'text':\n return node.value;\n case 'inlineCode':\n case 'code':\n return codePlaceholder(node.value, code);\n case 'html':\n return stripHtml(node.value);\n case 'break':\n return ' ';\n default:\n return '';\n }\n}\n\nconst CODE_PLACEHOLDER = /\\uE000(\\d+)\\uE000/g;\n\n// Plain text of one mdast node (or a whole tree): heading/list/table structure is kept as text,\n// markup (emphasis, link targets, task and callout markers) is dropped. Pure, synchronous.\nexport function extractText(node: Nodes): string {\n return extractTexts([node]);\n}\n\n// Blocks resolved together: a blank line inside %%...%% splits it across blocks, and a per-block\n// strip then never sees the closing %%. Code stays placeholder-held across all of them.\nexport function extractTexts(nodes: Nodes[]): string {\n const code: string[] = [];\n const joined = nodes\n .map((n) => extractNode(n, code))\n .filter((s) => s.length > 0)\n .join('\\n');\n const resolved = resolveFlavor(joined);\n return code.length === 0 ? resolved : resolved.replace(CODE_PLACEHOLDER, (_, i: string) => code[Number(i)]);\n}\n"],"names":["COMMENT_PAIR","EMBED","WIKILINK","BLOCK_ID","CALLOUT_MARKER","HTML_COMMENT","HTML_TAG","stripHtml","value","replace","anchorText","base","hashIdx","indexOf","trim","target","slice","anchor","wikilinkText","inner","pipeIdx","embedText","resolveFlavor","text","_","joinBlocks","nodes","code","map","n","extractNode","filter","s","length","join","joinInline","codePlaceholder","idx","push","SCHEME_PREFIX","isAutolink","url","node","type","children","alt","CODE_PLACEHOLDER","extractText","extractTexts","joined","resolved","i","Number"],"mappings":"AAEA,6FAA6F;AAC7F,6FAA6F;AAC7F,MAAMA,eAAe;AACrB,gGAAgG;AAChG,wFAAwF;AACxF,MAAMC,QAAQ;AACd,MAAMC,WAAW;AACjB,+FAA+F;AAC/F,iDAAiD;AACjD,MAAMC,WAAW;AACjB,6FAA6F;AAC7F,mFAAmF;AACnF,MAAMC,iBAAiB;AACvB,6FAA6F;AAC7F,mFAAmF;AACnF,MAAMC,eAAe;AACrB,MAAMC,WAAW;AAEjB,SAASC,UAAUC,KAAa;IAC9B,OAAOA,MAAMC,OAAO,CAACJ,cAAc,IAAII,OAAO,CAACH,UAAU;AAC3D;AAEA,gGAAgG;AAChG,iGAAiG;AACjG,SAASI,WAAWC,IAAY;IAC9B,MAAMC,UAAUD,KAAKE,OAAO,CAAC;IAC7B,IAAID,YAAY,CAAC,GAAG,OAAOD,KAAKG,IAAI;IACpC,MAAMC,SAASJ,KAAKK,KAAK,CAAC,GAAGJ,SAASE,IAAI;IAC1C,MAAMG,SAASN,KAAKK,KAAK,CAACJ,UAAU,GAAGE,IAAI;IAC3C,OAAOC,SAAS,GAAGA,OAAO,CAAC,EAAEE,QAAQ,GAAGA;AAC1C;AAEA,SAASC,aAAaC,KAAa;IACjC,MAAMC,UAAUD,MAAMN,OAAO,CAAC;IAC9B,OAAOO,YAAY,CAAC,IAAIV,WAAWS,SAASA,MAAMH,KAAK,CAACI,UAAU,GAAGN,IAAI;AAC3E;AAEA,SAASO,UAAUF,KAAa;IAC9B,MAAMC,UAAUD,MAAMN,OAAO,CAAC;IAC9B,OAAOH,WAAWU,YAAY,CAAC,IAAID,QAAQA,MAAMH,KAAK,CAAC,GAAGI;AAC5D;AAEA,SAASE,cAAcC,IAAY;IACjC,OAAOA,KACJd,OAAO,CAACJ,cAAc,IACtBI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{ Block, Chunk, ChunkOptions } from './types.js';
|
|
2
2
|
export declare function chunkFromBlocks(blocks: Block[], body: string, opts?: ChunkOptions): Chunk[];
|
|
3
3
|
export declare function chunk(body: string, opts?: ChunkOptions): Chunk[];
|
|
4
|
-
export { extractText } from './extract.js';
|
|
4
|
+
export { extractText, extractTexts } from './extract.js';
|
|
5
5
|
export { DEFAULT_TARGET_TOKENS, estimateTokens } from './group.js';
|
|
6
6
|
export { parse } from './parse.js';
|
|
7
7
|
export type { Block, BlockType, Chunk, ChunkOptions } from './types.js';
|
package/dist/esm/chunk/index.js
CHANGED
|
@@ -10,7 +10,7 @@ export function chunkFromBlocks(blocks, body, opts) {
|
|
|
10
10
|
export function chunk(body, opts) {
|
|
11
11
|
return chunkFromBlocks(parse(body), body, opts);
|
|
12
12
|
}
|
|
13
|
-
export { extractText } from './extract.js';
|
|
13
|
+
export { extractText, extractTexts } from './extract.js';
|
|
14
14
|
export { DEFAULT_TARGET_TOKENS, estimateTokens } from './group.js';
|
|
15
15
|
export { parse } from './parse.js';
|
|
16
16
|
export { CHUNK_VERSION } from './version.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/chunk/index.ts"],"sourcesContent":["import { group } from './group.ts';\nimport { parse } from './parse.ts';\nimport type { Block, Chunk, ChunkOptions } from './types.ts';\n\n// Groups blocks a caller already parsed (e.g. scan/index.ts, sharing one parse with the FTS\n// text path) against the same body they came from, per opts (D1/D3).\nexport function chunkFromBlocks(blocks: Block[], body: string, opts?: ChunkOptions): Chunk[] {\n return group(blocks, body, opts);\n}\n\n// Pure, deterministic function of file content; chunk semantics are version-stamped via\n// CHUNK_VERSION (./version.ts). Algorithm and evidence: BENCHMARKING.md, \"The chunking algorithm\".\nexport function chunk(body: string, opts?: ChunkOptions): Chunk[] {\n return chunkFromBlocks(parse(body), body, opts);\n}\n\nexport { extractText } from './extract.ts';\nexport { DEFAULT_TARGET_TOKENS, estimateTokens } from './group.ts';\nexport { parse } from './parse.ts';\nexport type { Block, BlockType, Chunk, ChunkOptions } from './types.ts';\nexport { CHUNK_VERSION } from './version.ts';\n"],"names":["group","parse","chunkFromBlocks","blocks","body","opts","chunk","extractText","DEFAULT_TARGET_TOKENS","estimateTokens","CHUNK_VERSION"],"mappings":"AAAA,SAASA,KAAK,QAAQ,aAAa;AACnC,SAASC,KAAK,QAAQ,aAAa;AAGnC,4FAA4F;AAC5F,qEAAqE;AACrE,OAAO,SAASC,gBAAgBC,MAAe,EAAEC,IAAY,EAAEC,IAAmB;IAChF,OAAOL,MAAMG,QAAQC,MAAMC;AAC7B;AAEA,wFAAwF;AACxF,mGAAmG;AACnG,OAAO,SAASC,MAAMF,IAAY,EAAEC,IAAmB;IACrD,OAAOH,gBAAgBD,MAAMG,OAAOA,MAAMC;AAC5C;AAEA,SAASE,WAAW,QAAQ,eAAe;
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/chunk/index.ts"],"sourcesContent":["import { group } from './group.ts';\nimport { parse } from './parse.ts';\nimport type { Block, Chunk, ChunkOptions } from './types.ts';\n\n// Groups blocks a caller already parsed (e.g. scan/index.ts, sharing one parse with the FTS\n// text path) against the same body they came from, per opts (D1/D3).\nexport function chunkFromBlocks(blocks: Block[], body: string, opts?: ChunkOptions): Chunk[] {\n return group(blocks, body, opts);\n}\n\n// Pure, deterministic function of file content; chunk semantics are version-stamped via\n// CHUNK_VERSION (./version.ts). Algorithm and evidence: BENCHMARKING.md, \"The chunking algorithm\".\nexport function chunk(body: string, opts?: ChunkOptions): Chunk[] {\n return chunkFromBlocks(parse(body), body, opts);\n}\n\nexport { extractText, extractTexts } from './extract.ts';\nexport { DEFAULT_TARGET_TOKENS, estimateTokens } from './group.ts';\nexport { parse } from './parse.ts';\nexport type { Block, BlockType, Chunk, ChunkOptions } from './types.ts';\nexport { CHUNK_VERSION } from './version.ts';\n"],"names":["group","parse","chunkFromBlocks","blocks","body","opts","chunk","extractText","extractTexts","DEFAULT_TARGET_TOKENS","estimateTokens","CHUNK_VERSION"],"mappings":"AAAA,SAASA,KAAK,QAAQ,aAAa;AACnC,SAASC,KAAK,QAAQ,aAAa;AAGnC,4FAA4F;AAC5F,qEAAqE;AACrE,OAAO,SAASC,gBAAgBC,MAAe,EAAEC,IAAY,EAAEC,IAAmB;IAChF,OAAOL,MAAMG,QAAQC,MAAMC;AAC7B;AAEA,wFAAwF;AACxF,mGAAmG;AACnG,OAAO,SAASC,MAAMF,IAAY,EAAEC,IAAmB;IACrD,OAAOH,gBAAgBD,MAAMG,OAAOA,MAAMC;AAC5C;AAEA,SAASE,WAAW,EAAEC,YAAY,QAAQ,eAAe;AACzD,SAASC,qBAAqB,EAAEC,cAAc,QAAQ,aAAa;AACnE,SAAST,KAAK,QAAQ,aAAa;AAEnC,SAASU,aAAa,QAAQ,eAAe"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Config } from '../config/index.js';
|
|
2
|
+
import type { Feature } from '../features/types.js';
|
|
3
|
+
import type { ParsedDoc } from '../scan/index.js';
|
|
4
|
+
import type { FileStat } from './list.js';
|
|
5
|
+
export type FileResult = {
|
|
6
|
+
doc: ParsedDoc;
|
|
7
|
+
warnings: string[];
|
|
8
|
+
};
|
|
9
|
+
export declare class ParsePool {
|
|
10
|
+
private pool;
|
|
11
|
+
poolsCreated: number;
|
|
12
|
+
private ensure;
|
|
13
|
+
run(files: FileStat[], features: Feature[], cfg: Config, onParsed: ((done: number) => void) | undefined, maxWorkers: number): Promise<FileResult[]>;
|
|
14
|
+
close(): Promise<void>;
|
|
15
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { reviveError } from './worker-error.js';
|
|
4
|
+
// Tinypool is ESM-only; our floor (>=22.20) has native require(esm), so the tier-2 house deferral reaches it.
|
|
5
|
+
const _require = typeof require === 'undefined' ? createRequire(import.meta.url) : require;
|
|
6
|
+
// Worker MUST load from dist/cjs/: a worker_threads thread is a fresh realm with no inherited
|
|
7
|
+
// TS loader hook, so a source path cannot work. Resolved on first pooled dispatch, not at import.
|
|
8
|
+
let workerFile;
|
|
9
|
+
function resolveWorkerFile() {
|
|
10
|
+
if (workerFile) return workerFile;
|
|
11
|
+
const load = createRequire(import.meta.url);
|
|
12
|
+
for (const rel of [
|
|
13
|
+
'..',
|
|
14
|
+
'../..',
|
|
15
|
+
'../../..'
|
|
16
|
+
]){
|
|
17
|
+
try {
|
|
18
|
+
if (load(`${rel}/package.json`).name === 'sensemaking') {
|
|
19
|
+
workerFile = join(dirname(load.resolve(`${rel}/package.json`)), 'dist', 'cjs', 'workers', 'parse.js');
|
|
20
|
+
return workerFile;
|
|
21
|
+
}
|
|
22
|
+
} catch {}
|
|
23
|
+
}
|
|
24
|
+
throw new Error('cannot locate the sensemaking package root, so the parse worker cannot be found; run npm run build');
|
|
25
|
+
}
|
|
26
|
+
// One Tinypool per instance, created lazily on first dispatch and reused by every later call:
|
|
27
|
+
// a builder owns one of these for its whole lifetime instead of paying pool startup per reconcile.
|
|
28
|
+
export class ParsePool {
|
|
29
|
+
ensure(workerData, maxWorkers) {
|
|
30
|
+
if (!this.pool) {
|
|
31
|
+
const { Tinypool } = _require('tinypool');
|
|
32
|
+
this.pool = new Tinypool({
|
|
33
|
+
filename: resolveWorkerFile(),
|
|
34
|
+
minThreads: maxWorkers,
|
|
35
|
+
maxThreads: maxWorkers,
|
|
36
|
+
workerData
|
|
37
|
+
});
|
|
38
|
+
this.poolsCreated++;
|
|
39
|
+
}
|
|
40
|
+
return this.pool;
|
|
41
|
+
}
|
|
42
|
+
// Never the tree: a worker task carries one FileStat and returns only what parseFile returns --
|
|
43
|
+
// extracted text and feature values, never the mdast tree.
|
|
44
|
+
async run(files, features, cfg, onParsed, maxWorkers) {
|
|
45
|
+
// cfg and the feature selection are constant for the dispatch, so they cross once per worker
|
|
46
|
+
// as workerData. Features carry closures and cannot cross at all; only their names do.
|
|
47
|
+
const workerData = {
|
|
48
|
+
cfg,
|
|
49
|
+
featureNames: features.map((feature)=>feature.name)
|
|
50
|
+
};
|
|
51
|
+
const pool = this.ensure(workerData, maxWorkers);
|
|
52
|
+
let done = 0;
|
|
53
|
+
// Promise.all over a mapped array is load-bearing: the resolved array keeps `files` order
|
|
54
|
+
// regardless of task completion order, which first-seen column order depends on downstream.
|
|
55
|
+
return Promise.all(files.map(async (file)=>{
|
|
56
|
+
const result = await pool.run(file);
|
|
57
|
+
if (!result.ok) throw reviveError(result.error);
|
|
58
|
+
onParsed === null || onParsed === void 0 ? void 0 : onParsed(++done);
|
|
59
|
+
return {
|
|
60
|
+
doc: result.doc,
|
|
61
|
+
warnings: result.warnings
|
|
62
|
+
};
|
|
63
|
+
}));
|
|
64
|
+
}
|
|
65
|
+
// A pool never created costs nothing to destroy.
|
|
66
|
+
async close() {
|
|
67
|
+
if (!this.pool) return;
|
|
68
|
+
const pool = this.pool;
|
|
69
|
+
this.pool = undefined;
|
|
70
|
+
await pool.destroy();
|
|
71
|
+
}
|
|
72
|
+
constructor(){
|
|
73
|
+
// Tinypools this instance has constructed. One dispatch or a hundred should leave it at 1;
|
|
74
|
+
// it is how a caller, and the specs, observe that a lifetime reuses its pool rather than churning one.
|
|
75
|
+
this.poolsCreated = 0;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/Users/kevin/Dev/OpenSource/ai/sensemaking/src/scan/pool.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n// Type-only: erased at build, but keeps depcheck's usage check satisfied for the tier-2\n// `_require` below (see coding-standards' deferral tiers).\nimport type * as TinypoolNS from 'tinypool';\nimport type { Config } from '../config/index.ts';\nimport type { Feature } from '../features/types.ts';\nimport type { ParsedDoc } from '../scan/index.ts';\nimport type { ParseTask, ParseTaskResult, ParseWorkerData } from '../workers/parse.ts';\nimport type { FileStat } from './list.ts';\nimport { reviveError } from './worker-error.ts';\n\n// Tinypool is ESM-only; our floor (>=22.20) has native require(esm), so the tier-2 house deferral reaches it.\nconst _require = typeof require === 'undefined' ? createRequire(import.meta.url) : require;\n\n// Worker MUST load from dist/cjs/: a worker_threads thread is a fresh realm with no inherited\n// TS loader hook, so a source path cannot work. Resolved on first pooled dispatch, not at import.\nlet workerFile: string | undefined;\nfunction resolveWorkerFile(): string {\n if (workerFile) return workerFile;\n const load = createRequire(import.meta.url);\n for (const rel of ['..', '../..', '../../..']) {\n try {\n if ((load(`${rel}/package.json`) as { name?: string }).name === 'sensemaking') {\n workerFile = join(dirname(load.resolve(`${rel}/package.json`)), 'dist', 'cjs', 'workers', 'parse.js');\n return workerFile;\n }\n } catch {}\n }\n throw new Error('cannot locate the sensemaking package root, so the parse worker cannot be found; run npm run build');\n}\n\nexport type FileResult = { doc: ParsedDoc; warnings: string[] };\n\n// One Tinypool per instance, created lazily on first dispatch and reused by every later call:\n// a builder owns one of these for its whole lifetime instead of paying pool startup per reconcile.\nexport class ParsePool {\n private pool: TinypoolNS.Tinypool | undefined;\n // Tinypools this instance has constructed. One dispatch or a hundred should leave it at 1;\n // it is how a caller, and the specs, observe that a lifetime reuses its pool rather than churning one.\n poolsCreated = 0;\n\n private ensure(workerData: ParseWorkerData, maxWorkers: number): TinypoolNS.Tinypool {\n if (!this.pool) {\n const { Tinypool } = _require('tinypool') as typeof TinypoolNS;\n this.pool = new Tinypool({ filename: resolveWorkerFile(), minThreads: maxWorkers, maxThreads: maxWorkers, workerData });\n this.poolsCreated++;\n }\n return this.pool;\n }\n\n // Never the tree: a worker task carries one FileStat and returns only what parseFile returns --\n // extracted text and feature values, never the mdast tree.\n async run(files: FileStat[], features: Feature[], cfg: Config, onParsed: ((done: number) => void) | undefined, maxWorkers: number): Promise<FileResult[]> {\n // cfg and the feature selection are constant for the dispatch, so they cross once per worker\n // as workerData. Features carry closures and cannot cross at all; only their names do.\n const workerData: ParseWorkerData = { cfg, featureNames: features.map((feature) => feature.name) };\n const pool = this.ensure(workerData, maxWorkers);\n let done = 0;\n // Promise.all over a mapped array is load-bearing: the resolved array keeps `files` order\n // regardless of task completion order, which first-seen column order depends on downstream.\n return Promise.all(\n files.map(async (file): Promise<FileResult> => {\n const result = (await pool.run(file as ParseTask)) as ParseTaskResult;\n if (!result.ok) throw reviveError(result.error);\n onParsed?.(++done);\n return { doc: result.doc, warnings: result.warnings };\n })\n );\n }\n\n // A pool never created costs nothing to destroy.\n async close(): Promise<void> {\n if (!this.pool) return;\n const pool = this.pool;\n this.pool = undefined;\n await pool.destroy();\n }\n}\n"],"names":["createRequire","dirname","join","reviveError","_require","require","url","workerFile","resolveWorkerFile","load","rel","name","resolve","Error","ParsePool","ensure","workerData","maxWorkers","pool","Tinypool","filename","minThreads","maxThreads","poolsCreated","run","files","features","cfg","onParsed","featureNames","map","feature","done","Promise","all","file","result","ok","error","doc","warnings","close","undefined","destroy"],"mappings":"AAAA,SAASA,aAAa,QAAQ,cAAc;AAC5C,SAASC,OAAO,EAAEC,IAAI,QAAQ,YAAY;AAS1C,SAASC,WAAW,QAAQ,oBAAoB;AAEhD,8GAA8G;AAC9G,MAAMC,WAAW,OAAOC,YAAY,cAAcL,cAAc,YAAYM,GAAG,IAAID;AAEnF,8FAA8F;AAC9F,kGAAkG;AAClG,IAAIE;AACJ,SAASC;IACP,IAAID,YAAY,OAAOA;IACvB,MAAME,OAAOT,cAAc,YAAYM,GAAG;IAC1C,KAAK,MAAMI,OAAO;QAAC;QAAM;QAAS;KAAW,CAAE;QAC7C,IAAI;YACF,IAAI,AAACD,KAAK,GAAGC,IAAI,aAAa,CAAC,EAAwBC,IAAI,KAAK,eAAe;gBAC7EJ,aAAaL,KAAKD,QAAQQ,KAAKG,OAAO,CAAC,GAAGF,IAAI,aAAa,CAAC,IAAI,QAAQ,OAAO,WAAW;gBAC1F,OAAOH;YACT;QACF,EAAE,OAAM,CAAC;IACX;IACA,M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