@gmickel/gno 2.15.0 → 2.17.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 +1 -1
- package/assets/skill/SKILL.md +27 -0
- package/assets/skill/cli-reference.md +24 -15
- package/assets/spa-production.json.gz +0 -0
- package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
- package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
- package/browser-extension/dist/manifest.json +1 -1
- package/package.json +1 -1
- package/spec/cli.md +43 -3
- package/spec/db/schema.sql +53 -1
- package/spec/mcp.md +9 -3
- package/spec/output-schemas/doctor.schema.json +27 -0
- package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
- package/spec/output-schemas/search-results.schema.json +14 -0
- package/spec/output-schemas/status.schema.json +22 -0
- package/src/cli/commands/agents/commands.ts +1 -1
- package/src/cli/commands/ask.ts +1 -1
- package/src/cli/commands/context-build.ts +1 -1
- package/src/cli/commands/doctor.ts +101 -29
- package/src/cli/commands/embed.ts +2 -2
- package/src/cli/commands/links.ts +30 -6
- package/src/cli/commands/mcp/install.ts +2 -2
- package/src/cli/commands/mcp/status.ts +1 -1
- package/src/cli/commands/mcp/uninstall.ts +1 -1
- package/src/cli/commands/query.ts +1 -1
- package/src/cli/commands/shared.ts +4 -4
- package/src/cli/commands/skill/install.ts +1 -1
- package/src/cli/commands/skill/paths-cmd.ts +1 -1
- package/src/cli/commands/skill/uninstall.ts +1 -1
- package/src/cli/commands/status.ts +75 -58
- package/src/cli/commands/vec.ts +180 -8
- package/src/cli/config-cache.ts +86 -0
- package/src/cli/globals.ts +64 -0
- package/src/cli/program.ts +63 -36
- package/src/cli/run.ts +121 -67
- package/src/cli/runtime-health.ts +132 -122
- package/src/cli/session-binding.ts +11 -2
- package/src/config/saver.ts +8 -0
- package/src/config/types.ts +6 -0
- package/src/converters/adapters/browser-export/formats.ts +25 -15
- package/src/converters/adapters/email/adapter.ts +37 -53
- package/src/converters/adapters/email/html.ts +37 -20
- package/src/converters/adapters/email/mime.ts +71 -39
- package/src/converters/adapters/ical/adapter.ts +20 -12
- package/src/converters/adapters/jsonl/adapter.ts +8 -6
- package/src/converters/adapters/shared/html-text.ts +55 -37
- package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
- package/src/converters/adapters/shared/utf8-lines.ts +69 -31
- package/src/converters/adapters/transcript/adapter.ts +12 -7
- package/src/converters/adapters/xlsx/adapter.ts +10 -7
- package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
- package/src/converters/canonicalize.ts +17 -3
- package/src/converters/native/markdown.ts +24 -17
- package/src/converters/native/plaintext.ts +5 -6
- package/src/converters/registry.ts +130 -8
- package/src/core/activation-status.ts +4 -8
- package/src/core/change-diff.ts +38 -11
- package/src/core/context-compiler.ts +17 -18
- package/src/core/context-evidence.ts +116 -25
- package/src/core/context-verifier.ts +70 -31
- package/src/core/file-lock.ts +10 -2
- package/src/core/graph-analysis.ts +3 -3
- package/src/core/link-inventory-markdown.ts +2 -2
- package/src/core/links.ts +20 -87
- package/src/core/memory-fence.ts +16 -9
- package/src/core/memory-recall.ts +168 -34
- package/src/core/path-rules.ts +143 -0
- package/src/core/retrieval-trace-session.ts +3 -0
- package/src/core/retrieval-trace.ts +9 -0
- package/src/core/section-parse.ts +16 -6
- package/src/core/typed-metadata.ts +68 -0
- package/src/core/vector-partition-status.ts +13 -0
- package/src/core/wiki-link-syntax.ts +88 -0
- package/src/embed/backlog.ts +142 -60
- package/src/embed/retry.ts +39 -33
- package/src/embed/variant-backlog.ts +582 -116
- package/src/embed/variant-retry.ts +157 -48
- package/src/index.ts +3 -3
- package/src/ingestion/budget-error-codes.ts +13 -0
- package/src/ingestion/chunker.ts +60 -49
- package/src/ingestion/compiled-context.ts +4 -5
- package/src/ingestion/convert-file.ts +1 -1
- package/src/ingestion/document-metadata.ts +16 -9
- package/src/ingestion/excluded-ranges.ts +97 -0
- package/src/ingestion/file-processor.ts +122 -37
- package/src/ingestion/frontmatter.ts +35 -7
- package/src/ingestion/graph-reconciliation.ts +187 -51
- package/src/ingestion/language.ts +66 -61
- package/src/ingestion/position.ts +5 -5
- package/src/ingestion/prepare-file.ts +50 -29
- package/src/ingestion/record-adapter-canonical.ts +37 -26
- package/src/ingestion/record-adapter.ts +46 -26
- package/src/ingestion/record-container.ts +121 -53
- package/src/ingestion/record-path.ts +5 -2
- package/src/ingestion/source-availability/darwin-io.ts +10 -7
- package/src/ingestion/source-availability/darwin-path.ts +21 -3
- package/src/ingestion/source-availability/readers.ts +51 -0
- package/src/ingestion/strip.ts +39 -105
- package/src/ingestion/sync.ts +692 -386
- package/src/ingestion/typed-metadata.ts +10 -4
- package/src/ingestion/walker.ts +485 -158
- package/src/llm/cache.ts +128 -84
- package/src/llm/http-inference.ts +112 -35
- package/src/llm/http-policy.ts +101 -0
- package/src/llm/httpEmbedding.ts +8 -1
- package/src/llm/httpGeneration.ts +5 -1
- package/src/llm/httpRerank.ts +5 -1
- package/src/llm/inference-scope.ts +15 -2
- package/src/llm/lazy-ports.ts +33 -3
- package/src/llm/lockfile.ts +34 -7
- package/src/llm/model-cleanup.ts +24 -0
- package/src/llm/native-worker/client.ts +23 -12
- package/src/llm/native-worker/dispatcher.ts +19 -9
- package/src/llm/native-worker/embedding-identity.ts +42 -16
- package/src/llm/native-worker/entry.ts +2 -1
- package/src/llm/native-worker/owner.ts +1 -0
- package/src/llm/native-worker/ports.ts +86 -23
- package/src/llm/native-worker/protocol.ts +386 -55
- package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
- package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
- package/src/llm/nodeLlamaCpp/generation.ts +194 -30
- package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
- package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
- package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
- package/src/llm/types.ts +14 -0
- package/src/mcp/context.ts +342 -23
- package/src/mcp/http-transport.ts +21 -3
- package/src/mcp/tool-profile-types.ts +62 -0
- package/src/mcp/tool-profile.ts +32 -56
- package/src/mcp/tools/context.ts +5 -1
- package/src/mcp/tools/index.ts +269 -191
- package/src/mcp/tools/links.ts +14 -6
- package/src/mcp/tools/query.ts +60 -37
- package/src/mcp/tools/vsearch.ts +25 -14
- package/src/pipeline/answer.ts +133 -40
- package/src/pipeline/claim-verification.ts +293 -189
- package/src/pipeline/claim-verifier.ts +6 -7
- package/src/pipeline/egress-lineage.ts +37 -26
- package/src/pipeline/exclude.ts +34 -11
- package/src/pipeline/expansion.ts +233 -19
- package/src/pipeline/explain.ts +17 -2
- package/src/pipeline/filters.ts +169 -33
- package/src/pipeline/graph-retrieval.ts +117 -61
- package/src/pipeline/hybrid.ts +626 -330
- package/src/pipeline/hydration.ts +86 -24
- package/src/pipeline/intent.ts +15 -7
- package/src/pipeline/owner-fusion.ts +61 -19
- package/src/pipeline/query-language.ts +15 -2
- package/src/pipeline/rerank.ts +15 -22
- package/src/pipeline/search.ts +193 -72
- package/src/pipeline/snippet.ts +15 -2
- package/src/pipeline/temporal.ts +51 -10
- package/src/pipeline/types.ts +7 -0
- package/src/pipeline/vsearch.ts +269 -154
- package/src/publish/attachment-raster.ts +2 -16
- package/src/publish/encrypted-export.ts +15 -5
- package/src/serve/browse-tree.ts +50 -42
- package/src/serve/connectors.ts +2 -1
- package/src/serve/context.ts +13 -4
- package/src/serve/doc-events.ts +3 -0
- package/src/serve/public/app.tsx +49 -21
- package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
- package/src/serve/public/components/CaptureModal.tsx +14 -10
- package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
- package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
- package/src/serve/public/globals.built.css +1 -1
- package/src/serve/public/globals.css +19 -0
- package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
- package/src/serve/public/lib/metadata-filter.ts +234 -9
- package/src/serve/public/pages/Browse.tsx +61 -27
- package/src/serve/public/pages/DocView.tsx +44 -25
- package/src/serve/public/pages/GraphView.tsx +8 -3
- package/src/serve/resident-runtime.ts +199 -48
- package/src/serve/routes/api.ts +98 -67
- package/src/serve/routes/links.ts +25 -5
- package/src/serve/server.ts +1370 -1180
- package/src/serve/spa-bundle-source.ts +52 -27
- package/src/serve/status.ts +101 -52
- package/src/serve/watch-reconciliation-fallback.ts +11 -7
- package/src/serve/watch-reconciliation-shared.ts +42 -4
- package/src/serve/watch-reconciliation.ts +21 -8
- package/src/serve/watch-service-events.ts +7 -1
- package/src/serve/watch-service-hosts.ts +3 -1
- package/src/serve/watch-service.ts +46 -21
- package/src/serve/watch-snapshot-scan.ts +6 -15
- package/src/sessions/archive.ts +20 -8
- package/src/sessions/sanitize.ts +38 -18
- package/src/sessions/service.ts +180 -102
- package/src/store/migrations/037-performance-indexes.ts +56 -0
- package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
- package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
- package/src/store/migrations/index.ts +6 -0
- package/src/store/sqlite/adapter.ts +1260 -651
- package/src/store/sqlite/chunking-policy.ts +15 -1
- package/src/store/sqlite/eligibility.ts +110 -70
- package/src/store/sqlite/graph-neighbors.ts +71 -46
- package/src/store/sqlite/graph-reference-state.ts +27 -3
- package/src/store/sqlite/graph-similarity.ts +59 -12
- package/src/store/sqlite/metadata-predicate.ts +123 -28
- package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
- package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
- package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
- package/src/store/types.ts +32 -0
- package/src/store/vector/coarse-router.ts +312 -0
- package/src/store/vector/eligibility.ts +39 -0
- package/src/store/vector/lazy.ts +17 -0
- package/src/store/vector/partition-index.ts +333 -59
- package/src/store/vector/proof-cache.ts +209 -0
- package/src/store/vector/runtime-compat.ts +6 -0
- package/src/store/vector/sqlite-vec.ts +270 -162
- package/src/store/vector/stats.ts +37 -73
- package/src/store/vector/status.ts +169 -53
- package/src/store/vector/stored-vectors.ts +131 -45
- package/src/store/vector/types.ts +19 -0
- package/src/store/vector/v2-mirror.ts +669 -0
- package/src/store/vector/variant-search.ts +1187 -111
- package/src/store/vector/variants.ts +964 -160
- package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
|
@@ -12,6 +12,8 @@ import "./setup";
|
|
|
12
12
|
import { Database } from "bun:sqlite";
|
|
13
13
|
// node:async_hooks binds nested transactions to one async request; Bun has no separate native equivalent.
|
|
14
14
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
15
|
+
// node:os totalmem: no Bun equivalent for total system memory.
|
|
16
|
+
import { totalmem } from "node:os";
|
|
15
17
|
// node:path basename: no Bun path utilities.
|
|
16
18
|
import { basename } from "node:path";
|
|
17
19
|
|
|
@@ -64,6 +66,7 @@ import type {
|
|
|
64
66
|
FileRefactorResolutionSnapshot,
|
|
65
67
|
GetGraphNeighborsOptions,
|
|
66
68
|
GetGraphOptions,
|
|
69
|
+
GraphDocumentIdentity,
|
|
67
70
|
GraphEdgeConfidence,
|
|
68
71
|
GraphEdgeAudit,
|
|
69
72
|
GraphLinkType,
|
|
@@ -149,6 +152,7 @@ import {
|
|
|
149
152
|
import { normalizeWikiName, stripWikiMdExt } from "../../core/links";
|
|
150
153
|
import { tracePhase } from "../../core/phase-trace";
|
|
151
154
|
import {
|
|
155
|
+
parseStoredTypedMetadata,
|
|
152
156
|
TYPED_METADATA_INGEST_VERSION,
|
|
153
157
|
typedMetadataSchema,
|
|
154
158
|
} from "../../core/typed-metadata";
|
|
@@ -185,6 +189,7 @@ import {
|
|
|
185
189
|
} from "./capsule-registry-store";
|
|
186
190
|
import {
|
|
187
191
|
appendDocumentChange as appendStoredDocumentChange,
|
|
192
|
+
type DocumentChangeSnapshot,
|
|
188
193
|
enforceDocumentChangeRetention as enforceStoredDocumentChangeRetention,
|
|
189
194
|
listDocumentChanges as listStoredDocumentChanges,
|
|
190
195
|
purgeDocumentChanges as purgeStoredDocumentChanges,
|
|
@@ -272,7 +277,6 @@ const WHITESPACE_REGEX = /\s+/;
|
|
|
272
277
|
const SINGLE_LINE_QUERY_PATTERN = /[\r\n]/;
|
|
273
278
|
const DOUBLE_QUOTE_PATTERN = /"/g;
|
|
274
279
|
const DOC_EDGE_TYPE_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
275
|
-
const SQLITE_SAFE_PARAMETER_BATCH_SIZE = 900;
|
|
276
280
|
|
|
277
281
|
/**
|
|
278
282
|
* Effective physical source path for watcher fallback queries.
|
|
@@ -575,6 +579,67 @@ function withoutBusyWait(db: Database, write: () => void): void {
|
|
|
575
579
|
}
|
|
576
580
|
|
|
577
581
|
/** Resolve a caller-supplied busy_timeout, defaulting rather than using 0. */
|
|
582
|
+
export const SQLITE_PRIMARY_CACHE_SIZE = -131072;
|
|
583
|
+
export const SQLITE_READ_CACHE_SIZE = -65536;
|
|
584
|
+
|
|
585
|
+
const SQLITE_MAX_REQUESTED_MMAP_BYTES = 8 * 1024 * 1024 * 1024;
|
|
586
|
+
const SQLITE_32BIT_MMAP_BYTES = 268435456;
|
|
587
|
+
|
|
588
|
+
const IS_64_BIT_ARCH =
|
|
589
|
+
process.arch === "x64" ||
|
|
590
|
+
process.arch === "arm64" ||
|
|
591
|
+
process.arch === "ppc64" ||
|
|
592
|
+
process.arch === "s390x" ||
|
|
593
|
+
process.arch === "riscv64" ||
|
|
594
|
+
process.arch === "loong64";
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* Compute the requested SQLite mmap_size in bytes: on 64-bit systems, up to
|
|
598
|
+
* 8 GiB bounded by half of total system memory (SQLite clamps to its compile-time
|
|
599
|
+
* MAX_MMAP_SIZE); on 32-bit systems, 256 MiB.
|
|
600
|
+
*/
|
|
601
|
+
export function computeRequestedMmapSizeBytes(
|
|
602
|
+
totalMemoryBytes: number = totalmem(),
|
|
603
|
+
is64Bit: boolean = IS_64_BIT_ARCH
|
|
604
|
+
): number {
|
|
605
|
+
if (!is64Bit) {
|
|
606
|
+
return SQLITE_32BIT_MMAP_BYTES;
|
|
607
|
+
}
|
|
608
|
+
const halfRam = Math.floor(Math.max(0, totalMemoryBytes) * 0.5);
|
|
609
|
+
return Math.min(SQLITE_MAX_REQUESTED_MMAP_BYTES, halfRam);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Apply shared SQLite memory/I/O PRAGMAs across all database open paths
|
|
614
|
+
* (`open`, `openReadOnly`, `openReadDb`) and return the effective `mmap_size`
|
|
615
|
+
* read back from SQLite. Never throws when mmap_size is clamped or unsupported.
|
|
616
|
+
*/
|
|
617
|
+
export function applySqlitePerformancePragmas(
|
|
618
|
+
db: Database,
|
|
619
|
+
role: "primary" | "read"
|
|
620
|
+
): number {
|
|
621
|
+
db.exec("PRAGMA temp_store = MEMORY");
|
|
622
|
+
db.exec(
|
|
623
|
+
`PRAGMA cache_size = ${
|
|
624
|
+
role === "primary" ? SQLITE_PRIMARY_CACHE_SIZE : SQLITE_READ_CACHE_SIZE
|
|
625
|
+
}`
|
|
626
|
+
);
|
|
627
|
+
const requestedMmap = computeRequestedMmapSizeBytes();
|
|
628
|
+
try {
|
|
629
|
+
db.exec(`PRAGMA mmap_size = ${requestedMmap}`);
|
|
630
|
+
} catch {
|
|
631
|
+
// Platforms/filesystems that reject mmap_size keep default file I/O.
|
|
632
|
+
}
|
|
633
|
+
try {
|
|
634
|
+
return (
|
|
635
|
+
db.query<{ mmap_size: number }, []>("PRAGMA mmap_size").get()
|
|
636
|
+
?.mmap_size ?? 0
|
|
637
|
+
);
|
|
638
|
+
} catch {
|
|
639
|
+
return 0;
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
578
643
|
function resolveBusyTimeoutMs(busyTimeoutMs?: number): number {
|
|
579
644
|
if (
|
|
580
645
|
busyTimeoutMs === undefined ||
|
|
@@ -632,6 +697,16 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
632
697
|
private shutdownDeadline?: number;
|
|
633
698
|
private contextGeneration = 0;
|
|
634
699
|
private chunkingGeneration = 0;
|
|
700
|
+
private staleIndexedCache: {
|
|
701
|
+
dv: number;
|
|
702
|
+
tc: number;
|
|
703
|
+
indexedNames: string[];
|
|
704
|
+
} | null = null;
|
|
705
|
+
private dateFieldsCache: {
|
|
706
|
+
dv: number;
|
|
707
|
+
tc: number;
|
|
708
|
+
byCollection: Map<string, string[]>;
|
|
709
|
+
} | null = null;
|
|
635
710
|
|
|
636
711
|
// ─────────────────────────────────────────────────────────────────────────
|
|
637
712
|
// Lifecycle
|
|
@@ -657,17 +732,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
657
732
|
);
|
|
658
733
|
|
|
659
734
|
// Keep WAL everywhere so readers can continue while a writer is active.
|
|
660
|
-
// CI still relaxes fsync
|
|
661
|
-
//
|
|
735
|
+
// CI still relaxes fsync for speed, but MEMORY journal mode breaks the
|
|
736
|
+
// cross-process read/write behavior we rely on in CLI tests.
|
|
737
|
+
let isWal = false;
|
|
662
738
|
try {
|
|
663
|
-
|
|
739
|
+
let journalMode = this.db
|
|
664
740
|
.query<{ journal_mode: string }, []>("PRAGMA journal_mode")
|
|
665
741
|
.get()?.journal_mode;
|
|
666
742
|
tracePhase(`db: journal_mode ${journalMode}`);
|
|
667
743
|
if (journalMode?.toLowerCase() !== "wal") {
|
|
668
|
-
this.db
|
|
669
|
-
|
|
744
|
+
journalMode = this.db
|
|
745
|
+
.query<{ journal_mode: string }, []>("PRAGMA journal_mode = WAL")
|
|
746
|
+
.get()?.journal_mode;
|
|
747
|
+
tracePhase(`db: journal_mode set to ${journalMode}`);
|
|
670
748
|
}
|
|
749
|
+
isWal = journalMode?.toLowerCase() === "wal";
|
|
671
750
|
} catch (cause) {
|
|
672
751
|
if (!isDatabaseLockedError(cause)) {
|
|
673
752
|
throw cause;
|
|
@@ -677,9 +756,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
677
756
|
// rely on the existing DB journal mode instead of failing open().
|
|
678
757
|
}
|
|
679
758
|
|
|
759
|
+
applySqlitePerformancePragmas(this.db, "primary");
|
|
760
|
+
|
|
680
761
|
if (process.env.CI) {
|
|
681
762
|
this.db.exec("PRAGMA synchronous = OFF");
|
|
682
|
-
|
|
763
|
+
} else if (isWal) {
|
|
764
|
+
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
683
765
|
}
|
|
684
766
|
|
|
685
767
|
// Load fts5-snowball extension if using snowball tokenizer
|
|
@@ -729,6 +811,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
729
811
|
this.db.exec(
|
|
730
812
|
`PRAGMA busy_timeout = ${resolveBusyTimeoutMs(busyTimeoutMs)}`
|
|
731
813
|
);
|
|
814
|
+
applySqlitePerformancePragmas(this.db, "read");
|
|
732
815
|
this.contextGeneration += 1;
|
|
733
816
|
return ok(undefined);
|
|
734
817
|
} catch (cause) {
|
|
@@ -746,6 +829,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
746
829
|
|
|
747
830
|
async close(): Promise<void> {
|
|
748
831
|
this.fenceForShutdown();
|
|
832
|
+
this.staleIndexedCache = null;
|
|
833
|
+
this.dateFieldsCache = null;
|
|
749
834
|
this.readDb?.close(false);
|
|
750
835
|
this.readDb = null;
|
|
751
836
|
if (this.db) {
|
|
@@ -831,6 +916,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
831
916
|
main.query<{ timeout: number }, []>("PRAGMA busy_timeout").get()
|
|
832
917
|
?.timeout ?? DEFAULT_BUSY_TIMEOUT_MS;
|
|
833
918
|
db.exec(`PRAGMA busy_timeout = ${busyTimeout}`);
|
|
919
|
+
applySqlitePerformancePragmas(db, "read");
|
|
834
920
|
if (this.ftsTokenizer.startsWith("snowball")) {
|
|
835
921
|
const snowball = loadFts5Snowball(db);
|
|
836
922
|
if (!snowball.loaded)
|
|
@@ -1105,20 +1191,47 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1105
1191
|
}
|
|
1106
1192
|
}
|
|
1107
1193
|
|
|
1194
|
+
private readDbVersionTuple(db: Database): { dv: number; tc: number } {
|
|
1195
|
+
const row = db
|
|
1196
|
+
.query<{ dv: number; tc: number }, []>(
|
|
1197
|
+
"SELECT (SELECT * FROM pragma_data_version) AS dv, total_changes() AS tc"
|
|
1198
|
+
)
|
|
1199
|
+
.get();
|
|
1200
|
+
return row ?? { dv: 0, tc: 0 };
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1108
1203
|
/**
|
|
1109
1204
|
* Indexed collections `configured` omits, checked cheaply on each read of a
|
|
1110
1205
|
* long-lived client: another client may add a collection after it opened.
|
|
1206
|
+
* Memoized by (PRAGMA data_version, total_changes()) so unchanged reads skip
|
|
1207
|
+
* the collection/document EXISTS scan.
|
|
1111
1208
|
*/
|
|
1112
1209
|
staleIndexedCollections(configured: readonly string[]): StaleCollection[] {
|
|
1113
1210
|
const db = this.ensureOpen();
|
|
1211
|
+
const canCache = !db.inTransaction;
|
|
1212
|
+
const { dv, tc } = this.readDbVersionTuple(db);
|
|
1213
|
+
let indexedNames: string[];
|
|
1214
|
+
if (
|
|
1215
|
+
canCache &&
|
|
1216
|
+
this.staleIndexedCache &&
|
|
1217
|
+
this.staleIndexedCache.dv === dv &&
|
|
1218
|
+
this.staleIndexedCache.tc === tc
|
|
1219
|
+
) {
|
|
1220
|
+
indexedNames = this.staleIndexedCache.indexedNames;
|
|
1221
|
+
} else {
|
|
1222
|
+
indexedNames = db
|
|
1223
|
+
.query<{ name: string }, []>(
|
|
1224
|
+
`SELECT c.name AS name FROM collections c
|
|
1225
|
+
WHERE EXISTS (SELECT 1 FROM documents d WHERE d.collection = c.name)`
|
|
1226
|
+
)
|
|
1227
|
+
.all()
|
|
1228
|
+
.map(({ name }) => name);
|
|
1229
|
+
if (canCache) {
|
|
1230
|
+
this.staleIndexedCache = { dv, tc, indexedNames };
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1114
1233
|
const listed = new Set(configured);
|
|
1115
|
-
|
|
1116
|
-
.query<{ name: string }, []>(
|
|
1117
|
-
`SELECT c.name AS name FROM collections c
|
|
1118
|
-
WHERE EXISTS (SELECT 1 FROM documents d WHERE d.collection = c.name)`
|
|
1119
|
-
)
|
|
1120
|
-
.all();
|
|
1121
|
-
return indexed.some(({ name }) => !listed.has(name))
|
|
1234
|
+
return indexedNames.some((name) => !listed.has(name))
|
|
1122
1235
|
? this.queryStaleCollections(db, configured).filter(
|
|
1123
1236
|
(c) => c.documents > 0
|
|
1124
1237
|
)
|
|
@@ -1773,9 +1886,23 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1773
1886
|
const uri = buildUri(doc.collection, doc.relPath);
|
|
1774
1887
|
|
|
1775
1888
|
const transaction = db.transaction((): UpsertDocumentResult => {
|
|
1889
|
+
interface PreviousDocumentSnapshotRow {
|
|
1890
|
+
id: number;
|
|
1891
|
+
collection: string;
|
|
1892
|
+
rel_path: string;
|
|
1893
|
+
docid: string;
|
|
1894
|
+
uri: string;
|
|
1895
|
+
source_hash: string;
|
|
1896
|
+
mirror_hash: string | null;
|
|
1897
|
+
active: number;
|
|
1898
|
+
title: string | null;
|
|
1899
|
+
}
|
|
1776
1900
|
const previousRow = db
|
|
1777
|
-
.query<
|
|
1778
|
-
|
|
1901
|
+
.query<PreviousDocumentSnapshotRow, [string, string]>(
|
|
1902
|
+
`SELECT id, collection, rel_path, docid, uri, source_hash,
|
|
1903
|
+
mirror_hash, active, title
|
|
1904
|
+
FROM documents
|
|
1905
|
+
WHERE collection = ? AND rel_path = ?`
|
|
1779
1906
|
)
|
|
1780
1907
|
.get(doc.collection, doc.relPath);
|
|
1781
1908
|
const legacyTitles = snapshotLegacyTitles(
|
|
@@ -1788,8 +1915,9 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1788
1915
|
: []
|
|
1789
1916
|
);
|
|
1790
1917
|
|
|
1791
|
-
db
|
|
1792
|
-
|
|
1918
|
+
const idRow = db
|
|
1919
|
+
.query<{ id: number }, (string | number | null)[]>(
|
|
1920
|
+
`
|
|
1793
1921
|
INSERT INTO documents (
|
|
1794
1922
|
collection, rel_path, source_hash, source_mime, source_ext,
|
|
1795
1923
|
source_size, source_mtime, source_ctime, docid, uri, title, mirror_hash,
|
|
@@ -1837,8 +1965,10 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1837
1965
|
last_error_at = excluded.last_error_at,
|
|
1838
1966
|
ingest_version = excluded.ingest_version,
|
|
1839
1967
|
updated_at = datetime('now')
|
|
1840
|
-
|
|
1841
|
-
|
|
1968
|
+
RETURNING id
|
|
1969
|
+
`
|
|
1970
|
+
)
|
|
1971
|
+
.get(
|
|
1842
1972
|
doc.collection,
|
|
1843
1973
|
doc.relPath,
|
|
1844
1974
|
doc.sourceHash,
|
|
@@ -1874,16 +2004,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1874
2004
|
doc.lastErrorCode ?? null,
|
|
1875
2005
|
doc.lastErrorMessage ?? null,
|
|
1876
2006
|
doc.lastErrorCode ? new Date().toISOString() : null,
|
|
1877
|
-
doc.ingestVersion ?? null
|
|
1878
|
-
|
|
1879
|
-
);
|
|
1880
|
-
|
|
1881
|
-
// Get the row id (either inserted or updated)
|
|
1882
|
-
const idRow = db
|
|
1883
|
-
.query<{ id: number }, [string, string]>(
|
|
1884
|
-
"SELECT id FROM documents WHERE collection = ? AND rel_path = ?"
|
|
1885
|
-
)
|
|
1886
|
-
.get(doc.collection, doc.relPath);
|
|
2007
|
+
doc.ingestVersion ?? null
|
|
2008
|
+
);
|
|
1887
2009
|
|
|
1888
2010
|
if (!idRow) {
|
|
1889
2011
|
throw new Error("Failed to get document id after upsert");
|
|
@@ -1898,32 +2020,44 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
1898
2020
|
(previousRow.mirror_hash !== (doc.mirrorHash ?? null) ||
|
|
1899
2021
|
previousRow.title !== (doc.title ?? null))
|
|
1900
2022
|
) {
|
|
1901
|
-
db.
|
|
2023
|
+
db.query("DELETE FROM vector_owners WHERE document_id = ?").run(
|
|
2024
|
+
idRow.id
|
|
2025
|
+
);
|
|
1902
2026
|
}
|
|
1903
2027
|
|
|
1904
2028
|
// Conversion failures deliberately drop mirror ownership. Remove the
|
|
1905
2029
|
// old lexical projection in the same transaction so stale content can
|
|
1906
2030
|
// never join against the newly updated document metadata.
|
|
1907
2031
|
if (doc.mirrorHash == null) {
|
|
1908
|
-
db.
|
|
1909
|
-
db.
|
|
1910
|
-
|
|
1911
|
-
|
|
2032
|
+
db.query("DELETE FROM documents_fts WHERE rowid = ?").run(idRow.id);
|
|
2033
|
+
db.query(
|
|
2034
|
+
"UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?"
|
|
2035
|
+
).run(idRow.id);
|
|
1912
2036
|
}
|
|
1913
2037
|
|
|
1914
2038
|
if (doc.changeJournal !== false) {
|
|
1915
|
-
const
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
2039
|
+
const previous: DocumentChangeSnapshot | null = previousRow
|
|
2040
|
+
? {
|
|
2041
|
+
id: previousRow.id,
|
|
2042
|
+
collection: previousRow.collection,
|
|
2043
|
+
relPath: previousRow.rel_path,
|
|
2044
|
+
docid: previousRow.docid,
|
|
2045
|
+
uri: previousRow.uri,
|
|
2046
|
+
sourceHash: previousRow.source_hash,
|
|
2047
|
+
mirrorHash: previousRow.mirror_hash,
|
|
2048
|
+
active: previousRow.active === 1,
|
|
2049
|
+
}
|
|
1925
2050
|
: null;
|
|
1926
|
-
const next =
|
|
2051
|
+
const next: DocumentChangeSnapshot = {
|
|
2052
|
+
id: idRow.id,
|
|
2053
|
+
collection: doc.collection,
|
|
2054
|
+
relPath: doc.relPath,
|
|
2055
|
+
docid,
|
|
2056
|
+
uri,
|
|
2057
|
+
sourceHash: doc.sourceHash,
|
|
2058
|
+
mirrorHash: doc.mirrorHash ?? null,
|
|
2059
|
+
active: true,
|
|
2060
|
+
};
|
|
1927
2061
|
const kind: DocumentChangeKind | null =
|
|
1928
2062
|
previous === null
|
|
1929
2063
|
? "create"
|
|
@@ -2126,6 +2260,59 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2126
2260
|
}
|
|
2127
2261
|
}
|
|
2128
2262
|
|
|
2263
|
+
async listGraphDocumentIdentities(): Promise<
|
|
2264
|
+
StoreResult<GraphDocumentIdentity[]>
|
|
2265
|
+
> {
|
|
2266
|
+
try {
|
|
2267
|
+
const db = this.ensureOpen();
|
|
2268
|
+
const rows = db
|
|
2269
|
+
.query<
|
|
2270
|
+
{
|
|
2271
|
+
documentId: number;
|
|
2272
|
+
collection: string;
|
|
2273
|
+
relPath: string;
|
|
2274
|
+
docid: string;
|
|
2275
|
+
uri: string;
|
|
2276
|
+
title: string | null;
|
|
2277
|
+
mirrorHash: string | null;
|
|
2278
|
+
sourceHash: string;
|
|
2279
|
+
contentType: string | null;
|
|
2280
|
+
active: number;
|
|
2281
|
+
},
|
|
2282
|
+
[]
|
|
2283
|
+
>(
|
|
2284
|
+
`SELECT id AS documentId, collection, rel_path AS relPath, docid, uri,
|
|
2285
|
+
title, mirror_hash AS mirrorHash, source_hash AS sourceHash,
|
|
2286
|
+
content_type AS contentType, active
|
|
2287
|
+
FROM documents`
|
|
2288
|
+
)
|
|
2289
|
+
.all();
|
|
2290
|
+
|
|
2291
|
+
return ok(
|
|
2292
|
+
rows.map((row) => ({
|
|
2293
|
+
documentId: row.documentId,
|
|
2294
|
+
collection: row.collection,
|
|
2295
|
+
relPath: row.relPath,
|
|
2296
|
+
docid: row.docid,
|
|
2297
|
+
uri: row.uri,
|
|
2298
|
+
title: row.title,
|
|
2299
|
+
mirrorHash: row.mirrorHash,
|
|
2300
|
+
sourceHash: row.sourceHash,
|
|
2301
|
+
contentType: row.contentType,
|
|
2302
|
+
active: row.active === 1,
|
|
2303
|
+
}))
|
|
2304
|
+
);
|
|
2305
|
+
} catch (cause) {
|
|
2306
|
+
return err(
|
|
2307
|
+
"QUERY_FAILED",
|
|
2308
|
+
cause instanceof Error
|
|
2309
|
+
? cause.message
|
|
2310
|
+
: "Failed to list graph document identities",
|
|
2311
|
+
cause
|
|
2312
|
+
);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2129
2316
|
async listDocumentsForAudit(options: {
|
|
2130
2317
|
collections: readonly string[];
|
|
2131
2318
|
pathPrefixes: readonly string[];
|
|
@@ -2412,33 +2599,23 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2412
2599
|
}
|
|
2413
2600
|
|
|
2414
2601
|
const db = this.ensureOpen();
|
|
2415
|
-
const
|
|
2416
|
-
|
|
2417
|
-
// SQLite SQLITE_LIMIT_VARIABLE_NUMBER defaults to 999.
|
|
2418
|
-
// Reserve headroom for optional non-IN parameters.
|
|
2419
|
-
const SQL_PARAM_LIMIT = 898;
|
|
2420
|
-
|
|
2421
|
-
for (let i = 0; i < uniqueHashes.length; i += SQL_PARAM_LIMIT) {
|
|
2422
|
-
const batch = uniqueHashes.slice(i, i + SQL_PARAM_LIMIT);
|
|
2423
|
-
const placeholders = batch.map(() => "?").join(",");
|
|
2424
|
-
const clauses = [`mirror_hash IN (${placeholders})`];
|
|
2425
|
-
const params: string[] = [...batch];
|
|
2426
|
-
|
|
2427
|
-
if (options.activeOnly ?? true) {
|
|
2428
|
-
clauses.push("active = 1");
|
|
2429
|
-
}
|
|
2430
|
-
if (options.collection) {
|
|
2431
|
-
clauses.push("collection = ?");
|
|
2432
|
-
params.push(options.collection);
|
|
2433
|
-
}
|
|
2434
|
-
if (options.collections !== undefined) {
|
|
2435
|
-
clauses.push("collection IN (SELECT value FROM json_each(?))");
|
|
2436
|
-
params.push(JSON.stringify(options.collections));
|
|
2437
|
-
}
|
|
2602
|
+
const clauses = ["mirror_hash IN (SELECT value FROM json_each(?))"];
|
|
2603
|
+
const params: string[] = [JSON.stringify(uniqueHashes)];
|
|
2438
2604
|
|
|
2439
|
-
|
|
2440
|
-
|
|
2605
|
+
if (options.activeOnly ?? true) {
|
|
2606
|
+
clauses.push("active = 1");
|
|
2441
2607
|
}
|
|
2608
|
+
if (options.collection) {
|
|
2609
|
+
clauses.push("collection = ?");
|
|
2610
|
+
params.push(options.collection);
|
|
2611
|
+
}
|
|
2612
|
+
if (options.collections !== undefined) {
|
|
2613
|
+
clauses.push("collection IN (SELECT value FROM json_each(?))");
|
|
2614
|
+
params.push(JSON.stringify(options.collections));
|
|
2615
|
+
}
|
|
2616
|
+
|
|
2617
|
+
const sql = `SELECT * FROM documents INDEXED BY idx_documents_mirror_hash WHERE ${clauses.join(" AND ")} ORDER BY id`;
|
|
2618
|
+
const rows = db.query<DbDocumentRow, string[]>(sql).all(...params);
|
|
2442
2619
|
|
|
2443
2620
|
return ok(rows.map(mapDocumentRow));
|
|
2444
2621
|
} catch (cause) {
|
|
@@ -2473,33 +2650,26 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2473
2650
|
}
|
|
2474
2651
|
|
|
2475
2652
|
const db = this.ensureOpen();
|
|
2476
|
-
const
|
|
2477
|
-
const
|
|
2478
|
-
|
|
2479
|
-
for (let i = 0; i < uniqueDocids.length; i += SQL_PARAM_LIMIT) {
|
|
2480
|
-
const batch = uniqueDocids.slice(i, i + SQL_PARAM_LIMIT);
|
|
2481
|
-
const placeholders = batch.map(() => "?").join(",");
|
|
2482
|
-
const clauses = [`docid IN (${placeholders})`];
|
|
2483
|
-
const params: (string | number)[] = [...batch];
|
|
2653
|
+
const clauses = ["docid IN (SELECT value FROM json_each(?))"];
|
|
2654
|
+
const params: (string | number)[] = [JSON.stringify(uniqueDocids)];
|
|
2484
2655
|
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2656
|
+
if (options.activeOnly ?? true) {
|
|
2657
|
+
clauses.push("active = 1");
|
|
2658
|
+
}
|
|
2659
|
+
if (options.collection) {
|
|
2660
|
+
clauses.push("collection = ?");
|
|
2661
|
+
params.push(options.collection);
|
|
2662
|
+
}
|
|
2492
2663
|
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
}
|
|
2498
|
-
const sql = `SELECT * FROM documents WHERE ${clauses.join(" AND ")} ORDER BY id`;
|
|
2499
|
-
rows.push(
|
|
2500
|
-
...db.query<DbDocumentRow, (string | number)[]>(sql).all(...params)
|
|
2501
|
-
);
|
|
2664
|
+
if (options.eligibility) {
|
|
2665
|
+
const eligible = buildEligibleDocumentQuery(options.eligibility, db);
|
|
2666
|
+
clauses.push(`id IN (SELECT id FROM (${eligible.sql}))`);
|
|
2667
|
+
params.push(...eligible.params);
|
|
2502
2668
|
}
|
|
2669
|
+
const sql = `SELECT * FROM documents WHERE ${clauses.join(" AND ")} ORDER BY id`;
|
|
2670
|
+
const rows = db
|
|
2671
|
+
.query<DbDocumentRow, (string | number)[]>(sql)
|
|
2672
|
+
.all(...params);
|
|
2503
2673
|
|
|
2504
2674
|
return ok(rows.map(mapDocumentRow));
|
|
2505
2675
|
} catch (cause) {
|
|
@@ -2576,11 +2746,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2576
2746
|
}
|
|
2577
2747
|
|
|
2578
2748
|
if (options.categories && options.categories.length > 0) {
|
|
2579
|
-
const
|
|
2749
|
+
const categoriesJson = JSON.stringify(options.categories);
|
|
2580
2750
|
conditions.push(
|
|
2581
|
-
|
|
2751
|
+
"(d.content_type IN (SELECT value FROM json_each(?)) OR EXISTS (SELECT 1 FROM json_each(COALESCE(d.categories, '[]')) jc WHERE jc.value IN (SELECT value FROM json_each(?))))"
|
|
2582
2752
|
);
|
|
2583
|
-
params.push(
|
|
2753
|
+
params.push(categoriesJson, categoriesJson);
|
|
2584
2754
|
}
|
|
2585
2755
|
|
|
2586
2756
|
if (options.author) {
|
|
@@ -2590,11 +2760,10 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2590
2760
|
|
|
2591
2761
|
// tagsAny: document has at least one of these tags (OR)
|
|
2592
2762
|
if (tagsAny && tagsAny.length > 0) {
|
|
2593
|
-
const placeholders = tagsAny.map(() => "?").join(",");
|
|
2594
2763
|
conditions.push(
|
|
2595
|
-
|
|
2764
|
+
"EXISTS (SELECT 1 FROM doc_tags dt WHERE dt.document_id = d.id AND dt.tag IN (SELECT value FROM json_each(?)))"
|
|
2596
2765
|
);
|
|
2597
|
-
params.push(
|
|
2766
|
+
params.push(JSON.stringify(tagsAny));
|
|
2598
2767
|
}
|
|
2599
2768
|
|
|
2600
2769
|
// tagsAll: document has all of these tags (AND)
|
|
@@ -2648,6 +2817,24 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2648
2817
|
): Promise<StoreResult<string[]>> {
|
|
2649
2818
|
try {
|
|
2650
2819
|
const db = this.ensureOpen();
|
|
2820
|
+
const canCache = !db.inTransaction;
|
|
2821
|
+
const { dv, tc } = this.readDbVersionTuple(db);
|
|
2822
|
+
const cacheKey = collection ?? "";
|
|
2823
|
+
if (canCache) {
|
|
2824
|
+
if (
|
|
2825
|
+
this.dateFieldsCache &&
|
|
2826
|
+
this.dateFieldsCache.dv === dv &&
|
|
2827
|
+
this.dateFieldsCache.tc === tc
|
|
2828
|
+
) {
|
|
2829
|
+
const hit = this.dateFieldsCache.byCollection.get(cacheKey);
|
|
2830
|
+
if (hit) {
|
|
2831
|
+
return ok([...hit]);
|
|
2832
|
+
}
|
|
2833
|
+
} else {
|
|
2834
|
+
this.dateFieldsCache = { dv, tc, byCollection: new Map() };
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
|
|
2651
2838
|
const conditions: string[] = [
|
|
2652
2839
|
"d.active = 1",
|
|
2653
2840
|
"d.date_fields IS NOT NULL",
|
|
@@ -2667,8 +2854,14 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2667
2854
|
ORDER BY jf.key ASC
|
|
2668
2855
|
`;
|
|
2669
2856
|
|
|
2670
|
-
const
|
|
2671
|
-
|
|
2857
|
+
const fields = db
|
|
2858
|
+
.query<{ field: string }, string[]>(sql)
|
|
2859
|
+
.all(...params)
|
|
2860
|
+
.map((r) => r.field);
|
|
2861
|
+
if (canCache && this.dateFieldsCache) {
|
|
2862
|
+
this.dateFieldsCache.byCollection.set(cacheKey, fields);
|
|
2863
|
+
}
|
|
2864
|
+
return ok([...fields]);
|
|
2672
2865
|
} catch (cause) {
|
|
2673
2866
|
return err(
|
|
2674
2867
|
"QUERY_FAILED",
|
|
@@ -2680,6 +2873,210 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2680
2873
|
}
|
|
2681
2874
|
}
|
|
2682
2875
|
|
|
2876
|
+
/**
|
|
2877
|
+
* Targeted lookup for similarity hit hydration: fetches only the active
|
|
2878
|
+
* documents owning the returned vector hits instead of scanning the entire
|
|
2879
|
+
* documents table.
|
|
2880
|
+
*/
|
|
2881
|
+
async listDocumentsForSimilarity(options: {
|
|
2882
|
+
documentIds: readonly number[];
|
|
2883
|
+
mirrorHashes: readonly string[];
|
|
2884
|
+
collection?: string;
|
|
2885
|
+
}): Promise<
|
|
2886
|
+
StoreResult<
|
|
2887
|
+
Array<{
|
|
2888
|
+
id: number;
|
|
2889
|
+
docid: string;
|
|
2890
|
+
uri: string;
|
|
2891
|
+
title: string | null;
|
|
2892
|
+
collection: string;
|
|
2893
|
+
relPath: string;
|
|
2894
|
+
mirrorHash: string;
|
|
2895
|
+
active: boolean;
|
|
2896
|
+
}>
|
|
2897
|
+
>
|
|
2898
|
+
> {
|
|
2899
|
+
const uniqueIds = [...new Set(options.documentIds)];
|
|
2900
|
+
const uniqueHashes = [...new Set(options.mirrorHashes)];
|
|
2901
|
+
if (uniqueIds.length === 0 && uniqueHashes.length === 0) {
|
|
2902
|
+
return ok([]);
|
|
2903
|
+
}
|
|
2904
|
+
try {
|
|
2905
|
+
const db = this.ensureOpen();
|
|
2906
|
+
const collectionClause = options.collection
|
|
2907
|
+
? " AND d.collection = ?"
|
|
2908
|
+
: "";
|
|
2909
|
+
const legs: string[] = [];
|
|
2910
|
+
const params: string[] = [];
|
|
2911
|
+
|
|
2912
|
+
// Drive each leg from json_each(?) via CROSS JOIN so SQLite seeks by PK
|
|
2913
|
+
// or idx_documents_mirror_hash instead of scanning idx_documents_collection
|
|
2914
|
+
// with a Bloom filter on scoped lookups.
|
|
2915
|
+
if (uniqueIds.length > 0) {
|
|
2916
|
+
legs.push(
|
|
2917
|
+
`SELECT d.id AS id, d.docid, d.uri, d.title, d.collection, d.rel_path, d.mirror_hash
|
|
2918
|
+
FROM json_each(?) AS j
|
|
2919
|
+
CROSS JOIN documents d ON d.id = j.value
|
|
2920
|
+
WHERE d.active = 1
|
|
2921
|
+
AND d.mirror_hash IS NOT NULL${collectionClause}`
|
|
2922
|
+
);
|
|
2923
|
+
params.push(JSON.stringify(uniqueIds));
|
|
2924
|
+
if (options.collection) params.push(options.collection);
|
|
2925
|
+
}
|
|
2926
|
+
|
|
2927
|
+
if (uniqueHashes.length > 0) {
|
|
2928
|
+
legs.push(
|
|
2929
|
+
`SELECT d.id AS id, d.docid, d.uri, d.title, d.collection, d.rel_path, d.mirror_hash
|
|
2930
|
+
FROM json_each(?) AS j
|
|
2931
|
+
CROSS JOIN documents d INDEXED BY idx_documents_mirror_hash ON d.mirror_hash = j.value
|
|
2932
|
+
WHERE d.active = 1
|
|
2933
|
+
AND d.mirror_hash IS NOT NULL${collectionClause}`
|
|
2934
|
+
);
|
|
2935
|
+
params.push(JSON.stringify(uniqueHashes));
|
|
2936
|
+
if (options.collection) params.push(options.collection);
|
|
2937
|
+
}
|
|
2938
|
+
|
|
2939
|
+
const sql = `${legs.join("\nUNION\n")}\nORDER BY 1`;
|
|
2940
|
+
const rows = db
|
|
2941
|
+
.query<
|
|
2942
|
+
{
|
|
2943
|
+
id: number;
|
|
2944
|
+
docid: string;
|
|
2945
|
+
uri: string;
|
|
2946
|
+
title: string | null;
|
|
2947
|
+
collection: string;
|
|
2948
|
+
rel_path: string;
|
|
2949
|
+
mirror_hash: string;
|
|
2950
|
+
},
|
|
2951
|
+
string[]
|
|
2952
|
+
>(sql)
|
|
2953
|
+
.all(...params);
|
|
2954
|
+
|
|
2955
|
+
return ok(
|
|
2956
|
+
rows.map((row) => ({
|
|
2957
|
+
id: row.id,
|
|
2958
|
+
docid: row.docid,
|
|
2959
|
+
uri: row.uri,
|
|
2960
|
+
title: row.title,
|
|
2961
|
+
collection: row.collection,
|
|
2962
|
+
relPath: row.rel_path,
|
|
2963
|
+
mirrorHash: row.mirror_hash,
|
|
2964
|
+
active: true,
|
|
2965
|
+
}))
|
|
2966
|
+
);
|
|
2967
|
+
} catch (cause) {
|
|
2968
|
+
return err(
|
|
2969
|
+
"QUERY_FAILED",
|
|
2970
|
+
cause instanceof Error
|
|
2971
|
+
? cause.message
|
|
2972
|
+
: "Failed to load similarity documents",
|
|
2973
|
+
cause
|
|
2974
|
+
);
|
|
2975
|
+
}
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2978
|
+
/**
|
|
2979
|
+
* Minimal-column SQL autocomplete search.
|
|
2980
|
+
* Selects only the 5 scalar columns needed for autocomplete (never hydrating
|
|
2981
|
+
* full DocumentRow blobs or parsing typedMetadata JSON). For non-empty
|
|
2982
|
+
* single-token ASCII queries, pushes an ASCII substring pre-filter into SQL
|
|
2983
|
+
* while still passing rows containing any non-ASCII character (so Unicode
|
|
2984
|
+
* case folding like `Kelvin` -> `kelvin` is never missed), then applies
|
|
2985
|
+
* exact JS display-title resolution, `.toLowerCase().includes()`,
|
|
2986
|
+
* `.localeCompare()` ordering, and `.slice(0, limit)`.
|
|
2987
|
+
*/
|
|
2988
|
+
async searchDocumentsForAutocomplete(options: {
|
|
2989
|
+
query: string;
|
|
2990
|
+
collection?: string;
|
|
2991
|
+
limit: number;
|
|
2992
|
+
}): Promise<
|
|
2993
|
+
StoreResult<
|
|
2994
|
+
Array<{
|
|
2995
|
+
docid: string;
|
|
2996
|
+
uri: string;
|
|
2997
|
+
title: string;
|
|
2998
|
+
collection: string;
|
|
2999
|
+
}>
|
|
3000
|
+
>
|
|
3001
|
+
> {
|
|
3002
|
+
try {
|
|
3003
|
+
const db = this.ensureOpen();
|
|
3004
|
+
const query = options.query.trim().toLowerCase();
|
|
3005
|
+
// Preserve Array.prototype.slice(0, limit) semantics identically
|
|
3006
|
+
// (including fractional limits like 1.5 -> 1 and negative limits like -1).
|
|
3007
|
+
const sliceLimit = Math.min(options.limit, 20);
|
|
3008
|
+
if (sliceLimit === 0) {
|
|
3009
|
+
return ok([]);
|
|
3010
|
+
}
|
|
3011
|
+
const isAsciiSingleSegment =
|
|
3012
|
+
query.length > 0 && !/[^\x20-\x7f]/.test(query) && !query.includes(" ");
|
|
3013
|
+
|
|
3014
|
+
const resolveTitle = (title: string | null, relPath: string): string =>
|
|
3015
|
+
title ??
|
|
3016
|
+
relPath
|
|
3017
|
+
.split("/")
|
|
3018
|
+
.pop()
|
|
3019
|
+
?.replace(/\.[^.]+$/, "") ??
|
|
3020
|
+
relPath;
|
|
3021
|
+
|
|
3022
|
+
type MinimalRow = {
|
|
3023
|
+
docid: string;
|
|
3024
|
+
uri: string;
|
|
3025
|
+
title: string | null;
|
|
3026
|
+
rel_path: string;
|
|
3027
|
+
collection: string;
|
|
3028
|
+
};
|
|
3029
|
+
|
|
3030
|
+
const conditions = ["active = 1"];
|
|
3031
|
+
const params: string[] = [];
|
|
3032
|
+
if (options.collection) {
|
|
3033
|
+
conditions.push("collection = ?");
|
|
3034
|
+
params.push(options.collection);
|
|
3035
|
+
}
|
|
3036
|
+
if (isAsciiSingleSegment) {
|
|
3037
|
+
// Pure-ASCII rows can only match if SQLite's ASCII lower() matches
|
|
3038
|
+
// title or uri (which includes rel_path); pass rows containing any
|
|
3039
|
+
// non-ASCII byte through so Unicode case folding matches identically.
|
|
3040
|
+
conditions.push(
|
|
3041
|
+
"(instr(lower(COALESCE(title, '')), ?) > 0 OR instr(lower(uri), ?) > 0 OR COALESCE(title, '') GLOB '*[^' || char(1) || '-' || char(127) || ']*' OR uri GLOB '*[^' || char(1) || '-' || char(127) || ']*')"
|
|
3042
|
+
);
|
|
3043
|
+
params.push(query, query);
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
const rows = db
|
|
3047
|
+
.query<MinimalRow, string[]>(
|
|
3048
|
+
`SELECT docid, uri, title, rel_path, collection
|
|
3049
|
+
FROM documents
|
|
3050
|
+
WHERE ${conditions.join(" AND ")}`
|
|
3051
|
+
)
|
|
3052
|
+
.all(...params);
|
|
3053
|
+
|
|
3054
|
+
const candidates = rows
|
|
3055
|
+
.map((row) => ({
|
|
3056
|
+
docid: row.docid,
|
|
3057
|
+
uri: row.uri,
|
|
3058
|
+
title: resolveTitle(row.title, row.rel_path),
|
|
3059
|
+
collection: row.collection,
|
|
3060
|
+
}))
|
|
3061
|
+
.filter((doc) => {
|
|
3062
|
+
if (!query) return true;
|
|
3063
|
+
return `${doc.title} ${doc.uri}`.toLowerCase().includes(query);
|
|
3064
|
+
})
|
|
3065
|
+
.sort((a, b) => a.title.localeCompare(b.title))
|
|
3066
|
+
.slice(0, sliceLimit);
|
|
3067
|
+
|
|
3068
|
+
return ok(candidates);
|
|
3069
|
+
} catch (cause) {
|
|
3070
|
+
return err(
|
|
3071
|
+
"QUERY_FAILED",
|
|
3072
|
+
cause instanceof Error
|
|
3073
|
+
? cause.message
|
|
3074
|
+
: "Failed to search autocomplete documents",
|
|
3075
|
+
cause
|
|
3076
|
+
);
|
|
3077
|
+
}
|
|
3078
|
+
}
|
|
3079
|
+
|
|
2683
3080
|
async markInactive(
|
|
2684
3081
|
collection: string,
|
|
2685
3082
|
relPaths: string[]
|
|
@@ -2692,18 +3089,29 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2692
3089
|
}
|
|
2693
3090
|
|
|
2694
3091
|
const uniquePaths = [...new Set(relPaths)];
|
|
2695
|
-
const
|
|
3092
|
+
const pathsJson = JSON.stringify(uniquePaths);
|
|
2696
3093
|
const transaction = db.transaction((): number => {
|
|
2697
3094
|
const activeRows = db
|
|
2698
|
-
.query<
|
|
2699
|
-
|
|
3095
|
+
.query<
|
|
3096
|
+
{
|
|
3097
|
+
id: number;
|
|
3098
|
+
collection: string;
|
|
3099
|
+
rel_path: string;
|
|
3100
|
+
docid: string;
|
|
3101
|
+
uri: string;
|
|
3102
|
+
source_hash: string;
|
|
3103
|
+
mirror_hash: string | null;
|
|
3104
|
+
},
|
|
3105
|
+
[string, string]
|
|
3106
|
+
>(
|
|
3107
|
+
`SELECT id, collection, rel_path, docid, uri, source_hash, mirror_hash
|
|
2700
3108
|
FROM documents
|
|
2701
3109
|
WHERE collection = ?
|
|
2702
3110
|
AND active = 1
|
|
2703
|
-
AND rel_path IN (
|
|
3111
|
+
AND rel_path IN (SELECT value FROM json_each(?))
|
|
2704
3112
|
ORDER BY rel_path ASC, id ASC`
|
|
2705
3113
|
)
|
|
2706
|
-
.all(collection,
|
|
3114
|
+
.all(collection, pathsJson);
|
|
2707
3115
|
if (activeRows.length === 0) {
|
|
2708
3116
|
return 0;
|
|
2709
3117
|
}
|
|
@@ -2711,13 +3119,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2711
3119
|
db,
|
|
2712
3120
|
activeRows.map((row) => row.mirror_hash)
|
|
2713
3121
|
);
|
|
2714
|
-
db.
|
|
3122
|
+
db.query(
|
|
2715
3123
|
`UPDATE documents SET active = 0, updated_at = datetime('now')
|
|
2716
3124
|
WHERE collection = ?
|
|
2717
3125
|
AND active = 1
|
|
2718
|
-
AND rel_path IN (
|
|
2719
|
-
|
|
2720
|
-
);
|
|
3126
|
+
AND rel_path IN (SELECT value FROM json_each(?))`
|
|
3127
|
+
).run(collection, pathsJson);
|
|
2721
3128
|
// Bun run().changes includes trigger writes; report logical document rows.
|
|
2722
3129
|
const changed =
|
|
2723
3130
|
db.query<{ count: number }, []>("SELECT changes() AS count").get()
|
|
@@ -2725,7 +3132,16 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2725
3132
|
reconcileLegacyTitles(db, legacyTitles);
|
|
2726
3133
|
const observedAtMs = Date.now();
|
|
2727
3134
|
for (const activeRow of activeRows) {
|
|
2728
|
-
const previous =
|
|
3135
|
+
const previous: DocumentChangeSnapshot = {
|
|
3136
|
+
id: activeRow.id,
|
|
3137
|
+
collection: activeRow.collection,
|
|
3138
|
+
relPath: activeRow.rel_path,
|
|
3139
|
+
docid: activeRow.docid,
|
|
3140
|
+
uri: activeRow.uri,
|
|
3141
|
+
sourceHash: activeRow.source_hash,
|
|
3142
|
+
mirrorHash: activeRow.mirror_hash,
|
|
3143
|
+
active: true,
|
|
3144
|
+
};
|
|
2729
3145
|
appendStoredDocumentChange(db, {
|
|
2730
3146
|
documentId: activeRow.id,
|
|
2731
3147
|
collection,
|
|
@@ -2973,24 +3389,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
2973
3389
|
}
|
|
2974
3390
|
|
|
2975
3391
|
const result = new Map<string, string>();
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
offset + SQLITE_SAFE_PARAMETER_BATCH_SIZE
|
|
2984
|
-
);
|
|
2985
|
-
const placeholders = batch.map(() => "?").join(", ");
|
|
2986
|
-
const rows = db
|
|
2987
|
-
.query<DbContentRow, string[]>(
|
|
2988
|
-
`SELECT mirror_hash, markdown FROM content
|
|
2989
|
-
WHERE mirror_hash IN (${placeholders})`
|
|
2990
|
-
)
|
|
2991
|
-
.all(...batch);
|
|
2992
|
-
for (const row of rows) result.set(row.mirror_hash, row.markdown);
|
|
2993
|
-
}
|
|
3392
|
+
const rows = db
|
|
3393
|
+
.query<DbContentRow, [string]>(
|
|
3394
|
+
`SELECT mirror_hash, markdown FROM content
|
|
3395
|
+
WHERE mirror_hash IN (SELECT value FROM json_each(?))`
|
|
3396
|
+
)
|
|
3397
|
+
.all(JSON.stringify(uniqueHashes));
|
|
3398
|
+
for (const row of rows) result.set(row.mirror_hash, row.markdown);
|
|
2994
3399
|
|
|
2995
3400
|
return ok(result);
|
|
2996
3401
|
} catch (cause) {
|
|
@@ -3024,29 +3429,43 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3024
3429
|
);
|
|
3025
3430
|
// Retain stable rows: DELETE cascades erase valid legacy vectors even
|
|
3026
3431
|
// when duplicate ingestion produces exactly the same embedding input.
|
|
3027
|
-
const nextBySequence = new Map(
|
|
3028
|
-
chunks.map((chunk) => [chunk.seq, chunk])
|
|
3029
|
-
);
|
|
3030
3432
|
const existing = db
|
|
3031
3433
|
.query<{ seq: number; text: string }, [string]>(
|
|
3032
3434
|
"SELECT seq, text FROM content_chunks WHERE mirror_hash = ?"
|
|
3033
3435
|
)
|
|
3034
3436
|
.all(mirrorHash);
|
|
3035
|
-
|
|
3036
|
-
const
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
3437
|
+
if (existing.length > 0) {
|
|
3438
|
+
const nextBySequence = new Map(
|
|
3439
|
+
chunks.map((chunk) => [chunk.seq, chunk])
|
|
3440
|
+
);
|
|
3441
|
+
const deleteOwner = db.query<unknown, [string, number]>(
|
|
3442
|
+
"DELETE FROM vector_owners WHERE mirror_hash = ? AND seq = ?"
|
|
3443
|
+
);
|
|
3444
|
+
const deleteChunk = db.query<unknown, [string, number]>(
|
|
3445
|
+
"DELETE FROM content_chunks WHERE mirror_hash = ? AND seq = ?"
|
|
3446
|
+
);
|
|
3447
|
+
for (const old of existing) {
|
|
3448
|
+
const next = nextBySequence.get(old.seq);
|
|
3449
|
+
if (!next || next.text !== old.text) {
|
|
3450
|
+
deleteOwner.run(mirrorHash, old.seq);
|
|
3451
|
+
deleteChunk.run(mirrorHash, old.seq);
|
|
3452
|
+
}
|
|
3046
3453
|
}
|
|
3047
3454
|
}
|
|
3048
3455
|
|
|
3049
|
-
const stmt = db.
|
|
3456
|
+
const stmt = db.query<
|
|
3457
|
+
unknown,
|
|
3458
|
+
[
|
|
3459
|
+
string,
|
|
3460
|
+
number,
|
|
3461
|
+
number,
|
|
3462
|
+
string,
|
|
3463
|
+
number,
|
|
3464
|
+
number,
|
|
3465
|
+
string | null,
|
|
3466
|
+
number | null,
|
|
3467
|
+
]
|
|
3468
|
+
>(`
|
|
3050
3469
|
INSERT INTO content_chunks (mirror_hash, seq, pos, text, start_line, end_line, language, token_count)
|
|
3051
3470
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
3052
3471
|
ON CONFLICT(mirror_hash, seq) DO UPDATE SET
|
|
@@ -3192,32 +3611,20 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3192
3611
|
|
|
3193
3612
|
const db = this.ensureOpen();
|
|
3194
3613
|
const result = new Map<string, ChunkRow[]>();
|
|
3614
|
+
const rows = db
|
|
3615
|
+
.query<DbChunkRow, [string]>(
|
|
3616
|
+
`SELECT * FROM content_chunks
|
|
3617
|
+
WHERE mirror_hash IN (SELECT value FROM json_each(?))
|
|
3618
|
+
ORDER BY mirror_hash, seq`
|
|
3619
|
+
)
|
|
3620
|
+
.all(JSON.stringify(uniqueHashes));
|
|
3195
3621
|
|
|
3196
|
-
//
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
i += SQLITE_SAFE_PARAMETER_BATCH_SIZE
|
|
3203
|
-
) {
|
|
3204
|
-
const batch = uniqueHashes.slice(
|
|
3205
|
-
i,
|
|
3206
|
-
i + SQLITE_SAFE_PARAMETER_BATCH_SIZE
|
|
3207
|
-
);
|
|
3208
|
-
const placeholders = batch.map(() => "?").join(",");
|
|
3209
|
-
const sql = `SELECT * FROM content_chunks
|
|
3210
|
-
WHERE mirror_hash IN (${placeholders})
|
|
3211
|
-
ORDER BY mirror_hash, seq`;
|
|
3212
|
-
const rows = db.query<DbChunkRow, string[]>(sql).all(...batch);
|
|
3213
|
-
|
|
3214
|
-
// Group by mirrorHash, preserving seq order from ORDER BY
|
|
3215
|
-
for (const row of rows) {
|
|
3216
|
-
const mapped = mapChunkRow(row);
|
|
3217
|
-
const existing = result.get(mapped.mirrorHash) ?? [];
|
|
3218
|
-
existing.push(mapped);
|
|
3219
|
-
result.set(mapped.mirrorHash, existing);
|
|
3220
|
-
}
|
|
3622
|
+
// Group by mirrorHash, preserving seq order from ORDER BY
|
|
3623
|
+
for (const row of rows) {
|
|
3624
|
+
const mapped = mapChunkRow(row);
|
|
3625
|
+
const existing = result.get(mapped.mirrorHash);
|
|
3626
|
+
if (existing) existing.push(mapped);
|
|
3627
|
+
else result.set(mapped.mirrorHash, [mapped]);
|
|
3221
3628
|
}
|
|
3222
3629
|
|
|
3223
3630
|
return ok(result);
|
|
@@ -3243,27 +3650,27 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3243
3650
|
const result = new Map<string, ChunkRow[]>();
|
|
3244
3651
|
if (pairs.length === 0) return ok(result);
|
|
3245
3652
|
const db = this.ensureOpen();
|
|
3246
|
-
const
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3653
|
+
const rows = db
|
|
3654
|
+
.query<DbChunkRow, [string]>(`
|
|
3655
|
+
WITH requested AS (
|
|
3656
|
+
SELECT
|
|
3657
|
+
json_extract(value, '$[0]') AS mirror_hash,
|
|
3658
|
+
json_extract(value, '$[1]') AS seq
|
|
3659
|
+
FROM json_each(?)
|
|
3660
|
+
)
|
|
3253
3661
|
SELECT c.* FROM requested r JOIN content_chunks c
|
|
3254
3662
|
ON c.mirror_hash = r.mirror_hash AND c.seq = r.seq
|
|
3255
3663
|
ORDER BY c.mirror_hash, c.seq
|
|
3256
3664
|
`)
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3665
|
+
.all(
|
|
3666
|
+
JSON.stringify(pairs.map(({ mirrorHash, seq }) => [mirrorHash, seq]))
|
|
3667
|
+
);
|
|
3668
|
+
for (const row of rows) {
|
|
3669
|
+
const mapped = mapChunkRow(row);
|
|
3670
|
+
const chunks = result.get(mapped.mirrorHash);
|
|
3671
|
+
if (chunks) chunks.push(mapped);
|
|
3672
|
+
else result.set(mapped.mirrorHash, [mapped]);
|
|
3264
3673
|
}
|
|
3265
|
-
for (const chunks of result.values())
|
|
3266
|
-
chunks.sort((a, b) => a.seq - b.seq);
|
|
3267
3674
|
return ok(result);
|
|
3268
3675
|
} catch (cause) {
|
|
3269
3676
|
return err(
|
|
@@ -3286,41 +3693,52 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3286
3693
|
const uniqueHashes = uniqueNonEmptyValues(mirrorHashes);
|
|
3287
3694
|
if (uniqueHashes.length === 0 || terms.length === 0) return ok([]);
|
|
3288
3695
|
const db = this.ensureOpen();
|
|
3289
|
-
//
|
|
3290
|
-
//
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
term.toUpperCase(),
|
|
3294
|
-
`${term.charAt(0).toUpperCase()}${term.slice(1)}`,
|
|
3295
|
-
]);
|
|
3696
|
+
// Compute lower(text) once per chunk in a derived table. SQLite lower()
|
|
3697
|
+
// folds ASCII only, so lowercase ASCII terms need only one instr(ltext, ?)
|
|
3698
|
+
// check, while non-ASCII or mixed-case terms check upper/capitalized too.
|
|
3699
|
+
const spellings: string[] = [];
|
|
3296
3700
|
const columns = terms
|
|
3297
|
-
.map(
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3701
|
+
.map((term) => {
|
|
3702
|
+
let isAscii = true;
|
|
3703
|
+
for (let i = 0; i < term.length; i++) {
|
|
3704
|
+
if (term.charCodeAt(i) > 0x7f) {
|
|
3705
|
+
isAscii = false;
|
|
3706
|
+
break;
|
|
3707
|
+
}
|
|
3708
|
+
}
|
|
3709
|
+
const isLowerAscii = isAscii && term === term.toLowerCase();
|
|
3710
|
+
if (isLowerAscii) {
|
|
3711
|
+
spellings.push(term);
|
|
3712
|
+
return "instr(ltext, ?) > 0";
|
|
3713
|
+
}
|
|
3714
|
+
spellings.push(
|
|
3715
|
+
term,
|
|
3716
|
+
term.toUpperCase(),
|
|
3717
|
+
`${term.charAt(0).toUpperCase()}${term.slice(1)}`
|
|
3718
|
+
);
|
|
3719
|
+
return "(instr(ltext, ?) > 0 OR instr(text, ?) > 0 OR instr(text, ?) > 0)";
|
|
3720
|
+
})
|
|
3301
3721
|
.join(", ");
|
|
3302
|
-
const
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3722
|
+
const values = db
|
|
3723
|
+
.query<unknown, string[]>(
|
|
3724
|
+
`WITH scoped AS MATERIALIZED (
|
|
3725
|
+
SELECT mirror_hash, seq, text, lower(text) AS ltext
|
|
3726
|
+
FROM content_chunks
|
|
3727
|
+
WHERE mirror_hash IN (SELECT value FROM json_each(?))
|
|
3728
|
+
)
|
|
3729
|
+
SELECT mirror_hash, seq, ${columns}
|
|
3730
|
+
FROM scoped
|
|
3731
|
+
ORDER BY mirror_hash, seq`
|
|
3732
|
+
)
|
|
3733
|
+
.values(JSON.stringify(uniqueHashes), ...spellings) as unknown[][];
|
|
3306
3734
|
const rows: { mirrorHash: string; seq: number; present: boolean[] }[] =
|
|
3307
3735
|
[];
|
|
3308
|
-
for (
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
ORDER BY mirror_hash, seq`
|
|
3315
|
-
)
|
|
3316
|
-
.values(...spellings, ...batch) as unknown[][];
|
|
3317
|
-
for (const [mirrorHash, seq, ...present] of values) {
|
|
3318
|
-
rows.push({
|
|
3319
|
-
mirrorHash: String(mirrorHash),
|
|
3320
|
-
seq: Number(seq),
|
|
3321
|
-
present: present.map((flag) => flag === 1),
|
|
3322
|
-
});
|
|
3323
|
-
}
|
|
3736
|
+
for (const [mirrorHash, seq, ...present] of values) {
|
|
3737
|
+
rows.push({
|
|
3738
|
+
mirrorHash: String(mirrorHash),
|
|
3739
|
+
seq: Number(seq),
|
|
3740
|
+
present: present.map((flag) => flag === 1),
|
|
3741
|
+
});
|
|
3324
3742
|
}
|
|
3325
3743
|
return ok(rows);
|
|
3326
3744
|
} catch (cause) {
|
|
@@ -3534,22 +3952,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3534
3952
|
return; // Document not found or inactive
|
|
3535
3953
|
}
|
|
3536
3954
|
|
|
3537
|
-
// Delete existing FTS entry for this doc
|
|
3538
|
-
db.
|
|
3539
|
-
db.run("UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?", [
|
|
3540
|
-
doc.id,
|
|
3541
|
-
]);
|
|
3955
|
+
// Delete existing FTS entry for this doc and update fts_mirror_hash once
|
|
3956
|
+
db.query("DELETE FROM documents_fts WHERE rowid = ?").run(doc.id);
|
|
3542
3957
|
|
|
3543
|
-
// Insert new FTS entry if we have content
|
|
3544
3958
|
if (doc.markdown !== null) {
|
|
3545
|
-
db.
|
|
3546
|
-
"INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
|
|
3547
|
-
|
|
3548
|
-
)
|
|
3549
|
-
db.run("UPDATE documents SET fts_mirror_hash = ? WHERE id = ?", [
|
|
3959
|
+
db.query(
|
|
3960
|
+
"INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
|
|
3961
|
+
).run(doc.id, doc.rel_path, doc.title ?? "", doc.markdown);
|
|
3962
|
+
db.query("UPDATE documents SET fts_mirror_hash = ? WHERE id = ?").run(
|
|
3550
3963
|
doc.mirror_hash,
|
|
3551
|
-
doc.id
|
|
3552
|
-
|
|
3964
|
+
doc.id
|
|
3965
|
+
);
|
|
3966
|
+
} else {
|
|
3967
|
+
db.query(
|
|
3968
|
+
"UPDATE documents SET fts_mirror_hash = NULL WHERE id = ?"
|
|
3969
|
+
).run(doc.id);
|
|
3553
3970
|
}
|
|
3554
3971
|
});
|
|
3555
3972
|
|
|
@@ -3574,41 +3991,28 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3574
3991
|
let count = 0;
|
|
3575
3992
|
|
|
3576
3993
|
const transaction = db.transaction(() => {
|
|
3577
|
-
// Clear FTS table
|
|
3578
|
-
db.
|
|
3579
|
-
db.
|
|
3580
|
-
|
|
3581
|
-
|
|
3582
|
-
|
|
3583
|
-
|
|
3584
|
-
|
|
3585
|
-
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
// Insert FTS entries
|
|
3600
|
-
const stmt = db.prepare(
|
|
3601
|
-
"INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
|
|
3602
|
-
);
|
|
3603
|
-
const markSynced = db.prepare(
|
|
3604
|
-
"UPDATE documents SET fts_mirror_hash = ? WHERE id = ?"
|
|
3994
|
+
// Clear FTS table and rebuild purely in SQL without loading bodies into JS
|
|
3995
|
+
db.exec("DELETE FROM documents_fts");
|
|
3996
|
+
db.exec("UPDATE documents SET fts_mirror_hash = NULL");
|
|
3997
|
+
db.query(
|
|
3998
|
+
`INSERT INTO documents_fts (rowid, filepath, title, body)
|
|
3999
|
+
SELECT d.id, d.rel_path, COALESCE(d.title, ''), c.markdown
|
|
4000
|
+
FROM documents d
|
|
4001
|
+
JOIN content c ON c.mirror_hash = d.mirror_hash
|
|
4002
|
+
WHERE d.active = 1 AND d.mirror_hash IS NOT NULL`
|
|
4003
|
+
).run();
|
|
4004
|
+
count =
|
|
4005
|
+
db.query<{ count: number }, []>("SELECT changes() AS count").get()
|
|
4006
|
+
?.count ?? 0;
|
|
4007
|
+
db.exec(
|
|
4008
|
+
`UPDATE documents
|
|
4009
|
+
SET fts_mirror_hash = mirror_hash
|
|
4010
|
+
WHERE active = 1
|
|
4011
|
+
AND mirror_hash IS NOT NULL
|
|
4012
|
+
AND EXISTS (
|
|
4013
|
+
SELECT 1 FROM content c WHERE c.mirror_hash = documents.mirror_hash
|
|
4014
|
+
)`
|
|
3605
4015
|
);
|
|
3606
|
-
|
|
3607
|
-
for (const doc of docs) {
|
|
3608
|
-
stmt.run(doc.id, doc.rel_path, doc.title ?? "", doc.markdown);
|
|
3609
|
-
markSynced.run(doc.mirror_hash, doc.id);
|
|
3610
|
-
count++;
|
|
3611
|
-
}
|
|
3612
4016
|
});
|
|
3613
4017
|
|
|
3614
4018
|
transaction();
|
|
@@ -3657,20 +4061,26 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3657
4061
|
return;
|
|
3658
4062
|
}
|
|
3659
4063
|
|
|
3660
|
-
|
|
4064
|
+
const deleteFts = db.query<unknown, [number]>(
|
|
4065
|
+
"DELETE FROM documents_fts WHERE rowid = ?"
|
|
4066
|
+
);
|
|
4067
|
+
const insertFts = db.query<unknown, [number, string, string, string]>(
|
|
4068
|
+
"INSERT INTO documents_fts (rowid, filepath, title, body) VALUES (?, ?, ?, ?)"
|
|
4069
|
+
);
|
|
4070
|
+
const markSynced = db.query<unknown, [string, number]>(
|
|
4071
|
+
"UPDATE documents SET fts_mirror_hash = ? WHERE id = ?"
|
|
4072
|
+
);
|
|
4073
|
+
|
|
4074
|
+
// Update FTS for each document using this hash (single fts_mirror_hash update)
|
|
3661
4075
|
for (const doc of docs) {
|
|
3662
|
-
|
|
3663
|
-
|
|
4076
|
+
deleteFts.run(doc.id);
|
|
4077
|
+
insertFts.run(
|
|
3664
4078
|
doc.id,
|
|
3665
|
-
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
[doc.id, doc.rel_path, doc.title ?? "", content.markdown]
|
|
4079
|
+
doc.rel_path,
|
|
4080
|
+
doc.title ?? "",
|
|
4081
|
+
content.markdown
|
|
3669
4082
|
);
|
|
3670
|
-
|
|
3671
|
-
mirrorHash,
|
|
3672
|
-
doc.id,
|
|
3673
|
-
]);
|
|
4083
|
+
markSynced.run(mirrorHash, doc.id);
|
|
3674
4084
|
}
|
|
3675
4085
|
});
|
|
3676
4086
|
|
|
@@ -3789,24 +4199,49 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3789
4199
|
if (options.scopes.length === 0) {
|
|
3790
4200
|
return ok([]);
|
|
3791
4201
|
}
|
|
3792
|
-
const
|
|
3793
|
-
|
|
3794
|
-
.
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
4202
|
+
const limit =
|
|
4203
|
+
options.limit !== undefined &&
|
|
4204
|
+
Number.isSafeInteger(options.limit) &&
|
|
4205
|
+
options.limit > 0
|
|
4206
|
+
? options.limit
|
|
4207
|
+
: null;
|
|
4208
|
+
const rows =
|
|
4209
|
+
limit !== null
|
|
4210
|
+
? db
|
|
4211
|
+
.query<
|
|
4212
|
+
{ id: number; docid: string; uri: string; mirror_hash: string },
|
|
4213
|
+
[string, string, number]
|
|
4214
|
+
>(
|
|
4215
|
+
`
|
|
4216
|
+
SELECT d.id, d.docid, d.uri, d.mirror_hash
|
|
4217
|
+
FROM documents d
|
|
4218
|
+
WHERE d.active = 1
|
|
4219
|
+
AND d.collection = ?
|
|
4220
|
+
AND d.mirror_hash IS NOT NULL
|
|
4221
|
+
AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (SELECT value FROM json_each(?)))
|
|
4222
|
+
${options.excludeSuperseded ? SUPERSEDED_EXCLUSION_SQL("d.id") : ""}
|
|
4223
|
+
ORDER BY d.id
|
|
4224
|
+
LIMIT ?
|
|
3798
4225
|
`
|
|
4226
|
+
)
|
|
4227
|
+
.all(options.collection, JSON.stringify(options.scopes), limit)
|
|
4228
|
+
: db
|
|
4229
|
+
.query<
|
|
4230
|
+
{ id: number; docid: string; uri: string; mirror_hash: string },
|
|
4231
|
+
[string, string]
|
|
4232
|
+
>(
|
|
4233
|
+
`
|
|
3799
4234
|
SELECT d.id, d.docid, d.uri, d.mirror_hash
|
|
3800
4235
|
FROM documents d
|
|
3801
4236
|
WHERE d.active = 1
|
|
3802
4237
|
AND d.collection = ?
|
|
3803
4238
|
AND d.mirror_hash IS NOT NULL
|
|
3804
|
-
AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (
|
|
4239
|
+
AND EXISTS (SELECT 1 FROM doc_memory_scopes ms WHERE ms.document_id = d.id AND ms.scope IN (SELECT value FROM json_each(?)))
|
|
3805
4240
|
${options.excludeSuperseded ? SUPERSEDED_EXCLUSION_SQL("d.id") : ""}
|
|
3806
4241
|
ORDER BY d.id
|
|
3807
4242
|
`
|
|
3808
|
-
|
|
3809
|
-
|
|
4243
|
+
)
|
|
4244
|
+
.all(options.collection, JSON.stringify(options.scopes));
|
|
3810
4245
|
return ok(
|
|
3811
4246
|
rows.map((row) => ({
|
|
3812
4247
|
id: row.id,
|
|
@@ -3876,14 +4311,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3876
4311
|
source: "frontmatter" | "user";
|
|
3877
4312
|
}
|
|
3878
4313
|
|
|
3879
|
-
// Use parameterized IN clause to prevent SQL injection
|
|
3880
|
-
const placeholders = documentIds.map(() => "?").join(", ");
|
|
3881
4314
|
const rows = db
|
|
3882
|
-
.query<DbTagRow,
|
|
4315
|
+
.query<DbTagRow, [string]>(
|
|
3883
4316
|
`SELECT document_id, tag, source FROM doc_tags
|
|
3884
|
-
WHERE document_id IN (
|
|
4317
|
+
WHERE document_id IN (SELECT value FROM json_each(?)) ORDER BY document_id, tag`
|
|
3885
4318
|
)
|
|
3886
|
-
.all(
|
|
4319
|
+
.all(JSON.stringify(documentIds));
|
|
3887
4320
|
|
|
3888
4321
|
// Group by document_id
|
|
3889
4322
|
const result = new Map<number, TagRow[]>();
|
|
@@ -3996,7 +4429,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
3996
4429
|
|
|
3997
4430
|
const params: (string | number)[] = [];
|
|
3998
4431
|
let sql = `
|
|
3999
|
-
SELECT dt.tag, COUNT(
|
|
4432
|
+
SELECT dt.tag, COUNT(*) as count
|
|
4000
4433
|
FROM doc_tags dt
|
|
4001
4434
|
JOIN documents d ON d.id = dt.document_id AND d.active = 1
|
|
4002
4435
|
`;
|
|
@@ -4262,9 +4695,12 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4262
4695
|
const sourceScopeSql = sourceAllowlist
|
|
4263
4696
|
? sourceAllowlist.length === 0
|
|
4264
4697
|
? "AND 0"
|
|
4265
|
-
:
|
|
4698
|
+
: "AND src.collection IN (SELECT value FROM json_each(?))"
|
|
4266
4699
|
: "";
|
|
4267
|
-
const sourceScopeParams =
|
|
4700
|
+
const sourceScopeParams =
|
|
4701
|
+
sourceAllowlist && sourceAllowlist.length > 0
|
|
4702
|
+
? [JSON.stringify(sourceAllowlist)]
|
|
4703
|
+
: [];
|
|
4268
4704
|
const backlinkColumns = `dl.id AS link_id, dl.source_doc_id, src.docid,
|
|
4269
4705
|
src.uri, src.title, src.collection AS source_collection,
|
|
4270
4706
|
src.rel_path AS source_rel_path, dl.target_ref_norm,
|
|
@@ -4349,21 +4785,21 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4349
4785
|
JOIN documents src ON src.id = dl.source_doc_id AND src.active = 1
|
|
4350
4786
|
WHERE dl.link_type = 'wiki'
|
|
4351
4787
|
AND dl.target_collection IS NULL
|
|
4352
|
-
AND src.collection IN (
|
|
4788
|
+
AND src.collection IN (SELECT value FROM json_each(?))
|
|
4353
4789
|
AND (dl.target_ref_norm IN (?, ?)
|
|
4354
4790
|
OR dl.target_ref_norm LIKE ? ESCAPE '\\'
|
|
4355
4791
|
OR dl.target_ref_norm LIKE ? ESCAPE '\\'
|
|
4356
|
-
OR dl.target_ref_norm IN (
|
|
4792
|
+
OR dl.target_ref_norm IN (SELECT value FROM json_each(?)))
|
|
4357
4793
|
${sourceScopeSql}
|
|
4358
4794
|
ORDER BY src.uri, dl.start_line, dl.start_col`
|
|
4359
4795
|
)
|
|
4360
4796
|
.all(
|
|
4361
|
-
|
|
4797
|
+
JSON.stringify(members),
|
|
4362
4798
|
base,
|
|
4363
4799
|
`${base}.md`,
|
|
4364
4800
|
`%/${escapeLike(base)}`,
|
|
4365
4801
|
`%/${escapeLike(`${base}.md`)}`,
|
|
4366
|
-
...keySet,
|
|
4802
|
+
JSON.stringify([...keySet]),
|
|
4367
4803
|
...sourceScopeParams
|
|
4368
4804
|
)
|
|
4369
4805
|
);
|
|
@@ -4373,40 +4809,53 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4373
4809
|
for (const row of [...wikiBacklinks, ...workspaceBacklinks]) {
|
|
4374
4810
|
candidates.set(row.link_id, row);
|
|
4375
4811
|
}
|
|
4376
|
-
const candidateRows = [...candidates.values()];
|
|
4377
|
-
const resolutions = resolveGraphLinkTargets(
|
|
4378
|
-
db,
|
|
4379
|
-
candidateRows.map((row) => ({
|
|
4380
|
-
targetRefNorm: row.target_ref_norm,
|
|
4381
|
-
targetCollection: row.target_collection ?? row.source_collection,
|
|
4382
|
-
linkType: "wiki" as const,
|
|
4383
|
-
source: linkSourceIdentity(row),
|
|
4384
|
-
}))
|
|
4385
|
-
);
|
|
4386
4812
|
const legacyLinkIds = new Set(wikiBacklinks.map((row) => row.link_id));
|
|
4387
|
-
const
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
4391
|
-
|
|
4392
|
-
|
|
4393
|
-
|
|
4394
|
-
|
|
4395
|
-
|
|
4396
|
-
|
|
4397
|
-
|
|
4398
|
-
|
|
4399
|
-
|
|
4813
|
+
const directWikiBacklinks: DbBacklinkRow[] = [];
|
|
4814
|
+
const workspaceCandidateRows: DbBacklinkRow[] = [];
|
|
4815
|
+
for (const row of candidates.values()) {
|
|
4816
|
+
const workspaceLink =
|
|
4817
|
+
!row.target_collection &&
|
|
4818
|
+
workspaceKeyForDocument(
|
|
4819
|
+
memberships,
|
|
4820
|
+
row.source_collection,
|
|
4821
|
+
row.source_rel_path
|
|
4822
|
+
) !== null;
|
|
4823
|
+
if (workspaceLink) {
|
|
4824
|
+
workspaceCandidateRows.push(row);
|
|
4825
|
+
} else if (legacyLinkIds.has(row.link_id)) {
|
|
4826
|
+
directWikiBacklinks.push(row);
|
|
4827
|
+
}
|
|
4828
|
+
}
|
|
4829
|
+
const resolvedWorkspaceBacklinks: DbBacklinkRow[] = [];
|
|
4830
|
+
if (workspaceCandidateRows.length > 0) {
|
|
4831
|
+
const resolutions = resolveGraphLinkTargets(
|
|
4832
|
+
db,
|
|
4833
|
+
workspaceCandidateRows.map((row) => ({
|
|
4834
|
+
targetRefNorm: row.target_ref_norm,
|
|
4835
|
+
targetCollection: row.target_collection ?? row.source_collection,
|
|
4836
|
+
linkType: "wiki" as const,
|
|
4837
|
+
source: linkSourceIdentity(row),
|
|
4838
|
+
}))
|
|
4839
|
+
);
|
|
4840
|
+
for (let i = 0; i < workspaceCandidateRows.length; i++) {
|
|
4841
|
+
const resolution = resolutions[i];
|
|
4842
|
+
if (
|
|
4400
4843
|
isTraversableResolution(resolution) &&
|
|
4401
4844
|
resolution.targetId === documentId
|
|
4402
|
-
)
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
|
|
4408
|
-
|
|
4409
|
-
|
|
4845
|
+
) {
|
|
4846
|
+
resolvedWorkspaceBacklinks.push(workspaceCandidateRows[i]!);
|
|
4847
|
+
}
|
|
4848
|
+
}
|
|
4849
|
+
}
|
|
4850
|
+
const resolvedWikiBacklinks = [
|
|
4851
|
+
...directWikiBacklinks,
|
|
4852
|
+
...resolvedWorkspaceBacklinks,
|
|
4853
|
+
].sort(
|
|
4854
|
+
(left, right) =>
|
|
4855
|
+
(left.uri < right.uri ? -1 : left.uri > right.uri ? 1 : 0) ||
|
|
4856
|
+
left.start_line - right.start_line ||
|
|
4857
|
+
left.start_col - right.start_col
|
|
4858
|
+
);
|
|
4410
4859
|
|
|
4411
4860
|
// Query markdown backlinks (link_type='markdown')
|
|
4412
4861
|
// NULL target_collection means "same collection as source" - enforce this in SQL
|
|
@@ -4487,8 +4936,7 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4487
4936
|
number,
|
|
4488
4937
|
{ docid: string; uri: string; title: string | null; collection: string }
|
|
4489
4938
|
>();
|
|
4490
|
-
|
|
4491
|
-
const batch = ids.slice(offset, offset + 900);
|
|
4939
|
+
if (ids.length > 0) {
|
|
4492
4940
|
for (const row of db
|
|
4493
4941
|
.query<
|
|
4494
4942
|
{
|
|
@@ -4498,11 +4946,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4498
4946
|
title: string | null;
|
|
4499
4947
|
collection: string;
|
|
4500
4948
|
},
|
|
4501
|
-
|
|
4949
|
+
[string]
|
|
4502
4950
|
>(
|
|
4503
|
-
|
|
4951
|
+
"SELECT id, docid, uri, title, collection FROM documents WHERE id IN (SELECT value FROM json_each(?))"
|
|
4504
4952
|
)
|
|
4505
|
-
.all(
|
|
4953
|
+
.all(JSON.stringify(ids))) {
|
|
4506
4954
|
byId.set(row.id, {
|
|
4507
4955
|
docid: row.docid,
|
|
4508
4956
|
uri: row.uri,
|
|
@@ -4752,144 +5200,118 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
4752
5200
|
|
|
4753
5201
|
const referrers: FileRefactorResolutionReferrerDocument[] = [];
|
|
4754
5202
|
let totalContentChars = sourceContent?.length ?? 0;
|
|
5203
|
+
const boundedCandidateIds = sortedCandidateIds.slice(0, maxReferrers);
|
|
4755
5204
|
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
4759
|
-
|
|
4760
|
-
|
|
4761
|
-
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
},
|
|
4770
|
-
[number]
|
|
4771
|
-
>(
|
|
4772
|
-
`SELECT id, uri, rel_path, collection, title, mirror_hash,
|
|
4773
|
-
source_ext, source_mime, record_key
|
|
4774
|
-
FROM documents
|
|
4775
|
-
WHERE id = ? AND active = 1`
|
|
4776
|
-
)
|
|
4777
|
-
.get(referrerId);
|
|
4778
|
-
if (!referrerRow) continue;
|
|
4779
|
-
|
|
4780
|
-
const caps = getDocumentCapabilities({
|
|
4781
|
-
sourceExt: referrerRow.source_ext,
|
|
4782
|
-
sourceMime: referrerRow.source_mime,
|
|
4783
|
-
contentAvailable: Boolean(referrerRow.mirror_hash),
|
|
4784
|
-
recordKey: referrerRow.record_key,
|
|
4785
|
-
});
|
|
4786
|
-
|
|
4787
|
-
if (!referrerRow.mirror_hash) {
|
|
4788
|
-
truncationReasons.push("referrer_content_missing");
|
|
4789
|
-
referrers.push({
|
|
4790
|
-
id: referrerRow.id,
|
|
4791
|
-
uri: referrerRow.uri,
|
|
4792
|
-
relPath: referrerRow.rel_path,
|
|
4793
|
-
collection: referrerRow.collection,
|
|
4794
|
-
title: referrerRow.title,
|
|
4795
|
-
content: null,
|
|
4796
|
-
contentTruncated: false,
|
|
4797
|
-
contentMissing: true,
|
|
4798
|
-
editable: caps.editable,
|
|
4799
|
-
editableReason: caps.editable
|
|
4800
|
-
? undefined
|
|
4801
|
-
: caps.reason
|
|
4802
|
-
? "read_only_document"
|
|
4803
|
-
: "capability_denied",
|
|
4804
|
-
sourceExt: referrerRow.source_ext,
|
|
4805
|
-
sourceMime: referrerRow.source_mime,
|
|
4806
|
-
recordKey: referrerRow.record_key,
|
|
4807
|
-
});
|
|
4808
|
-
continue;
|
|
5205
|
+
if (boundedCandidateIds.length > 0) {
|
|
5206
|
+
interface ReferrerJoinedRow {
|
|
5207
|
+
id: number;
|
|
5208
|
+
uri: string;
|
|
5209
|
+
rel_path: string;
|
|
5210
|
+
collection: string;
|
|
5211
|
+
title: string | null;
|
|
5212
|
+
mirror_hash: string | null;
|
|
5213
|
+
source_ext: string;
|
|
5214
|
+
source_mime: string;
|
|
5215
|
+
record_key: string | null;
|
|
5216
|
+
markdown: string | null;
|
|
5217
|
+
has_content: number;
|
|
4809
5218
|
}
|
|
4810
|
-
|
|
4811
|
-
|
|
4812
|
-
|
|
4813
|
-
|
|
4814
|
-
|
|
4815
|
-
|
|
4816
|
-
|
|
4817
|
-
|
|
4818
|
-
|
|
4819
|
-
|
|
4820
|
-
|
|
4821
|
-
|
|
4822
|
-
|
|
4823
|
-
|
|
4824
|
-
|
|
4825
|
-
|
|
4826
|
-
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
5219
|
+
const referrerStmt = db.prepare<ReferrerJoinedRow, [number, string]>(
|
|
5220
|
+
`SELECT d.id, d.uri, d.rel_path, d.collection, d.title, d.mirror_hash,
|
|
5221
|
+
d.source_ext, d.source_mime, d.record_key,
|
|
5222
|
+
substr(c.markdown, 1, ?) AS markdown,
|
|
5223
|
+
CASE WHEN c.mirror_hash IS NOT NULL THEN 1 ELSE 0 END AS has_content
|
|
5224
|
+
FROM documents d
|
|
5225
|
+
LEFT JOIN content c ON c.mirror_hash = d.mirror_hash
|
|
5226
|
+
WHERE d.active = 1
|
|
5227
|
+
AND d.id IN (SELECT value FROM json_each(?))
|
|
5228
|
+
ORDER BY d.id ASC`
|
|
5229
|
+
);
|
|
5230
|
+
try {
|
|
5231
|
+
for (const referrerRow of referrerStmt.iterate(
|
|
5232
|
+
maxChars + 1,
|
|
5233
|
+
JSON.stringify(boundedCandidateIds)
|
|
5234
|
+
)) {
|
|
5235
|
+
const caps = getDocumentCapabilities({
|
|
5236
|
+
sourceExt: referrerRow.source_ext,
|
|
5237
|
+
sourceMime: referrerRow.source_mime,
|
|
5238
|
+
contentAvailable: Boolean(referrerRow.mirror_hash),
|
|
5239
|
+
recordKey: referrerRow.record_key,
|
|
5240
|
+
});
|
|
5241
|
+
const editableReason = caps.editable
|
|
4831
5242
|
? undefined
|
|
4832
5243
|
: caps.reason
|
|
4833
|
-
? "read_only_document"
|
|
4834
|
-
: "capability_denied"
|
|
4835
|
-
|
|
4836
|
-
|
|
4837
|
-
|
|
4838
|
-
|
|
4839
|
-
|
|
4840
|
-
|
|
5244
|
+
? ("read_only_document" as const)
|
|
5245
|
+
: ("capability_denied" as const);
|
|
5246
|
+
|
|
5247
|
+
if (!referrerRow.mirror_hash || referrerRow.has_content !== 1) {
|
|
5248
|
+
truncationReasons.push("referrer_content_missing");
|
|
5249
|
+
referrers.push({
|
|
5250
|
+
id: referrerRow.id,
|
|
5251
|
+
uri: referrerRow.uri,
|
|
5252
|
+
relPath: referrerRow.rel_path,
|
|
5253
|
+
collection: referrerRow.collection,
|
|
5254
|
+
title: referrerRow.title,
|
|
5255
|
+
content: null,
|
|
5256
|
+
contentTruncated: false,
|
|
5257
|
+
contentMissing: true,
|
|
5258
|
+
editable: caps.editable,
|
|
5259
|
+
editableReason,
|
|
5260
|
+
sourceExt: referrerRow.source_ext,
|
|
5261
|
+
sourceMime: referrerRow.source_mime,
|
|
5262
|
+
recordKey: referrerRow.record_key,
|
|
5263
|
+
});
|
|
5264
|
+
continue;
|
|
5265
|
+
}
|
|
4841
5266
|
|
|
4842
|
-
|
|
4843
|
-
|
|
4844
|
-
|
|
4845
|
-
|
|
4846
|
-
|
|
4847
|
-
|
|
4848
|
-
|
|
4849
|
-
|
|
4850
|
-
|
|
4851
|
-
|
|
4852
|
-
|
|
4853
|
-
|
|
4854
|
-
|
|
4855
|
-
|
|
4856
|
-
|
|
4857
|
-
|
|
4858
|
-
|
|
4859
|
-
|
|
4860
|
-
|
|
4861
|
-
|
|
4862
|
-
|
|
4863
|
-
|
|
4864
|
-
|
|
4865
|
-
|
|
4866
|
-
:
|
|
4867
|
-
|
|
4868
|
-
|
|
4869
|
-
|
|
4870
|
-
});
|
|
4871
|
-
continue;
|
|
4872
|
-
}
|
|
5267
|
+
const rawMarkdown = referrerRow.markdown ?? "";
|
|
5268
|
+
const contentTruncated = rawMarkdown.length > maxChars;
|
|
5269
|
+
if (contentTruncated) {
|
|
5270
|
+
truncationReasons.push("referrer_content_truncated");
|
|
5271
|
+
}
|
|
5272
|
+
const content = contentTruncated
|
|
5273
|
+
? rawMarkdown.slice(0, maxChars)
|
|
5274
|
+
: rawMarkdown;
|
|
5275
|
+
totalContentChars += content.length;
|
|
5276
|
+
if (totalContentChars > maxTotalChars) {
|
|
5277
|
+
truncationReasons.push("total_content_truncated");
|
|
5278
|
+
referrers.push({
|
|
5279
|
+
id: referrerRow.id,
|
|
5280
|
+
uri: referrerRow.uri,
|
|
5281
|
+
relPath: referrerRow.rel_path,
|
|
5282
|
+
collection: referrerRow.collection,
|
|
5283
|
+
title: referrerRow.title,
|
|
5284
|
+
content: null,
|
|
5285
|
+
contentTruncated: false,
|
|
5286
|
+
contentMissing: true,
|
|
5287
|
+
editable: caps.editable,
|
|
5288
|
+
editableReason,
|
|
5289
|
+
sourceExt: referrerRow.source_ext,
|
|
5290
|
+
sourceMime: referrerRow.source_mime,
|
|
5291
|
+
recordKey: referrerRow.record_key,
|
|
5292
|
+
});
|
|
5293
|
+
continue;
|
|
5294
|
+
}
|
|
4873
5295
|
|
|
4874
|
-
|
|
4875
|
-
|
|
4876
|
-
|
|
4877
|
-
|
|
4878
|
-
|
|
4879
|
-
|
|
4880
|
-
|
|
4881
|
-
|
|
4882
|
-
|
|
4883
|
-
|
|
4884
|
-
|
|
4885
|
-
|
|
4886
|
-
|
|
4887
|
-
|
|
4888
|
-
|
|
4889
|
-
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
}
|
|
5296
|
+
referrers.push({
|
|
5297
|
+
id: referrerRow.id,
|
|
5298
|
+
uri: referrerRow.uri,
|
|
5299
|
+
relPath: referrerRow.rel_path,
|
|
5300
|
+
collection: referrerRow.collection,
|
|
5301
|
+
title: referrerRow.title,
|
|
5302
|
+
content,
|
|
5303
|
+
contentTruncated,
|
|
5304
|
+
contentMissing: false,
|
|
5305
|
+
editable: caps.editable,
|
|
5306
|
+
editableReason,
|
|
5307
|
+
sourceExt: referrerRow.source_ext,
|
|
5308
|
+
sourceMime: referrerRow.source_mime,
|
|
5309
|
+
recordKey: referrerRow.record_key,
|
|
5310
|
+
});
|
|
5311
|
+
}
|
|
5312
|
+
} finally {
|
|
5313
|
+
referrerStmt.finalize();
|
|
5314
|
+
}
|
|
4893
5315
|
}
|
|
4894
5316
|
|
|
4895
5317
|
const snapshot: FileRefactorResolutionSnapshot = {
|
|
@@ -5898,16 +6320,17 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
5898
6320
|
}
|
|
5899
6321
|
|
|
5900
6322
|
const connectedIdList = [...connectedNodeIds].sort((a, b) => a - b);
|
|
6323
|
+
const connectedIdsJson =
|
|
6324
|
+
connectedIdList.length > 0 ? JSON.stringify(connectedIdList) : null;
|
|
5901
6325
|
const connectedMetaMap = new Map<number, NodeMetaRow>();
|
|
5902
|
-
if (
|
|
5903
|
-
const placeholders = connectedIdList.map(() => "?").join(",");
|
|
6326
|
+
if (connectedIdsJson) {
|
|
5904
6327
|
const connectedRows = db
|
|
5905
|
-
.query<NodeMetaRow,
|
|
6328
|
+
.query<NodeMetaRow, [string]>(
|
|
5906
6329
|
`SELECT id, docid, uri, title, collection, rel_path
|
|
5907
6330
|
FROM documents
|
|
5908
|
-
WHERE id IN (
|
|
6331
|
+
WHERE id IN (SELECT value FROM json_each(?))`
|
|
5909
6332
|
)
|
|
5910
|
-
.all(
|
|
6333
|
+
.all(connectedIdsJson);
|
|
5911
6334
|
for (const row of connectedRows) {
|
|
5912
6335
|
connectedMetaMap.set(row.id, row);
|
|
5913
6336
|
}
|
|
@@ -5946,10 +6369,11 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
5946
6369
|
isolatedBaseConditions.push("collection = ?");
|
|
5947
6370
|
isolatedBaseParams.push(collection);
|
|
5948
6371
|
}
|
|
5949
|
-
if (
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
6372
|
+
if (connectedIdsJson) {
|
|
6373
|
+
isolatedBaseConditions.push(
|
|
6374
|
+
"id NOT IN (SELECT value FROM json_each(?))"
|
|
6375
|
+
);
|
|
6376
|
+
isolatedBaseParams.push(connectedIdsJson);
|
|
5953
6377
|
}
|
|
5954
6378
|
const isolatedWhereClause = isolatedBaseConditions.join(" AND ");
|
|
5955
6379
|
const isolatedCountRow = db
|
|
@@ -5998,9 +6422,8 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
5998
6422
|
isolatedParams.push(collection);
|
|
5999
6423
|
}
|
|
6000
6424
|
if (excluded.length > 0) {
|
|
6001
|
-
|
|
6002
|
-
|
|
6003
|
-
isolatedParams.push(...excluded);
|
|
6425
|
+
conditions.push("id NOT IN (SELECT value FROM json_each(?))");
|
|
6426
|
+
isolatedParams.push(JSON.stringify(excluded));
|
|
6004
6427
|
}
|
|
6005
6428
|
isolatedParams.push(remaining);
|
|
6006
6429
|
|
|
@@ -6296,7 +6719,67 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6296
6719
|
.replace(SQLITE_EXT_REGEX, "")
|
|
6297
6720
|
.replace(INDEX_PREFIX_REGEX, "") || "default";
|
|
6298
6721
|
|
|
6299
|
-
//
|
|
6722
|
+
// Single pass over `documents` gathers per-collection counts, configured
|
|
6723
|
+
// totals, global lastUpdatedAt, and global typed-metadata coverage.
|
|
6724
|
+
interface DocumentAggregateRow {
|
|
6725
|
+
collection: string;
|
|
6726
|
+
total: number;
|
|
6727
|
+
active: number;
|
|
6728
|
+
errored: number;
|
|
6729
|
+
chunked: number;
|
|
6730
|
+
last_updated: string | null;
|
|
6731
|
+
meta_pending: number;
|
|
6732
|
+
meta_invalid: number;
|
|
6733
|
+
}
|
|
6734
|
+
const docAggregateRows = db
|
|
6735
|
+
.query<DocumentAggregateRow, []>(
|
|
6736
|
+
`
|
|
6737
|
+
SELECT
|
|
6738
|
+
collection,
|
|
6739
|
+
COUNT(*) AS total,
|
|
6740
|
+
SUM(CASE WHEN active = 1 THEN 1 ELSE 0 END) AS active,
|
|
6741
|
+
SUM(CASE WHEN last_error_code IS NOT NULL THEN 1 ELSE 0 END) AS errored,
|
|
6742
|
+
SUM(CASE WHEN mirror_hash IS NOT NULL THEN 1 ELSE 0 END) AS chunked,
|
|
6743
|
+
strftime('%Y-%m-%dT%H:%M:%fZ', MAX(updated_at)) AS last_updated,
|
|
6744
|
+
SUM(CASE WHEN active = 1 AND mirror_hash IS NOT NULL AND (
|
|
6745
|
+
ingest_version IS NULL OR ingest_version < ${TYPED_METADATA_INGEST_VERSION}
|
|
6746
|
+
OR (typed_metadata IS NULL AND metadata_error IS NULL)
|
|
6747
|
+
) THEN 1 ELSE 0 END) AS meta_pending,
|
|
6748
|
+
SUM(CASE WHEN active = 1 AND mirror_hash IS NOT NULL AND metadata_error IS NOT NULL
|
|
6749
|
+
THEN 1 ELSE 0 END) AS meta_invalid
|
|
6750
|
+
FROM documents
|
|
6751
|
+
GROUP BY collection
|
|
6752
|
+
`
|
|
6753
|
+
)
|
|
6754
|
+
.all();
|
|
6755
|
+
|
|
6756
|
+
const configuredSet = options?.configuredCollections
|
|
6757
|
+
? new Set(options.configuredCollections)
|
|
6758
|
+
: null;
|
|
6759
|
+
const docStatsByCollection = new Map<string, DocumentAggregateRow>();
|
|
6760
|
+
let totalDocuments = 0;
|
|
6761
|
+
let activeDocuments = 0;
|
|
6762
|
+
let lastUpdatedAt: string | null = null;
|
|
6763
|
+
let metaPending = 0;
|
|
6764
|
+
let metaInvalid = 0;
|
|
6765
|
+
for (const row of docAggregateRows) {
|
|
6766
|
+
docStatsByCollection.set(row.collection, row);
|
|
6767
|
+
if (!configuredSet || configuredSet.has(row.collection)) {
|
|
6768
|
+
totalDocuments += row.total;
|
|
6769
|
+
activeDocuments += row.active;
|
|
6770
|
+
}
|
|
6771
|
+
if (
|
|
6772
|
+
row.last_updated !== null &&
|
|
6773
|
+
(lastUpdatedAt === null || row.last_updated > lastUpdatedAt)
|
|
6774
|
+
) {
|
|
6775
|
+
lastUpdatedAt = row.last_updated;
|
|
6776
|
+
}
|
|
6777
|
+
metaPending += row.meta_pending;
|
|
6778
|
+
metaInvalid += row.meta_invalid;
|
|
6779
|
+
}
|
|
6780
|
+
|
|
6781
|
+
// Get collection metadata + chunk counts; skip legacy vector scans when
|
|
6782
|
+
// variantStatus is authoritative.
|
|
6300
6783
|
interface CollectionStat {
|
|
6301
6784
|
name: string;
|
|
6302
6785
|
path: string;
|
|
@@ -6304,107 +6787,104 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6304
6787
|
egress_policy_source: EgressPolicySource;
|
|
6305
6788
|
workspace_root: string | null;
|
|
6306
6789
|
workspace_source: LinkWorkspaceSource | null;
|
|
6307
|
-
total: number;
|
|
6308
|
-
active: number;
|
|
6309
|
-
errored: number;
|
|
6310
|
-
chunked: number;
|
|
6311
6790
|
chunk_count: number;
|
|
6312
6791
|
embedded_count: number;
|
|
6313
6792
|
}
|
|
6314
6793
|
|
|
6315
|
-
const collectionStats =
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
6319
|
-
|
|
6320
|
-
|
|
6321
|
-
|
|
6322
|
-
|
|
6323
|
-
|
|
6324
|
-
|
|
6325
|
-
|
|
6326
|
-
|
|
6327
|
-
|
|
6328
|
-
|
|
6329
|
-
|
|
6330
|
-
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6335
|
-
|
|
6336
|
-
|
|
6337
|
-
|
|
6338
|
-
|
|
6339
|
-
|
|
6340
|
-
|
|
6341
|
-
|
|
6342
|
-
|
|
6343
|
-
|
|
6344
|
-
|
|
6345
|
-
|
|
6346
|
-
|
|
6347
|
-
)
|
|
6348
|
-
|
|
6349
|
-
|
|
6350
|
-
|
|
6351
|
-
|
|
6352
|
-
|
|
6353
|
-
|
|
6354
|
-
|
|
6355
|
-
|
|
6356
|
-
|
|
6357
|
-
|
|
6358
|
-
|
|
6359
|
-
|
|
6360
|
-
|
|
6361
|
-
|
|
6362
|
-
|
|
6363
|
-
|
|
6364
|
-
|
|
6365
|
-
|
|
6366
|
-
|
|
6367
|
-
|
|
6368
|
-
|
|
6369
|
-
|
|
6370
|
-
|
|
6371
|
-
|
|
6372
|
-
|
|
6373
|
-
|
|
6374
|
-
|
|
6375
|
-
|
|
6376
|
-
|
|
6377
|
-
|
|
6378
|
-
|
|
6379
|
-
|
|
6380
|
-
|
|
6381
|
-
|
|
6382
|
-
|
|
6383
|
-
|
|
6384
|
-
|
|
6385
|
-
|
|
6386
|
-
|
|
6387
|
-
|
|
6388
|
-
|
|
6389
|
-
|
|
6390
|
-
|
|
6391
|
-
|
|
6392
|
-
|
|
6393
|
-
|
|
6394
|
-
|
|
6395
|
-
|
|
6396
|
-
|
|
6397
|
-
|
|
6398
|
-
|
|
6399
|
-
|
|
6400
|
-
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6404
|
-
|
|
6405
|
-
|
|
6406
|
-
|
|
6407
|
-
|
|
6794
|
+
const collectionStats = variantStatus
|
|
6795
|
+
? db
|
|
6796
|
+
.query<CollectionStat, [string | null, string | null]>(
|
|
6797
|
+
`
|
|
6798
|
+
WITH active_collection_mirrors AS (
|
|
6799
|
+
SELECT DISTINCT collection, mirror_hash
|
|
6800
|
+
FROM documents
|
|
6801
|
+
WHERE active = 1 AND mirror_hash IS NOT NULL
|
|
6802
|
+
),
|
|
6803
|
+
collection_chunks AS (
|
|
6804
|
+
SELECT
|
|
6805
|
+
acm.collection,
|
|
6806
|
+
COUNT(*) AS chunk_count
|
|
6807
|
+
FROM active_collection_mirrors acm
|
|
6808
|
+
JOIN content_chunks cc ON cc.mirror_hash = acm.mirror_hash
|
|
6809
|
+
GROUP BY acm.collection
|
|
6810
|
+
)
|
|
6811
|
+
SELECT
|
|
6812
|
+
c.name,
|
|
6813
|
+
c.path,
|
|
6814
|
+
c.egress_policy,
|
|
6815
|
+
c.egress_policy_source,
|
|
6816
|
+
c.workspace_root,
|
|
6817
|
+
c.workspace_source,
|
|
6818
|
+
COALESCE(ch.chunk_count, 0) AS chunk_count,
|
|
6819
|
+
0 AS embedded_count
|
|
6820
|
+
FROM collections c
|
|
6821
|
+
LEFT JOIN collection_chunks ch ON ch.collection = c.name
|
|
6822
|
+
WHERE ? IS NULL OR c.name IN (SELECT value FROM json_each(?))
|
|
6823
|
+
ORDER BY c.name
|
|
6824
|
+
`
|
|
6825
|
+
)
|
|
6826
|
+
.all(configuredJson, configuredJson)
|
|
6827
|
+
: db
|
|
6828
|
+
.query<
|
|
6829
|
+
CollectionStat,
|
|
6830
|
+
[
|
|
6831
|
+
string | null,
|
|
6832
|
+
string | null,
|
|
6833
|
+
string | null,
|
|
6834
|
+
string | null,
|
|
6835
|
+
string | null,
|
|
6836
|
+
]
|
|
6837
|
+
>(
|
|
6838
|
+
`
|
|
6839
|
+
WITH active_collection_mirrors AS (
|
|
6840
|
+
SELECT DISTINCT collection, mirror_hash
|
|
6841
|
+
FROM documents
|
|
6842
|
+
WHERE active = 1 AND mirror_hash IS NOT NULL
|
|
6843
|
+
),
|
|
6844
|
+
matching_vectors AS (
|
|
6845
|
+
SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
|
|
6846
|
+
FROM content_vectors
|
|
6847
|
+
WHERE (? IS NULL OR (
|
|
6848
|
+
model = ? AND embed_fingerprint = ?
|
|
6849
|
+
))
|
|
6850
|
+
GROUP BY mirror_hash, seq
|
|
6851
|
+
),
|
|
6852
|
+
collection_chunks AS (
|
|
6853
|
+
SELECT
|
|
6854
|
+
acm.collection,
|
|
6855
|
+
COUNT(*) AS chunk_count,
|
|
6856
|
+
SUM(CASE
|
|
6857
|
+
WHEN mv.embedded_at >= cc.created_at THEN 1
|
|
6858
|
+
ELSE 0
|
|
6859
|
+
END) AS embedded_count
|
|
6860
|
+
FROM active_collection_mirrors acm
|
|
6861
|
+
JOIN content_chunks cc ON cc.mirror_hash = acm.mirror_hash
|
|
6862
|
+
LEFT JOIN matching_vectors mv
|
|
6863
|
+
ON mv.mirror_hash = cc.mirror_hash AND mv.seq = cc.seq
|
|
6864
|
+
GROUP BY acm.collection
|
|
6865
|
+
)
|
|
6866
|
+
SELECT
|
|
6867
|
+
c.name,
|
|
6868
|
+
c.path,
|
|
6869
|
+
c.egress_policy,
|
|
6870
|
+
c.egress_policy_source,
|
|
6871
|
+
c.workspace_root,
|
|
6872
|
+
c.workspace_source,
|
|
6873
|
+
COALESCE(ch.chunk_count, 0) AS chunk_count,
|
|
6874
|
+
COALESCE(ch.embedded_count, 0) AS embedded_count
|
|
6875
|
+
FROM collections c
|
|
6876
|
+
LEFT JOIN collection_chunks ch ON ch.collection = c.name
|
|
6877
|
+
WHERE ? IS NULL OR c.name IN (SELECT value FROM json_each(?))
|
|
6878
|
+
ORDER BY c.name
|
|
6879
|
+
`
|
|
6880
|
+
)
|
|
6881
|
+
.all(
|
|
6882
|
+
embedModel,
|
|
6883
|
+
embedModel,
|
|
6884
|
+
embedFingerprint,
|
|
6885
|
+
configuredJson,
|
|
6886
|
+
configuredJson
|
|
6887
|
+
);
|
|
6408
6888
|
|
|
6409
6889
|
// Chunks of active documents only (deduplicated by canonical chunk);
|
|
6410
6890
|
// content_chunks keeps rows of deleted documents until cleanup.
|
|
@@ -6423,51 +6903,52 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6423
6903
|
)
|
|
6424
6904
|
.get(configuredJson, configuredJson)?.count ?? 0;
|
|
6425
6905
|
|
|
6426
|
-
// Embedding backlog:
|
|
6427
|
-
|
|
6428
|
-
|
|
6429
|
-
|
|
6430
|
-
|
|
6431
|
-
|
|
6432
|
-
|
|
6433
|
-
|
|
6434
|
-
|
|
6435
|
-
|
|
6436
|
-
|
|
6437
|
-
|
|
6438
|
-
|
|
6439
|
-
|
|
6440
|
-
|
|
6441
|
-
|
|
6442
|
-
|
|
6443
|
-
|
|
6444
|
-
|
|
6445
|
-
|
|
6446
|
-
|
|
6447
|
-
|
|
6448
|
-
|
|
6449
|
-
|
|
6450
|
-
|
|
6451
|
-
|
|
6452
|
-
|
|
6453
|
-
|
|
6454
|
-
|
|
6455
|
-
|
|
6456
|
-
|
|
6457
|
-
|
|
6458
|
-
|
|
6459
|
-
|
|
6460
|
-
|
|
6461
|
-
|
|
6462
|
-
|
|
6463
|
-
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
|
|
6906
|
+
// Embedding backlog: skip legacy content_vectors scan when variantStatus is present.
|
|
6907
|
+
const embeddingBacklog = variantStatus
|
|
6908
|
+
? variantStatus.backlog
|
|
6909
|
+
: (db
|
|
6910
|
+
.query<
|
|
6911
|
+
{ count: number },
|
|
6912
|
+
[
|
|
6913
|
+
string | null,
|
|
6914
|
+
string | null,
|
|
6915
|
+
string | null,
|
|
6916
|
+
string | null,
|
|
6917
|
+
string | null,
|
|
6918
|
+
]
|
|
6919
|
+
>(
|
|
6920
|
+
`
|
|
6921
|
+
WITH active_mirrors AS (
|
|
6922
|
+
SELECT DISTINCT mirror_hash
|
|
6923
|
+
FROM documents
|
|
6924
|
+
WHERE active = 1 AND mirror_hash IS NOT NULL
|
|
6925
|
+
AND (? IS NULL OR collection IN (SELECT value FROM json_each(?)))
|
|
6926
|
+
),
|
|
6927
|
+
matching_vectors AS (
|
|
6928
|
+
SELECT mirror_hash, seq, MAX(embedded_at) AS embedded_at
|
|
6929
|
+
FROM content_vectors
|
|
6930
|
+
WHERE (? IS NULL OR (
|
|
6931
|
+
model = ? AND embed_fingerprint = ?
|
|
6932
|
+
))
|
|
6933
|
+
GROUP BY mirror_hash, seq
|
|
6934
|
+
)
|
|
6935
|
+
SELECT COUNT(*) AS count
|
|
6936
|
+
FROM active_mirrors am
|
|
6937
|
+
JOIN content_chunks c ON c.mirror_hash = am.mirror_hash
|
|
6938
|
+
LEFT JOIN matching_vectors mv
|
|
6939
|
+
ON mv.mirror_hash = c.mirror_hash
|
|
6940
|
+
AND mv.seq = c.seq
|
|
6941
|
+
AND mv.embedded_at >= c.created_at
|
|
6942
|
+
WHERE mv.mirror_hash IS NULL
|
|
6943
|
+
`
|
|
6944
|
+
)
|
|
6945
|
+
.get(
|
|
6946
|
+
configuredJson,
|
|
6947
|
+
configuredJson,
|
|
6948
|
+
embedModel,
|
|
6949
|
+
embedModel,
|
|
6950
|
+
embedFingerprint
|
|
6951
|
+
)?.count ?? 0);
|
|
6471
6952
|
|
|
6472
6953
|
// Recent errors (last 24h)
|
|
6473
6954
|
const recentErrorsRow = db
|
|
@@ -6479,42 +6960,36 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6479
6960
|
)
|
|
6480
6961
|
.get();
|
|
6481
6962
|
|
|
6482
|
-
// Last updated (max updated_at from documents)
|
|
6483
|
-
const lastUpdatedRow = db
|
|
6484
|
-
.query<{ last_updated: string | null }, []>(
|
|
6485
|
-
"SELECT strftime('%Y-%m-%dT%H:%M:%fZ', MAX(updated_at)) as last_updated FROM documents"
|
|
6486
|
-
)
|
|
6487
|
-
.get();
|
|
6488
|
-
|
|
6489
6963
|
// Health check: no recent errors and DB is accessible
|
|
6490
6964
|
const recentErrors = recentErrorsRow?.count ?? 0;
|
|
6491
6965
|
const healthy = recentErrors === 0;
|
|
6492
6966
|
|
|
6493
|
-
const metadataCoverage = await this.getTypedMetadataCoverage({});
|
|
6494
|
-
if (!metadataCoverage.ok) return metadataCoverage;
|
|
6495
6967
|
return ok({
|
|
6496
|
-
typedMetadata:
|
|
6968
|
+
typedMetadata: { pending: metaPending, invalid: metaInvalid },
|
|
6497
6969
|
version,
|
|
6498
6970
|
indexName,
|
|
6499
6971
|
configPath: this.configPath,
|
|
6500
6972
|
dbPath: this.dbPath,
|
|
6501
6973
|
ftsTokenizer: this.ftsTokenizer,
|
|
6502
|
-
collections: collectionStats.map((s) =>
|
|
6503
|
-
|
|
6504
|
-
|
|
6505
|
-
|
|
6506
|
-
|
|
6507
|
-
|
|
6508
|
-
|
|
6509
|
-
|
|
6510
|
-
|
|
6511
|
-
|
|
6512
|
-
|
|
6513
|
-
|
|
6514
|
-
|
|
6515
|
-
|
|
6516
|
-
:
|
|
6517
|
-
|
|
6974
|
+
collections: collectionStats.map((s) => {
|
|
6975
|
+
const ds = docStatsByCollection.get(s.name);
|
|
6976
|
+
return {
|
|
6977
|
+
name: s.name,
|
|
6978
|
+
path: s.path,
|
|
6979
|
+
egressPolicy: s.egress_policy,
|
|
6980
|
+
egressPolicySource: s.egress_policy_source,
|
|
6981
|
+
workspaceRoot: s.workspace_root,
|
|
6982
|
+
workspaceSource: s.workspace_source ?? "none",
|
|
6983
|
+
totalDocuments: ds?.total ?? 0,
|
|
6984
|
+
activeDocuments: ds?.active ?? 0,
|
|
6985
|
+
errorDocuments: ds?.errored ?? 0,
|
|
6986
|
+
chunkedDocuments: ds?.chunked ?? 0,
|
|
6987
|
+
totalChunks: s.chunk_count,
|
|
6988
|
+
embeddedChunks: variantStatus
|
|
6989
|
+
? (variantStatus.embeddedByCollection.get(s.name) ?? 0)
|
|
6990
|
+
: s.embedded_count,
|
|
6991
|
+
};
|
|
6992
|
+
}),
|
|
6518
6993
|
...(vectorPartitions.length
|
|
6519
6994
|
? {
|
|
6520
6995
|
vectorPartitions,
|
|
@@ -6523,13 +6998,13 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6523
6998
|
: {}),
|
|
6524
6999
|
}
|
|
6525
7000
|
: {}),
|
|
6526
|
-
totalDocuments
|
|
6527
|
-
activeDocuments
|
|
7001
|
+
totalDocuments,
|
|
7002
|
+
activeDocuments,
|
|
6528
7003
|
totalChunks: chunkCount,
|
|
6529
|
-
embeddingBacklog
|
|
7004
|
+
embeddingBacklog,
|
|
6530
7005
|
chunking: getChunkingStatus(db, options?.chunking),
|
|
6531
7006
|
recentErrors,
|
|
6532
|
-
lastUpdatedAt
|
|
7007
|
+
lastUpdatedAt,
|
|
6533
7008
|
healthy,
|
|
6534
7009
|
});
|
|
6535
7010
|
} catch (cause) {
|
|
@@ -6591,6 +7066,86 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6591
7066
|
}
|
|
6592
7067
|
}
|
|
6593
7068
|
|
|
7069
|
+
async getRecentBudgetStops(
|
|
7070
|
+
codes: readonly string[],
|
|
7071
|
+
scanLimit = 100,
|
|
7072
|
+
maxStops = 10
|
|
7073
|
+
): Promise<
|
|
7074
|
+
StoreResult<
|
|
7075
|
+
Array<{
|
|
7076
|
+
collection: string;
|
|
7077
|
+
relPath: string;
|
|
7078
|
+
code: string;
|
|
7079
|
+
message: string;
|
|
7080
|
+
}>
|
|
7081
|
+
>
|
|
7082
|
+
> {
|
|
7083
|
+
if (codes.length === 0 || scanLimit <= 0 || maxStops <= 0) {
|
|
7084
|
+
return ok([]);
|
|
7085
|
+
}
|
|
7086
|
+
try {
|
|
7087
|
+
const db = this.ensureOpen();
|
|
7088
|
+
const rows = db
|
|
7089
|
+
.query<
|
|
7090
|
+
{
|
|
7091
|
+
collection: string;
|
|
7092
|
+
rel_path: string;
|
|
7093
|
+
code: string;
|
|
7094
|
+
message: string;
|
|
7095
|
+
},
|
|
7096
|
+
[number, string, number]
|
|
7097
|
+
>(
|
|
7098
|
+
`WITH recent AS (
|
|
7099
|
+
SELECT
|
|
7100
|
+
collection,
|
|
7101
|
+
rel_path,
|
|
7102
|
+
occurred_at,
|
|
7103
|
+
code,
|
|
7104
|
+
message,
|
|
7105
|
+
ROW_NUMBER() OVER (
|
|
7106
|
+
PARTITION BY collection, rel_path
|
|
7107
|
+
ORDER BY occurred_at DESC, id DESC
|
|
7108
|
+
) AS rn
|
|
7109
|
+
FROM (
|
|
7110
|
+
SELECT id, collection, rel_path, occurred_at, code, message
|
|
7111
|
+
FROM ingest_errors
|
|
7112
|
+
ORDER BY occurred_at DESC
|
|
7113
|
+
LIMIT ?
|
|
7114
|
+
)
|
|
7115
|
+
)
|
|
7116
|
+
SELECT r.collection, r.rel_path, r.code, r.message
|
|
7117
|
+
FROM recent r
|
|
7118
|
+
INNER JOIN documents d
|
|
7119
|
+
ON d.collection = r.collection
|
|
7120
|
+
AND d.rel_path = r.rel_path
|
|
7121
|
+
WHERE r.rn = 1
|
|
7122
|
+
AND r.code IN (SELECT value FROM json_each(?))
|
|
7123
|
+
AND d.active = 1
|
|
7124
|
+
AND d.last_error_code = r.code
|
|
7125
|
+
ORDER BY r.occurred_at DESC
|
|
7126
|
+
LIMIT ?`
|
|
7127
|
+
)
|
|
7128
|
+
.all(scanLimit, JSON.stringify(codes), maxStops);
|
|
7129
|
+
|
|
7130
|
+
return ok(
|
|
7131
|
+
rows.map((row) => ({
|
|
7132
|
+
collection: row.collection,
|
|
7133
|
+
relPath: row.rel_path,
|
|
7134
|
+
code: row.code,
|
|
7135
|
+
message: row.message,
|
|
7136
|
+
}))
|
|
7137
|
+
);
|
|
7138
|
+
} catch (cause) {
|
|
7139
|
+
return err(
|
|
7140
|
+
"QUERY_FAILED",
|
|
7141
|
+
cause instanceof Error
|
|
7142
|
+
? cause.message
|
|
7143
|
+
: "Failed to get recent budget stops",
|
|
7144
|
+
cause
|
|
7145
|
+
);
|
|
7146
|
+
}
|
|
7147
|
+
}
|
|
7148
|
+
|
|
6594
7149
|
// ─────────────────────────────────────────────────────────────────────────
|
|
6595
7150
|
// Cleanup
|
|
6596
7151
|
// ─────────────────────────────────────────────────────────────────────────
|
|
@@ -6661,6 +7216,60 @@ export class SqliteAdapter implements StorePort, SqliteDbProvider {
|
|
|
6661
7216
|
}
|
|
6662
7217
|
}
|
|
6663
7218
|
|
|
7219
|
+
async getLlmCache(key: string): Promise<StoreResult<string | null>> {
|
|
7220
|
+
try {
|
|
7221
|
+
const db = this.ensureOpen();
|
|
7222
|
+
const row = db
|
|
7223
|
+
.query<{ value: string }, [string]>(
|
|
7224
|
+
`SELECT value FROM llm_cache
|
|
7225
|
+
WHERE key = ? AND (expires_at IS NULL OR expires_at >= datetime('now'))`
|
|
7226
|
+
)
|
|
7227
|
+
.get(key);
|
|
7228
|
+
return ok(row?.value ?? null);
|
|
7229
|
+
} catch (cause) {
|
|
7230
|
+
return err(
|
|
7231
|
+
"QUERY_FAILED",
|
|
7232
|
+
cause instanceof Error ? cause.message : "Failed to read LLM cache",
|
|
7233
|
+
cause
|
|
7234
|
+
);
|
|
7235
|
+
}
|
|
7236
|
+
}
|
|
7237
|
+
|
|
7238
|
+
async setLlmCache(
|
|
7239
|
+
key: string,
|
|
7240
|
+
value: string,
|
|
7241
|
+
expiresAt?: string
|
|
7242
|
+
): Promise<StoreResult<void>> {
|
|
7243
|
+
try {
|
|
7244
|
+
const db = this.ensureOpen();
|
|
7245
|
+
db.query<unknown, [string, string, string | null]>(
|
|
7246
|
+
`INSERT OR REPLACE INTO llm_cache (key, value, created_at, expires_at)
|
|
7247
|
+
VALUES (?, ?, datetime('now'), ?)`
|
|
7248
|
+
).run(key, value, expiresAt ?? null);
|
|
7249
|
+
return ok(undefined);
|
|
7250
|
+
} catch (cause) {
|
|
7251
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
7252
|
+
const rawCode =
|
|
7253
|
+
cause && typeof cause === "object" && "code" in cause
|
|
7254
|
+
? (cause as { code?: unknown }).code
|
|
7255
|
+
: undefined;
|
|
7256
|
+
const code = typeof rawCode === "string" ? rawCode : "";
|
|
7257
|
+
if (
|
|
7258
|
+
code.includes("READONLY") ||
|
|
7259
|
+
code.includes("BUSY") ||
|
|
7260
|
+
code.includes("LOCKED") ||
|
|
7261
|
+
/readonly|locked|busy/i.test(message)
|
|
7262
|
+
) {
|
|
7263
|
+
return ok(undefined);
|
|
7264
|
+
}
|
|
7265
|
+
return err(
|
|
7266
|
+
"QUERY_FAILED",
|
|
7267
|
+
cause instanceof Error ? cause.message : "Failed to write LLM cache",
|
|
7268
|
+
cause
|
|
7269
|
+
);
|
|
7270
|
+
}
|
|
7271
|
+
}
|
|
7272
|
+
|
|
6664
7273
|
async clearEmbeddingsForCollection(
|
|
6665
7274
|
collection: string,
|
|
6666
7275
|
options: { mode: "stale" | "all"; activeModel?: string }
|
|
@@ -7036,7 +7645,7 @@ function mapDocumentRow(row: DbDocumentRow): DocumentRow {
|
|
|
7036
7645
|
frontmatterDate: row.frontmatter_date,
|
|
7037
7646
|
dateFields,
|
|
7038
7647
|
typedMetadata: row.typed_metadata
|
|
7039
|
-
?
|
|
7648
|
+
? parseStoredTypedMetadata(row.typed_metadata)
|
|
7040
7649
|
: null,
|
|
7041
7650
|
metadataError: row.metadata_error,
|
|
7042
7651
|
recordKey: row.record_key,
|