@equationalapplications/core-llm-wiki 9.1.0 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SIJD5GEF.mjs → chunk-H436I7OM.mjs} +1832 -496
- package/dist/chunk-H436I7OM.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2161 -404
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +655 -236
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-CmcCGx0_.d.mts → testing-DsD-idCv.d.mts} +401 -29
- package/dist/{testing-CmcCGx0_.d.ts → testing-DsD-idCv.d.ts} +401 -29
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1298 -173
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-SIJD5GEF.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-
|
|
2
|
-
export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-
|
|
1
|
+
import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-H436I7OM.mjs';
|
|
2
|
+
export { CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-H436I7OM.mjs';
|
|
3
3
|
import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
|
|
4
4
|
import MiniSearch from 'minisearch';
|
|
5
5
|
|
|
@@ -348,10 +348,15 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
348
348
|
const chunk = ids.slice(i, i + this.chunkSize);
|
|
349
349
|
const placeholders = chunk.map(() => "?").join(",");
|
|
350
350
|
const chunkRows = await executor.getAllAsync(
|
|
351
|
-
`SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
|
|
351
|
+
`SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
|
|
352
352
|
chunk
|
|
353
353
|
);
|
|
354
|
-
rows.push(...chunkRows.map((row) => ({
|
|
354
|
+
rows.push(...chunkRows.map((row) => ({
|
|
355
|
+
id: row.id,
|
|
356
|
+
entity_id: row.entity_id,
|
|
357
|
+
updated_at: Number(row.updated_at),
|
|
358
|
+
deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
|
|
359
|
+
})));
|
|
355
360
|
}
|
|
356
361
|
return rows;
|
|
357
362
|
}
|
|
@@ -523,22 +528,25 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
523
528
|
* Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.
|
|
524
529
|
* Used by runPrune().
|
|
525
530
|
*/
|
|
526
|
-
async getPrunableMetadata(entityId, cutoff, tx) {
|
|
531
|
+
async getPrunableMetadata(entityId, cutoff, tx, opts) {
|
|
527
532
|
const executor = this.getExecutor(tx);
|
|
533
|
+
const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
|
|
534
|
+
const args = opts?.noCutoff ? [entityId] : [entityId, cutoff];
|
|
528
535
|
return executor.getAllAsync(
|
|
529
536
|
`SELECT id, entity_id FROM ${this.prefix}entries
|
|
530
|
-
WHERE entity_id = ? AND deleted_at IS NOT NULL
|
|
531
|
-
|
|
537
|
+
WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
|
|
538
|
+
args
|
|
532
539
|
);
|
|
533
540
|
}
|
|
534
541
|
/**
|
|
535
542
|
* Fetch all non-deleted entries for an entity, ordered by updated_at DESC.
|
|
536
543
|
* Used by _getFullBundle().
|
|
537
544
|
*/
|
|
538
|
-
async findAllByEntityId(entityId, tx) {
|
|
545
|
+
async findAllByEntityId(entityId, tx, opts) {
|
|
539
546
|
const executor = this.getExecutor(tx);
|
|
547
|
+
const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
|
|
540
548
|
const rows = await executor.getAllAsync(
|
|
541
|
-
`SELECT * FROM ${this.prefix}entries WHERE entity_id =
|
|
549
|
+
`SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
|
|
542
550
|
[entityId]
|
|
543
551
|
);
|
|
544
552
|
return rows.map(mapRowToFact);
|
|
@@ -618,10 +626,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
618
626
|
* Fetch all non-deleted entries for an entity with embedding blobs preserved.
|
|
619
627
|
* Used by ImportExportService for export/import round-tripping.
|
|
620
628
|
*/
|
|
621
|
-
async findAllByEntityIdWithBlobs(entityId, tx) {
|
|
629
|
+
async findAllByEntityIdWithBlobs(entityId, tx, opts) {
|
|
622
630
|
const executor = this.getExecutor(tx);
|
|
631
|
+
const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
|
|
623
632
|
const rows = await executor.getAllAsync(
|
|
624
|
-
`SELECT * FROM ${this.prefix}entries WHERE entity_id =
|
|
633
|
+
`SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
|
|
625
634
|
[entityId]
|
|
626
635
|
);
|
|
627
636
|
return rows.map(mapRowToFactWithBlobs);
|
|
@@ -692,20 +701,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
692
701
|
for (let i = 0; i < ids.length; i += chunkSize) {
|
|
693
702
|
const chunk = ids.slice(i, i + chunkSize);
|
|
694
703
|
const placeholders = chunk.map(() => "?").join(",");
|
|
704
|
+
const cutoffPredicate = opts.noCutoff ? "" : " AND deleted_at <= ?";
|
|
705
|
+
const delArgs = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];
|
|
695
706
|
const deleted = (await executor.getAllAsync(
|
|
696
|
-
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND
|
|
697
|
-
|
|
698
|
-
)).map((r) => r.id);
|
|
707
|
+
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,
|
|
708
|
+
delArgs
|
|
709
|
+
)).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === "number" ? r.deleted_at : Number(r.deleted_at) }));
|
|
699
710
|
totalChanges += deleted.length;
|
|
700
|
-
opts.deletedIds?.push(...deleted);
|
|
711
|
+
opts.deletedIds?.push(...deleted.map((r) => r.id));
|
|
701
712
|
if (deleted.length > 0) {
|
|
702
|
-
for (const
|
|
713
|
+
for (const row of deleted) {
|
|
703
714
|
await this.outbox.push({
|
|
704
715
|
entityId,
|
|
705
716
|
tableName: "entries",
|
|
706
|
-
recordId: id,
|
|
717
|
+
recordId: row.id,
|
|
707
718
|
operation: "DELETE",
|
|
708
|
-
payload: { id, entity_id: entityId, deleted_at:
|
|
719
|
+
payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at }
|
|
709
720
|
}, tx);
|
|
710
721
|
}
|
|
711
722
|
}
|
|
@@ -874,6 +885,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
874
885
|
);
|
|
875
886
|
return new Set(rows.map((r) => r.id));
|
|
876
887
|
}
|
|
888
|
+
/**
|
|
889
|
+
* Depth-aware supersession walk for chain forget (spec forget-erasure §3).
|
|
890
|
+
* Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;
|
|
891
|
+
* the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).
|
|
892
|
+
* No `deleted_at` filter: soft-deleted links still carry the chain.
|
|
893
|
+
*/
|
|
894
|
+
async findSupersessionChainWalk(entityId, factId, maxDepth, tx) {
|
|
895
|
+
const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);
|
|
896
|
+
const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);
|
|
897
|
+
const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
|
|
898
|
+
const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
|
|
899
|
+
return { ids: Array.from(/* @__PURE__ */ new Set([...succ, ...pred])), truncated };
|
|
900
|
+
}
|
|
877
901
|
async findSupersessionChainIds(entityId, factId, maxDepth, tx) {
|
|
878
902
|
const executor = this.getExecutor(tx);
|
|
879
903
|
const successors = await executor.getAllAsync(
|
|
@@ -884,7 +908,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
884
908
|
JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?
|
|
885
909
|
WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?
|
|
886
910
|
)
|
|
887
|
-
SELECT id FROM fwd ORDER BY depth ASC`,
|
|
911
|
+
SELECT id, depth FROM fwd ORDER BY depth ASC`,
|
|
888
912
|
[factId, entityId, entityId, maxDepth]
|
|
889
913
|
);
|
|
890
914
|
const predecessors = await executor.getAllAsync(
|
|
@@ -895,10 +919,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
895
919
|
JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id
|
|
896
920
|
WHERE bwd.depth < ?
|
|
897
921
|
)
|
|
898
|
-
SELECT id FROM bwd ORDER BY depth DESC`,
|
|
922
|
+
SELECT id, depth FROM bwd ORDER BY depth DESC`,
|
|
899
923
|
[entityId, factId, entityId, maxDepth]
|
|
900
924
|
);
|
|
901
|
-
const drop = (
|
|
925
|
+
const drop = (rows) => rows.filter((r) => r.id !== factId);
|
|
902
926
|
return { predecessors: drop(predecessors), successors: drop(successors) };
|
|
903
927
|
}
|
|
904
928
|
async findExpiredIds(entityId, cutoff, tx) {
|
|
@@ -1188,20 +1212,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
1188
1212
|
FROM ${this.prefix}entries
|
|
1189
1213
|
WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
|
|
1190
1214
|
)
|
|
1191
|
-
SELECT source_ref,
|
|
1192
|
-
source_hash AS source_hash,
|
|
1193
|
-
fact_count AS fact_count,
|
|
1194
|
-
updated_at AS last_ingested_at
|
|
1215
|
+
SELECT ranked.source_ref,
|
|
1216
|
+
ranked.source_hash AS source_hash,
|
|
1217
|
+
ranked.fact_count AS fact_count,
|
|
1218
|
+
ranked.updated_at AS last_ingested_at,
|
|
1219
|
+
d.source_hash AS stored_hash,
|
|
1220
|
+
d.char_count AS stored_chars
|
|
1195
1221
|
FROM ranked
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1222
|
+
LEFT JOIN ${this.prefix}source_documents d
|
|
1223
|
+
ON d.entity_id = ? AND d.source_ref = ranked.source_ref
|
|
1224
|
+
WHERE ranked.rn = 1
|
|
1225
|
+
ORDER BY ranked.source_ref COLLATE BINARY`,
|
|
1226
|
+
[entityId, entityId]
|
|
1199
1227
|
);
|
|
1200
1228
|
return rows.map((r) => ({
|
|
1201
1229
|
sourceRef: r.source_ref,
|
|
1202
1230
|
sourceHash: r.source_hash,
|
|
1203
1231
|
factCount: Number(r.fact_count),
|
|
1204
|
-
lastIngestedAt: Number(r.last_ingested_at)
|
|
1232
|
+
lastIngestedAt: Number(r.last_ingested_at),
|
|
1233
|
+
// Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.
|
|
1234
|
+
stored: r.stored_hash === null || r.stored_hash === void 0 ? null : r.stored_hash === r.source_hash ? { charCount: Number(r.stored_chars) } : { charCount: Number(r.stored_chars), staleHash: true }
|
|
1205
1235
|
}));
|
|
1206
1236
|
}
|
|
1207
1237
|
/**
|
|
@@ -1699,10 +1729,15 @@ var TaskRepository = class extends BaseRepository {
|
|
|
1699
1729
|
const chunk = ids.slice(i, i + chunkSize);
|
|
1700
1730
|
const placeholders = chunk.map(() => "?").join(",");
|
|
1701
1731
|
const chunkRows = await executor.getAllAsync(
|
|
1702
|
-
`SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
|
|
1732
|
+
`SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
|
|
1703
1733
|
chunk
|
|
1704
1734
|
);
|
|
1705
|
-
rows.push(...chunkRows.map((row) => ({
|
|
1735
|
+
rows.push(...chunkRows.map((row) => ({
|
|
1736
|
+
id: row.id,
|
|
1737
|
+
entity_id: row.entity_id,
|
|
1738
|
+
updated_at: Number(row.updated_at),
|
|
1739
|
+
deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
|
|
1740
|
+
})));
|
|
1706
1741
|
}
|
|
1707
1742
|
return rows;
|
|
1708
1743
|
}
|
|
@@ -1865,10 +1900,11 @@ var TaskRepository = class extends BaseRepository {
|
|
|
1865
1900
|
* Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.
|
|
1866
1901
|
* Used by _getFullBundle().
|
|
1867
1902
|
*/
|
|
1868
|
-
async findAllByEntityId(entityId, tx) {
|
|
1903
|
+
async findAllByEntityId(entityId, tx, opts) {
|
|
1869
1904
|
const executor = this.getExecutor(tx);
|
|
1905
|
+
const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
|
|
1870
1906
|
const rows = await executor.getAllAsync(
|
|
1871
|
-
`SELECT * FROM ${this.prefix}tasks WHERE entity_id =
|
|
1907
|
+
`SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} ORDER BY priority DESC, created_at ASC`,
|
|
1872
1908
|
[entityId]
|
|
1873
1909
|
);
|
|
1874
1910
|
return rows.map(mapRowToTask);
|
|
@@ -1877,16 +1913,19 @@ var TaskRepository = class extends BaseRepository {
|
|
|
1877
1913
|
* Bulk delete pruned tasks (already soft-deleted) by cutoff date.
|
|
1878
1914
|
* Used by runPrune(). Returns number of deleted rows.
|
|
1879
1915
|
*/
|
|
1880
|
-
async bulkDeletePruned(entityId, cutoff, tx) {
|
|
1916
|
+
async bulkDeletePruned(entityId, cutoff, tx, opts) {
|
|
1881
1917
|
const executor = this.getExecutor(tx);
|
|
1918
|
+
const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
|
|
1919
|
+
const selectArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
|
|
1882
1920
|
const rowsToDelete = await executor.getAllAsync(
|
|
1883
|
-
`SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL
|
|
1884
|
-
|
|
1921
|
+
`SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
|
|
1922
|
+
selectArgs
|
|
1885
1923
|
);
|
|
1886
1924
|
if (rowsToDelete.length === 0) return 0;
|
|
1925
|
+
const deleteArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
|
|
1887
1926
|
const result = await executor.runAsync(
|
|
1888
|
-
`DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL
|
|
1889
|
-
|
|
1927
|
+
`DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
|
|
1928
|
+
deleteArgs
|
|
1890
1929
|
);
|
|
1891
1930
|
for (const row of rowsToDelete) {
|
|
1892
1931
|
await this.outbox.push(
|
|
@@ -2194,195 +2233,6 @@ var EventRepository = class extends BaseRepository {
|
|
|
2194
2233
|
return row?.total ?? 0;
|
|
2195
2234
|
}
|
|
2196
2235
|
};
|
|
2197
|
-
var MiniSearchIndexStrategy = class {
|
|
2198
|
-
constructor() {
|
|
2199
|
-
/**
|
|
2200
|
-
* Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
|
|
2201
|
-
* `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
|
|
2202
|
-
* not see this map; it only sees `hasIndexedEntity`. The previous
|
|
2203
|
-
* `miniSearchEntryIdsByEntity` lived on `SearchService`.
|
|
2204
|
-
*/
|
|
2205
|
-
this.entryIdsByEntity = /* @__PURE__ */ new Map();
|
|
2206
|
-
/**
|
|
2207
|
-
* Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
|
|
2208
|
-
* decide which ids are owned by `entityId` (the only safe membership test
|
|
2209
|
-
* — a rebuild that failed between its discard pass and the set replacement
|
|
2210
|
-
* can leave the forward set claiming ids the MiniSearch instance does not
|
|
2211
|
-
* hold). The pre-extraction `syncEntries` deleted from one set per id, not
|
|
2212
|
-
* from every entity's set.
|
|
2213
|
-
*/
|
|
2214
|
-
this.entityIdById = /* @__PURE__ */ new Map();
|
|
2215
|
-
this.index = this.createIndex();
|
|
2216
|
-
}
|
|
2217
|
-
/**
|
|
2218
|
-
* Build a fresh MiniSearch instance with the project's index options.
|
|
2219
|
-
* Called from the constructor and from `replaceAll`. We do not use
|
|
2220
|
-
* `removeAll()` on an existing instance because that empties the index but
|
|
2221
|
-
* leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
|
|
2222
|
-
* `syncEntries`' conditional vacuum early after a clear.
|
|
2223
|
-
*/
|
|
2224
|
-
createIndex() {
|
|
2225
|
-
return new MiniSearch({
|
|
2226
|
-
fields: ["title", "body", "tags"],
|
|
2227
|
-
storeFields: ["entity_id"],
|
|
2228
|
-
// Vacuuming is driven explicitly at the end of each serialized rebuild
|
|
2229
|
-
// (see SearchService.syncEntries). Auto-vacuum fires on its own
|
|
2230
|
-
// schedule, asynchronously with respect to the caller, and traversing
|
|
2231
|
-
// the tree mid-rebuild is what threw the uncaught TypeError in
|
|
2232
|
-
// MiniSearch.performVacuuming (#64).
|
|
2233
|
-
autoVacuum: false,
|
|
2234
|
-
searchOptions: {
|
|
2235
|
-
boost: { title: 2 },
|
|
2236
|
-
fuzzy: 0.2,
|
|
2237
|
-
prefix: true
|
|
2238
|
-
}
|
|
2239
|
-
});
|
|
2240
|
-
}
|
|
2241
|
-
/**
|
|
2242
|
-
* Incremental sync. Removes only ids currently tracked under `entityId`
|
|
2243
|
-
* (other entities' docs are untouched), then upserts `documents` by id.
|
|
2244
|
-
* The same id appearing in both `ids` and `documents` is discarded first
|
|
2245
|
-
* so the upsert does not throw on a duplicate id.
|
|
2246
|
-
*
|
|
2247
|
-
* Every document must carry `entityId` as its `entity_id`; a mismatch is
|
|
2248
|
-
* rejected before the write mutates anything. A tracking-only call
|
|
2249
|
-
* (`replace(entityId, [], [])`) registers the entity as indexed, matching
|
|
2250
|
-
* the interface contract.
|
|
2251
|
-
*
|
|
2252
|
-
* Atomicity: never awaits between the discard pass and `addDocuments`, so
|
|
2253
|
-
* a concurrent `search()` sees the index wholly before or wholly after,
|
|
2254
|
-
* never half-updated. This is the precondition the pre-extraction
|
|
2255
|
-
* `syncEntries` kept with its "no await from here to `addAll`" comment.
|
|
2256
|
-
*/
|
|
2257
|
-
async replace(entityId, ids, documents) {
|
|
2258
|
-
assertOwnedBy(entityId, documents);
|
|
2259
|
-
this.discardIds(ids, entityId);
|
|
2260
|
-
if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2261
|
-
this.addDocuments(documents);
|
|
2262
|
-
}
|
|
2263
|
-
/**
|
|
2264
|
-
* Per-entity rebuild. Removes every id tracked under `entityId` (with the
|
|
2265
|
-
* `index.has(id)` guard so a stale tracking set cannot make `discard()`
|
|
2266
|
-
* throw), then writes `documents`. The entity stays registered as
|
|
2267
|
-
* indexed — even when `documents` is empty — so the next `syncEntries`
|
|
2268
|
-
* call can take the fast path. Every document must belong to `entityId`.
|
|
2269
|
-
*/
|
|
2270
|
-
async replaceEntity(entityId, documents) {
|
|
2271
|
-
assertOwnedBy(entityId, documents);
|
|
2272
|
-
const previous = this.entryIdsByEntity.get(entityId);
|
|
2273
|
-
if (previous) this.discardIds([...previous]);
|
|
2274
|
-
this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2275
|
-
this.addDocuments(documents);
|
|
2276
|
-
}
|
|
2277
|
-
/**
|
|
2278
|
-
* Global rebuild / clear. Replaces the MiniSearch instance and clears both
|
|
2279
|
-
* id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
|
|
2280
|
-
* `SearchService.clearAll()` calls `replaceAll([])`.
|
|
2281
|
-
*/
|
|
2282
|
-
async replaceAll(documents) {
|
|
2283
|
-
this.index = this.createIndex();
|
|
2284
|
-
this.entryIdsByEntity.clear();
|
|
2285
|
-
this.entityIdById.clear();
|
|
2286
|
-
this.addDocuments(documents);
|
|
2287
|
-
}
|
|
2288
|
-
/**
|
|
2289
|
-
* Best-match-first search over the documents whose `entity_id` is in
|
|
2290
|
-
* `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
|
|
2291
|
-
* uses this to over-fetch candidates before the `limit` cap). Scores are
|
|
2292
|
-
* raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
|
|
2293
|
-
* any scaling, not the strategy.
|
|
2294
|
-
*/
|
|
2295
|
-
async search(query, options) {
|
|
2296
|
-
if (options.entityIds.length === 0) return [];
|
|
2297
|
-
const entityIdSet = new Set(options.entityIds);
|
|
2298
|
-
const limit = options.preFilterLimit ?? options.limit;
|
|
2299
|
-
const raw = this.index.search(query, {
|
|
2300
|
-
filter: (r) => entityIdSet.has(r.entity_id),
|
|
2301
|
-
combineWith: "OR"
|
|
2302
|
-
});
|
|
2303
|
-
raw.sort((a, b) => {
|
|
2304
|
-
const scoreDiff = b.score - a.score;
|
|
2305
|
-
if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
|
|
2306
|
-
return a.id.localeCompare(b.id);
|
|
2307
|
-
});
|
|
2308
|
-
return raw.slice(0, limit).map((r) => ({
|
|
2309
|
-
id: r.id,
|
|
2310
|
-
entity_id: r.entity_id,
|
|
2311
|
-
score: r.score
|
|
2312
|
-
}));
|
|
2313
|
-
}
|
|
2314
|
-
/**
|
|
2315
|
-
* Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
|
|
2316
|
-
* un-vacuumed discard inverts the relative scores of term-sharing
|
|
2317
|
-
* documents at any index size. `SearchService.syncEntries` calls this
|
|
2318
|
-
* after a discard-bearing turn. No-op when `dirtCount === 0`.
|
|
2319
|
-
*/
|
|
2320
|
-
async vacuum() {
|
|
2321
|
-
if (this.index.dirtCount > 0) {
|
|
2322
|
-
await this.index.vacuum();
|
|
2323
|
-
}
|
|
2324
|
-
}
|
|
2325
|
-
/**
|
|
2326
|
-
* `true` when `entityId` has been indexed at least once under the current
|
|
2327
|
-
* strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
|
|
2328
|
-
* kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
|
|
2329
|
-
*/
|
|
2330
|
-
hasIndexedEntity(entityId) {
|
|
2331
|
-
return this.entryIdsByEntity.has(entityId);
|
|
2332
|
-
}
|
|
2333
|
-
/**
|
|
2334
|
-
* Add `documents` to the MiniSearch instance and register them in
|
|
2335
|
-
* `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
|
|
2336
|
-
* during `add`, so each doc is copied first. `add` throws on an id the
|
|
2337
|
-
* index already holds — `replace` and `replaceEntity` discard first for
|
|
2338
|
-
* that reason.
|
|
2339
|
-
*
|
|
2340
|
-
* Adds and registers one document at a time: if a duplicate id throws
|
|
2341
|
-
* part-way through, every document already in the index is tracked, so
|
|
2342
|
-
* the next rebuild can discard it instead of failing on it again. This is
|
|
2343
|
-
* the precondition the per-turn recovery path relies on (#258 review).
|
|
2344
|
-
*/
|
|
2345
|
-
addDocuments(documents) {
|
|
2346
|
-
for (const d of documents) {
|
|
2347
|
-
const doc = { ...d };
|
|
2348
|
-
this.index.add(doc);
|
|
2349
|
-
const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
|
|
2350
|
-
set.add(doc.id);
|
|
2351
|
-
this.entryIdsByEntity.set(doc.entity_id, set);
|
|
2352
|
-
this.entityIdById.set(doc.id, doc.entity_id);
|
|
2353
|
-
}
|
|
2354
|
-
}
|
|
2355
|
-
/**
|
|
2356
|
-
* Discard `ids` from the MiniSearch instance and from both id maps, but
|
|
2357
|
-
* only for ids currently owned by `entityId` (the second argument). When
|
|
2358
|
-
* `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
|
|
2359
|
-
* path), every id is discarded regardless of owning entity.
|
|
2360
|
-
*
|
|
2361
|
-
* `index.has(id)` is the membership test of record: a rebuild that failed
|
|
2362
|
-
* between its own discard pass and the set replacement can leave the
|
|
2363
|
-
* tracking set claiming ids the index no longer holds — `discard()` throws
|
|
2364
|
-
* on those, so we guard.
|
|
2365
|
-
*/
|
|
2366
|
-
discardIds(ids, entityId) {
|
|
2367
|
-
for (const id of ids) {
|
|
2368
|
-
const owning = this.entityIdById.get(id);
|
|
2369
|
-
if (owning === void 0) continue;
|
|
2370
|
-
if (entityId !== void 0 && owning !== entityId) continue;
|
|
2371
|
-
if (this.index.has(id)) this.index.discard(id);
|
|
2372
|
-
this.entryIdsByEntity.get(owning)?.delete(id);
|
|
2373
|
-
this.entityIdById.delete(id);
|
|
2374
|
-
}
|
|
2375
|
-
}
|
|
2376
|
-
};
|
|
2377
|
-
function assertOwnedBy(entityId, documents) {
|
|
2378
|
-
for (const doc of documents) {
|
|
2379
|
-
if (doc.entity_id !== entityId) {
|
|
2380
|
-
throw new Error(
|
|
2381
|
-
`IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
|
|
2382
|
-
);
|
|
2383
|
-
}
|
|
2384
|
-
}
|
|
2385
|
-
}
|
|
2386
2236
|
|
|
2387
2237
|
// src/utils/monotonicNow.ts
|
|
2388
2238
|
var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
|
|
@@ -2400,12 +2250,46 @@ function buildFtsMatchQuery(query) {
|
|
|
2400
2250
|
}
|
|
2401
2251
|
|
|
2402
2252
|
// src/services/search/Fts5IndexStrategy.ts
|
|
2253
|
+
async function hydratePassageHits(db, prefix, raw) {
|
|
2254
|
+
const docs = /* @__PURE__ */ new Map();
|
|
2255
|
+
const out = [];
|
|
2256
|
+
for (const r of raw) {
|
|
2257
|
+
const pas = await db.getFirstAsync(
|
|
2258
|
+
`SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`,
|
|
2259
|
+
[r.id, r.entity_id]
|
|
2260
|
+
);
|
|
2261
|
+
if (!pas) continue;
|
|
2262
|
+
const dk = `${r.entity_id}\0${r.document_id}`;
|
|
2263
|
+
if (!docs.has(dk)) {
|
|
2264
|
+
docs.set(dk, await db.getFirstAsync(
|
|
2265
|
+
`SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`,
|
|
2266
|
+
[r.document_id, r.entity_id]
|
|
2267
|
+
) ?? null);
|
|
2268
|
+
}
|
|
2269
|
+
const doc = docs.get(dk);
|
|
2270
|
+
if (!doc) continue;
|
|
2271
|
+
const start = Number(pas.start_offset);
|
|
2272
|
+
const end = Number(pas.end_offset);
|
|
2273
|
+
out.push({
|
|
2274
|
+
...r,
|
|
2275
|
+
seq: Number(pas.seq),
|
|
2276
|
+
start_offset: start,
|
|
2277
|
+
end_offset: end,
|
|
2278
|
+
source_ref: doc.source_ref,
|
|
2279
|
+
source_hash: doc.source_hash,
|
|
2280
|
+
text: doc.text.slice(start, end)
|
|
2281
|
+
});
|
|
2282
|
+
}
|
|
2283
|
+
return out;
|
|
2284
|
+
}
|
|
2403
2285
|
var Fts5IndexStrategy = class {
|
|
2404
2286
|
constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
|
|
2405
2287
|
this.db = db;
|
|
2406
2288
|
this.prefix = prefix;
|
|
2407
2289
|
this.metadataRepo = metadataRepo;
|
|
2408
2290
|
this.budgetMs = budgetMs;
|
|
2291
|
+
/** Set when passage-index init failed; passage drain and search become no-ops. */
|
|
2292
|
+
this.passagesDisabled = false;
|
|
2409
2293
|
}
|
|
2410
2294
|
/**
|
|
2411
2295
|
* Resolves the index state (spec #280 Change 3 transition table). Every
|
|
@@ -2413,6 +2297,120 @@ var Fts5IndexStrategy = class {
|
|
|
2413
2297
|
* failure leaves zero mutation (Change 4 ordering).
|
|
2414
2298
|
*/
|
|
2415
2299
|
async init(opts = {}) {
|
|
2300
|
+
await this.initEntries(opts);
|
|
2301
|
+
try {
|
|
2302
|
+
await this.ensurePassageObjects();
|
|
2303
|
+
} catch (err) {
|
|
2304
|
+
this.passagesDisabled = true;
|
|
2305
|
+
console.warn("[WikiMemory] passage index init failed; passage search returns [] until a later open:", err);
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
/**
|
|
2309
|
+
* Source-store passage index objects (spec source-store §6): created here,
|
|
2310
|
+
* the way the entries_fts objects are, never by setupDatabase. Skipped when
|
|
2311
|
+
* the store tables are absent (a pre-v17 database).
|
|
2312
|
+
*/
|
|
2313
|
+
async ensurePassageObjects() {
|
|
2314
|
+
const p = this.prefix;
|
|
2315
|
+
if (!await this.metadataRepo.tableExists(`${p}source_passages`)) return;
|
|
2316
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
2317
|
+
await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));
|
|
2318
|
+
const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);
|
|
2319
|
+
const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
|
|
2320
|
+
if (mapped === null && queued === null) {
|
|
2321
|
+
await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
|
|
2322
|
+
await tx.runAsync(
|
|
2323
|
+
`INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
|
|
2324
|
+
SELECT entity_id, id FROM ${p}source_documents`
|
|
2325
|
+
);
|
|
2326
|
+
}
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
/**
|
|
2330
|
+
* Drain the passage ledger one document at a time (spec §6, the stated
|
|
2331
|
+
* departure from all-SQL): the document's text is read into JS and sliced at
|
|
2332
|
+
* the offsets the cutter stored, so transient memory is bounded by
|
|
2333
|
+
* `maxCharsPerSource` for the ONE document, never the store. Each document
|
|
2334
|
+
* is one transaction. `entityId` limits the drain to that entity's ledger rows.
|
|
2335
|
+
*/
|
|
2336
|
+
async drainPassages(opts = {}) {
|
|
2337
|
+
if (this.passagesDisabled) return;
|
|
2338
|
+
const p = this.prefix;
|
|
2339
|
+
if (!await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`)) return;
|
|
2340
|
+
for (; ; ) {
|
|
2341
|
+
if (opts.deadline !== void 0 && monotonicNow() >= opts.deadline) return;
|
|
2342
|
+
let ran = false;
|
|
2343
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
2344
|
+
const first = opts.entityId === void 0 ? await tx.getFirstAsync(
|
|
2345
|
+
`SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`
|
|
2346
|
+
) : await tx.getFirstAsync(
|
|
2347
|
+
`SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,
|
|
2348
|
+
[opts.entityId]
|
|
2349
|
+
);
|
|
2350
|
+
if (!first) return;
|
|
2351
|
+
const docId = first.doc_id;
|
|
2352
|
+
const ent = first.entity_id;
|
|
2353
|
+
const hi = await tx.getFirstAsync(
|
|
2354
|
+
`SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`,
|
|
2355
|
+
[docId, ent]
|
|
2356
|
+
);
|
|
2357
|
+
await tx.runAsync(
|
|
2358
|
+
`DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,
|
|
2359
|
+
[docId]
|
|
2360
|
+
);
|
|
2361
|
+
await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);
|
|
2362
|
+
const doc = await tx.getFirstAsync(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);
|
|
2363
|
+
if (doc) {
|
|
2364
|
+
const rows = await tx.getAllAsync(
|
|
2365
|
+
`SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`,
|
|
2366
|
+
[docId, ent]
|
|
2367
|
+
);
|
|
2368
|
+
for (const r of rows) {
|
|
2369
|
+
const { lastInsertRowId } = await tx.runAsync(
|
|
2370
|
+
`INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`,
|
|
2371
|
+
[r.id, docId]
|
|
2372
|
+
);
|
|
2373
|
+
await tx.runAsync(
|
|
2374
|
+
`INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,
|
|
2375
|
+
[lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]
|
|
2376
|
+
);
|
|
2377
|
+
}
|
|
2378
|
+
}
|
|
2379
|
+
await tx.runAsync(
|
|
2380
|
+
`DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`,
|
|
2381
|
+
[docId, hi?.hi ?? 0]
|
|
2382
|
+
);
|
|
2383
|
+
ran = true;
|
|
2384
|
+
});
|
|
2385
|
+
if (!ran) return;
|
|
2386
|
+
}
|
|
2387
|
+
}
|
|
2388
|
+
/**
|
|
2389
|
+
* Best-match-first passage search. A hit counts only while its
|
|
2390
|
+
* `source_passages` row exists, so a stalled drain never surfaces a deleted
|
|
2391
|
+
* passage (spec §5).
|
|
2392
|
+
*/
|
|
2393
|
+
async searchPassages(query, options) {
|
|
2394
|
+
if (this.passagesDisabled || options.entityIds.length === 0) return [];
|
|
2395
|
+
const match = buildFtsMatchQuery(query);
|
|
2396
|
+
if (match === null) return [];
|
|
2397
|
+
const p = this.prefix;
|
|
2398
|
+
const t = `${p}source_passages_fts`;
|
|
2399
|
+
const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;
|
|
2400
|
+
const raw = await this.db.getAllAsync(
|
|
2401
|
+
`SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (
|
|
2402
|
+
SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw
|
|
2403
|
+
FROM ${t}
|
|
2404
|
+
WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
|
|
2405
|
+
AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))
|
|
2406
|
+
ORDER BY raw, passage_id
|
|
2407
|
+
LIMIT ?)
|
|
2408
|
+
ORDER BY raw, id`,
|
|
2409
|
+
[match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit]
|
|
2410
|
+
);
|
|
2411
|
+
return hydratePassageHits(this.db, p, raw);
|
|
2412
|
+
}
|
|
2413
|
+
async initEntries(opts) {
|
|
2416
2414
|
try {
|
|
2417
2415
|
await this.initOnce(opts);
|
|
2418
2416
|
} catch (err) {
|
|
@@ -2586,6 +2584,53 @@ var Fts5IndexStrategy = class {
|
|
|
2586
2584
|
if (!isSqliteError(err)) throw err;
|
|
2587
2585
|
}
|
|
2588
2586
|
}
|
|
2587
|
+
/** Listed retired table names (erase step 4 / module-less fallback). */
|
|
2588
|
+
async retiredTables() {
|
|
2589
|
+
return this.retiredList();
|
|
2590
|
+
}
|
|
2591
|
+
/**
|
|
2592
|
+
* Erase step 4: reclaim every retired table to completion (DROP + delist), no
|
|
2593
|
+
* deadline. Failures surface (unlike the best-effort quantum path); the
|
|
2594
|
+
* SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.
|
|
2595
|
+
*/
|
|
2596
|
+
async reclaimRetiredToCompletion() {
|
|
2597
|
+
await this.reclaimRetired(Number.POSITIVE_INFINITY);
|
|
2598
|
+
}
|
|
2599
|
+
/**
|
|
2600
|
+
* Erase step 3: surfaced passage drain, no deadline. Fails only when passage
|
|
2601
|
+
* init was disabled AND the ledger still has rows; otherwise warns and continues.
|
|
2602
|
+
*/
|
|
2603
|
+
async drainPassagesStrict() {
|
|
2604
|
+
if (this.passagesDisabled) {
|
|
2605
|
+
const p = this.prefix;
|
|
2606
|
+
const pending = await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`) !== null;
|
|
2607
|
+
if (pending) throw new Error("passage index disabled with pending ledger rows");
|
|
2608
|
+
console.warn("[WikiMemory] erase: passage index disabled; nothing pending, continuing");
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
await this.drainPassages({});
|
|
2612
|
+
}
|
|
2613
|
+
/**
|
|
2614
|
+
* Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to
|
|
2615
|
+
* empty, no deadline, errors surfaced; throws if rows remain afterwards.
|
|
2616
|
+
*/
|
|
2617
|
+
async drainEntriesLedgerStrict() {
|
|
2618
|
+
while (await this.drainLedgerChunk()) ;
|
|
2619
|
+
const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);
|
|
2620
|
+
if (left !== null && left !== void 0) throw new Error("entries FTS ledger still has pending rows after drain");
|
|
2621
|
+
}
|
|
2622
|
+
/** Erase step 7: FTS 'optimize' on each FTS table that exists. */
|
|
2623
|
+
async optimizeFts() {
|
|
2624
|
+
const p = this.prefix;
|
|
2625
|
+
for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {
|
|
2626
|
+
if (!await this.metadataRepo.tableExists(t)) continue;
|
|
2627
|
+
await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
/** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */
|
|
2631
|
+
async rebuildForErase() {
|
|
2632
|
+
await this.resetAndRearm();
|
|
2633
|
+
}
|
|
2589
2634
|
/** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */
|
|
2590
2635
|
async reclaimRetired(deadline) {
|
|
2591
2636
|
while (monotonicNow() < deadline) {
|
|
@@ -2894,6 +2939,281 @@ function assertEntity(entityId, documents) {
|
|
|
2894
2939
|
}
|
|
2895
2940
|
}
|
|
2896
2941
|
|
|
2942
|
+
// src/services/search/MiniSearchIndexStrategy.ts
|
|
2943
|
+
async function loadStoredPassages(db, prefix, entityId) {
|
|
2944
|
+
const out = [];
|
|
2945
|
+
const docs = await db.getAllAsync(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);
|
|
2946
|
+
for (const d of docs) {
|
|
2947
|
+
const doc = await db.getFirstAsync(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);
|
|
2948
|
+
if (!doc) continue;
|
|
2949
|
+
const rows = await db.getAllAsync(
|
|
2950
|
+
`SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`,
|
|
2951
|
+
[d.id]
|
|
2952
|
+
);
|
|
2953
|
+
for (const r of rows) {
|
|
2954
|
+
out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });
|
|
2955
|
+
}
|
|
2956
|
+
}
|
|
2957
|
+
return out;
|
|
2958
|
+
}
|
|
2959
|
+
var MiniSearchIndexStrategy = class {
|
|
2960
|
+
constructor() {
|
|
2961
|
+
/**
|
|
2962
|
+
* Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
|
|
2963
|
+
* `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
|
|
2964
|
+
* not see this map; it only sees `hasIndexedEntity`. The previous
|
|
2965
|
+
* `miniSearchEntryIdsByEntity` lived on `SearchService`.
|
|
2966
|
+
*/
|
|
2967
|
+
this.entryIdsByEntity = /* @__PURE__ */ new Map();
|
|
2968
|
+
/**
|
|
2969
|
+
* Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
|
|
2970
|
+
* decide which ids are owned by `entityId` (the only safe membership test
|
|
2971
|
+
* — a rebuild that failed between its discard pass and the set replacement
|
|
2972
|
+
* can leave the forward set claiming ids the MiniSearch instance does not
|
|
2973
|
+
* hold). The pre-extraction `syncEntries` deleted from one set per id, not
|
|
2974
|
+
* from every entity's set.
|
|
2975
|
+
*/
|
|
2976
|
+
this.entityIdById = /* @__PURE__ */ new Map();
|
|
2977
|
+
// ---- Source-store passage index (spec source-store §6) --------------------
|
|
2978
|
+
// A second in-heap instance over the same passage slices as the FTS5 path.
|
|
2979
|
+
this.passageIndex = this.createPassageIndex();
|
|
2980
|
+
this.passageIdsByEntity = /* @__PURE__ */ new Map();
|
|
2981
|
+
/** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */
|
|
2982
|
+
this.passageSource = null;
|
|
2983
|
+
this.index = this.createIndex();
|
|
2984
|
+
}
|
|
2985
|
+
/**
|
|
2986
|
+
* Build a fresh MiniSearch instance with the project's index options.
|
|
2987
|
+
* Called from the constructor and from `replaceAll`. We do not use
|
|
2988
|
+
* `removeAll()` on an existing instance because that empties the index but
|
|
2989
|
+
* leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
|
|
2990
|
+
* `syncEntries`' conditional vacuum early after a clear.
|
|
2991
|
+
*/
|
|
2992
|
+
createIndex() {
|
|
2993
|
+
return new MiniSearch({
|
|
2994
|
+
fields: ["title", "body", "tags"],
|
|
2995
|
+
storeFields: ["entity_id"],
|
|
2996
|
+
// Vacuuming is driven explicitly at the end of each serialized rebuild
|
|
2997
|
+
// (see SearchService.syncEntries). Auto-vacuum fires on its own
|
|
2998
|
+
// schedule, asynchronously with respect to the caller, and traversing
|
|
2999
|
+
// the tree mid-rebuild is what threw the uncaught TypeError in
|
|
3000
|
+
// MiniSearch.performVacuuming (#64).
|
|
3001
|
+
autoVacuum: false,
|
|
3002
|
+
searchOptions: {
|
|
3003
|
+
boost: { title: 2 },
|
|
3004
|
+
fuzzy: 0.2,
|
|
3005
|
+
prefix: true
|
|
3006
|
+
}
|
|
3007
|
+
});
|
|
3008
|
+
}
|
|
3009
|
+
/**
|
|
3010
|
+
* Incremental sync. Removes only ids currently tracked under `entityId`
|
|
3011
|
+
* (other entities' docs are untouched), then upserts `documents` by id.
|
|
3012
|
+
* The same id appearing in both `ids` and `documents` is discarded first
|
|
3013
|
+
* so the upsert does not throw on a duplicate id.
|
|
3014
|
+
*
|
|
3015
|
+
* Every document must carry `entityId` as its `entity_id`; a mismatch is
|
|
3016
|
+
* rejected before the write mutates anything. A tracking-only call
|
|
3017
|
+
* (`replace(entityId, [], [])`) registers the entity as indexed, matching
|
|
3018
|
+
* the interface contract.
|
|
3019
|
+
*
|
|
3020
|
+
* Atomicity: never awaits between the discard pass and `addDocuments`, so
|
|
3021
|
+
* a concurrent `search()` sees the index wholly before or wholly after,
|
|
3022
|
+
* never half-updated. This is the precondition the pre-extraction
|
|
3023
|
+
* `syncEntries` kept with its "no await from here to `addAll`" comment.
|
|
3024
|
+
*/
|
|
3025
|
+
async replace(entityId, ids, documents) {
|
|
3026
|
+
assertOwnedBy(entityId, documents);
|
|
3027
|
+
this.discardIds(ids, entityId);
|
|
3028
|
+
if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
3029
|
+
this.addDocuments(documents);
|
|
3030
|
+
}
|
|
3031
|
+
/**
|
|
3032
|
+
* Per-entity rebuild. Removes every id tracked under `entityId` (with the
|
|
3033
|
+
* `index.has(id)` guard so a stale tracking set cannot make `discard()`
|
|
3034
|
+
* throw), then writes `documents`. The entity stays registered as
|
|
3035
|
+
* indexed — even when `documents` is empty — so the next `syncEntries`
|
|
3036
|
+
* call can take the fast path. Every document must belong to `entityId`.
|
|
3037
|
+
*/
|
|
3038
|
+
async replaceEntity(entityId, documents) {
|
|
3039
|
+
assertOwnedBy(entityId, documents);
|
|
3040
|
+
const previous = this.entryIdsByEntity.get(entityId);
|
|
3041
|
+
if (previous) this.discardIds([...previous]);
|
|
3042
|
+
this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
3043
|
+
this.addDocuments(documents);
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Global rebuild / clear. Replaces the MiniSearch instance and clears both
|
|
3047
|
+
* id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
|
|
3048
|
+
* `SearchService.clearAll()` calls `replaceAll([])`.
|
|
3049
|
+
*/
|
|
3050
|
+
async replaceAll(documents) {
|
|
3051
|
+
this.index = this.createIndex();
|
|
3052
|
+
this.entryIdsByEntity.clear();
|
|
3053
|
+
this.entityIdById.clear();
|
|
3054
|
+
this.addDocuments(documents);
|
|
3055
|
+
}
|
|
3056
|
+
/**
|
|
3057
|
+
* Best-match-first search over the documents whose `entity_id` is in
|
|
3058
|
+
* `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
|
|
3059
|
+
* uses this to over-fetch candidates before the `limit` cap). Scores are
|
|
3060
|
+
* raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
|
|
3061
|
+
* any scaling, not the strategy.
|
|
3062
|
+
*/
|
|
3063
|
+
async search(query, options) {
|
|
3064
|
+
if (options.entityIds.length === 0) return [];
|
|
3065
|
+
const entityIdSet = new Set(options.entityIds);
|
|
3066
|
+
const limit = options.preFilterLimit ?? options.limit;
|
|
3067
|
+
const raw = this.index.search(query, {
|
|
3068
|
+
filter: (r) => entityIdSet.has(r.entity_id),
|
|
3069
|
+
combineWith: "OR"
|
|
3070
|
+
});
|
|
3071
|
+
raw.sort((a, b) => {
|
|
3072
|
+
const scoreDiff = b.score - a.score;
|
|
3073
|
+
if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
|
|
3074
|
+
return a.id.localeCompare(b.id);
|
|
3075
|
+
});
|
|
3076
|
+
return raw.slice(0, limit).map((r) => ({
|
|
3077
|
+
id: r.id,
|
|
3078
|
+
entity_id: r.entity_id,
|
|
3079
|
+
score: r.score
|
|
3080
|
+
}));
|
|
3081
|
+
}
|
|
3082
|
+
createPassageIndex() {
|
|
3083
|
+
return new MiniSearch({
|
|
3084
|
+
fields: ["text"],
|
|
3085
|
+
storeFields: ["entity_id", "document_id"],
|
|
3086
|
+
autoVacuum: false,
|
|
3087
|
+
// explicit vacuum below, same reason as the facts instance (#64)
|
|
3088
|
+
searchOptions: { fuzzy: 0.2, prefix: true }
|
|
3089
|
+
});
|
|
3090
|
+
}
|
|
3091
|
+
/**
|
|
3092
|
+
* Re-index stored passages from SQLite: one entity, or every stored entity
|
|
3093
|
+
* when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per
|
|
3094
|
+
* entity, and the heap grows with the number of stored entities, spec §6).
|
|
3095
|
+
* It is also the post-commit sync after forget/clearAll: deleted passages
|
|
3096
|
+
* drop out because the reload no longer finds their rows (spec §5).
|
|
3097
|
+
* Reads happen first; the discard and add are synchronous, so the swap is
|
|
3098
|
+
* atomic (a concurrent search sees the index wholly before or wholly after),
|
|
3099
|
+
* and the vacuum runs after the swap.
|
|
3100
|
+
*/
|
|
3101
|
+
async reindexSourcePassages(db, prefix, entityId) {
|
|
3102
|
+
this.passageSource = { db, prefix };
|
|
3103
|
+
const entityIds = entityId !== void 0 ? [entityId] : [.../* @__PURE__ */ new Set([
|
|
3104
|
+
...(await db.getAllAsync(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),
|
|
3105
|
+
...this.passageIdsByEntity.keys()
|
|
3106
|
+
])];
|
|
3107
|
+
for (const id of entityIds) {
|
|
3108
|
+
const passages = await loadStoredPassages(db, prefix, id);
|
|
3109
|
+
for (const old of this.passageIdsByEntity.get(id) ?? []) {
|
|
3110
|
+
if (this.passageIndex.has(old)) this.passageIndex.discard(old);
|
|
3111
|
+
}
|
|
3112
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3113
|
+
for (const d of passages) {
|
|
3114
|
+
this.passageIndex.add({ ...d });
|
|
3115
|
+
ids.add(d.id);
|
|
3116
|
+
}
|
|
3117
|
+
if (ids.size > 0) this.passageIdsByEntity.set(id, ids);
|
|
3118
|
+
else this.passageIdsByEntity.delete(id);
|
|
3119
|
+
if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();
|
|
3120
|
+
}
|
|
3121
|
+
}
|
|
3122
|
+
/** Best-match-first passage search over the entities in `options.entityIds`. */
|
|
3123
|
+
async searchPassages(query, options) {
|
|
3124
|
+
if (options.entityIds.length === 0 || !this.passageSource) return [];
|
|
3125
|
+
const allowed = new Set(options.entityIds);
|
|
3126
|
+
const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id), combineWith: "OR" });
|
|
3127
|
+
raw.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
3128
|
+
const live = /* @__PURE__ */ new Set();
|
|
3129
|
+
for (const eid of options.entityIds) {
|
|
3130
|
+
const rows = await this.passageSource.db.getAllAsync(
|
|
3131
|
+
`SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`,
|
|
3132
|
+
[eid]
|
|
3133
|
+
);
|
|
3134
|
+
for (const row of rows) live.add(row.id);
|
|
3135
|
+
}
|
|
3136
|
+
const hits = raw.filter((r) => live.has(r.id)).slice(0, options.limit).map((r) => ({
|
|
3137
|
+
id: r.id,
|
|
3138
|
+
entity_id: r.entity_id,
|
|
3139
|
+
document_id: r.document_id,
|
|
3140
|
+
score: r.score
|
|
3141
|
+
}));
|
|
3142
|
+
return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);
|
|
3143
|
+
}
|
|
3144
|
+
/**
|
|
3145
|
+
* Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
|
|
3146
|
+
* un-vacuumed discard inverts the relative scores of term-sharing
|
|
3147
|
+
* documents at any index size. `SearchService.syncEntries` calls this
|
|
3148
|
+
* after a discard-bearing turn. No-op when `dirtCount === 0`.
|
|
3149
|
+
*/
|
|
3150
|
+
async vacuum() {
|
|
3151
|
+
if (this.index.dirtCount > 0) {
|
|
3152
|
+
await this.index.vacuum();
|
|
3153
|
+
}
|
|
3154
|
+
}
|
|
3155
|
+
/**
|
|
3156
|
+
* `true` when `entityId` has been indexed at least once under the current
|
|
3157
|
+
* strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
|
|
3158
|
+
* kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
|
|
3159
|
+
*/
|
|
3160
|
+
hasIndexedEntity(entityId) {
|
|
3161
|
+
return this.entryIdsByEntity.has(entityId);
|
|
3162
|
+
}
|
|
3163
|
+
/**
|
|
3164
|
+
* Add `documents` to the MiniSearch instance and register them in
|
|
3165
|
+
* `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
|
|
3166
|
+
* during `add`, so each doc is copied first. `add` throws on an id the
|
|
3167
|
+
* index already holds — `replace` and `replaceEntity` discard first for
|
|
3168
|
+
* that reason.
|
|
3169
|
+
*
|
|
3170
|
+
* Adds and registers one document at a time: if a duplicate id throws
|
|
3171
|
+
* part-way through, every document already in the index is tracked, so
|
|
3172
|
+
* the next rebuild can discard it instead of failing on it again. This is
|
|
3173
|
+
* the precondition the per-turn recovery path relies on (#258 review).
|
|
3174
|
+
*/
|
|
3175
|
+
addDocuments(documents) {
|
|
3176
|
+
for (const d of documents) {
|
|
3177
|
+
const doc = { ...d };
|
|
3178
|
+
this.index.add(doc);
|
|
3179
|
+
const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
|
|
3180
|
+
set.add(doc.id);
|
|
3181
|
+
this.entryIdsByEntity.set(doc.entity_id, set);
|
|
3182
|
+
this.entityIdById.set(doc.id, doc.entity_id);
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
/**
|
|
3186
|
+
* Discard `ids` from the MiniSearch instance and from both id maps, but
|
|
3187
|
+
* only for ids currently owned by `entityId` (the second argument). When
|
|
3188
|
+
* `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
|
|
3189
|
+
* path), every id is discarded regardless of owning entity.
|
|
3190
|
+
*
|
|
3191
|
+
* `index.has(id)` is the membership test of record: a rebuild that failed
|
|
3192
|
+
* between its own discard pass and the set replacement can leave the
|
|
3193
|
+
* tracking set claiming ids the index no longer holds — `discard()` throws
|
|
3194
|
+
* on those, so we guard.
|
|
3195
|
+
*/
|
|
3196
|
+
discardIds(ids, entityId) {
|
|
3197
|
+
for (const id of ids) {
|
|
3198
|
+
const owning = this.entityIdById.get(id);
|
|
3199
|
+
if (owning === void 0) continue;
|
|
3200
|
+
if (entityId !== void 0 && owning !== entityId) continue;
|
|
3201
|
+
if (this.index.has(id)) this.index.discard(id);
|
|
3202
|
+
this.entryIdsByEntity.get(owning)?.delete(id);
|
|
3203
|
+
this.entityIdById.delete(id);
|
|
3204
|
+
}
|
|
3205
|
+
}
|
|
3206
|
+
};
|
|
3207
|
+
function assertOwnedBy(entityId, documents) {
|
|
3208
|
+
for (const doc of documents) {
|
|
3209
|
+
if (doc.entity_id !== entityId) {
|
|
3210
|
+
throw new Error(
|
|
3211
|
+
`IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
|
|
3212
|
+
);
|
|
3213
|
+
}
|
|
3214
|
+
}
|
|
3215
|
+
}
|
|
3216
|
+
|
|
2897
3217
|
// src/services/search/createIndexStrategy.ts
|
|
2898
3218
|
var FTS5_INIT_RETRY_MS = 250;
|
|
2899
3219
|
function isModuleAbsentError(err) {
|
|
@@ -2931,6 +3251,22 @@ async function probeFts5(db, prefix) {
|
|
|
2931
3251
|
}
|
|
2932
3252
|
}
|
|
2933
3253
|
async function detachFts5(db, prefix, metadataRepo) {
|
|
3254
|
+
const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);
|
|
3255
|
+
if (passageLedger) {
|
|
3256
|
+
const [ai, ad] = passageFtsTriggerNames(prefix);
|
|
3257
|
+
await db.withTransactionAsync(async (tx) => {
|
|
3258
|
+
await tx.execAsync(
|
|
3259
|
+
`DROP TRIGGER IF EXISTS ${ai};
|
|
3260
|
+
DROP TRIGGER IF EXISTS ${ad};
|
|
3261
|
+
DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;
|
|
3262
|
+
DROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`
|
|
3263
|
+
);
|
|
3264
|
+
});
|
|
3265
|
+
try {
|
|
3266
|
+
await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`);
|
|
3267
|
+
} catch {
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
2934
3270
|
const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
|
|
2935
3271
|
const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
|
|
2936
3272
|
if (!hasLedger && state !== "live") return;
|
|
@@ -3945,7 +4281,8 @@ var WikiMemory = class {
|
|
|
3945
4281
|
this.jobManager,
|
|
3946
4282
|
this.embeddingService,
|
|
3947
4283
|
this.options,
|
|
3948
|
-
this.vectorRemovalService
|
|
4284
|
+
this.vectorRemovalService,
|
|
4285
|
+
this.prefix
|
|
3949
4286
|
);
|
|
3950
4287
|
this.retrievalService = new RetrievalService(
|
|
3951
4288
|
this.options,
|
|
@@ -3955,6 +4292,7 @@ var WikiMemory = class {
|
|
|
3955
4292
|
this.metadataRepo,
|
|
3956
4293
|
this.searchService
|
|
3957
4294
|
);
|
|
4295
|
+
this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
|
|
3958
4296
|
this.writeService = new WriteService(
|
|
3959
4297
|
this.db,
|
|
3960
4298
|
this.options,
|
|
@@ -4082,11 +4420,22 @@ var WikiMemory = class {
|
|
|
4082
4420
|
* host runs a plain `setup()` outside the lease.
|
|
4083
4421
|
*
|
|
4084
4422
|
* Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
|
|
4085
|
-
* left converges on later opens and no-arg `syncSearchIndex()` calls
|
|
4086
|
-
*
|
|
4087
|
-
*
|
|
4423
|
+
* left converges on later opens, and on no-arg `syncSearchIndex()` calls for
|
|
4424
|
+
* the entries ledger. Passage-ledger leftover converges on later opens and on
|
|
4425
|
+
* passage-store writes for the entity (`storeSource`, `forget`,
|
|
4426
|
+
* `importDump`), which drain that entity's rows; no-arg calls do not touch
|
|
4427
|
+
* the passage ledger. Not bounded: an index reset (tokenizer change, re-attach
|
|
4428
|
+
* after detach, a lost or inconsistent index), which runs as one unchunked
|
|
4429
|
+
* transaction.
|
|
4088
4430
|
*/
|
|
4089
4431
|
async setup(opts) {
|
|
4432
|
+
await this.db.execAsync("PRAGMA secure_delete=ON");
|
|
4433
|
+
const secureDelete = await this.db.getFirstAsync("PRAGMA secure_delete");
|
|
4434
|
+
if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {
|
|
4435
|
+
console.warn(
|
|
4436
|
+
"[WikiMemory] PRAGMA secure_delete=ON (full zeroing) was not honored by this SQLite runtime; deleted content may remain recoverable in the database file until erase() verifies it."
|
|
4437
|
+
);
|
|
4438
|
+
}
|
|
4090
4439
|
const setupBudgetMs = this.setupBudgetMs();
|
|
4091
4440
|
const openDeadline = monotonicNow() + setupBudgetMs;
|
|
4092
4441
|
const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);
|
|
@@ -4128,6 +4477,7 @@ var WikiMemory = class {
|
|
|
4128
4477
|
)
|
|
4129
4478
|
);
|
|
4130
4479
|
await this.searchService.sync(void 0, { deadline: openDeadline });
|
|
4480
|
+
await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
|
|
4131
4481
|
await this.startSetupRemovalDrain();
|
|
4132
4482
|
}
|
|
4133
4483
|
/** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
|
|
@@ -4368,6 +4718,15 @@ var WikiMemory = class {
|
|
|
4368
4718
|
if (options?.prefix === void 0) return ids;
|
|
4369
4719
|
return ids.filter((id) => id.startsWith(options.prefix));
|
|
4370
4720
|
}
|
|
4721
|
+
/**
|
|
4722
|
+
* Erase everything soft-deleted, store-wide, and verify it (forget-erasure
|
|
4723
|
+
* spec §2). Throws `EraseStepError` (partial report, `verified: false`) when
|
|
4724
|
+
* a step fails; skipped entities report `verified: false`.
|
|
4725
|
+
* `{ rebuild: true }` additionally restarts the FTS rebuild.
|
|
4726
|
+
*/
|
|
4727
|
+
async erase(options) {
|
|
4728
|
+
return this.maintenanceService.erase(options);
|
|
4729
|
+
}
|
|
4371
4730
|
async runPrune(entityId, options) {
|
|
4372
4731
|
return this.maintenanceService.runPrune(entityId, options);
|
|
4373
4732
|
}
|
|
@@ -4550,6 +4909,7 @@ var WikiMemory = class {
|
|
|
4550
4909
|
);
|
|
4551
4910
|
this.searchService.setIndexStrategy(strategy);
|
|
4552
4911
|
if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();
|
|
4912
|
+
if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);
|
|
4553
4913
|
} finally {
|
|
4554
4914
|
if (this.searchService.isKeywordAvailable()) {
|
|
4555
4915
|
this.reinitFailures = 0;
|
|
@@ -4584,15 +4944,35 @@ var WikiMemory = class {
|
|
|
4584
4944
|
async syncDrained(sync) {
|
|
4585
4945
|
return await sync && this.searchService.isKeywordAvailable();
|
|
4586
4946
|
}
|
|
4587
|
-
async exportDump(entityIds) {
|
|
4588
|
-
return this.importExportService.exportDump(entityIds);
|
|
4947
|
+
async exportDump(entityIds, opts) {
|
|
4948
|
+
return this.importExportService.exportDump(entityIds, opts);
|
|
4949
|
+
}
|
|
4950
|
+
/**
|
|
4951
|
+
* The retention windows `runPrune()` uses when the host runs it (shipped
|
|
4952
|
+
* defaults plus host overrides), for GDPR disclosure. Nothing prunes
|
|
4953
|
+
* automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`
|
|
4954
|
+
* means "keep forever". Read-only.
|
|
4955
|
+
*/
|
|
4956
|
+
getRetentionPolicy() {
|
|
4957
|
+
const c = this.options.config;
|
|
4958
|
+
return {
|
|
4959
|
+
retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,
|
|
4960
|
+
retainEventsFor: c?.pruneEventsAfter ?? 30,
|
|
4961
|
+
pruneSupersededAfter: c?.pruneSupersededAfter ?? null
|
|
4962
|
+
};
|
|
4589
4963
|
}
|
|
4590
4964
|
/** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */
|
|
4591
4965
|
async getEntitySummary(entityId) {
|
|
4592
4966
|
return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
|
|
4593
4967
|
}
|
|
4594
4968
|
async importDump(dump, opts) {
|
|
4595
|
-
|
|
4969
|
+
try {
|
|
4970
|
+
return await this.importExportService.importDump(dump, opts);
|
|
4971
|
+
} finally {
|
|
4972
|
+
for (const entityId of Object.keys(dump?.entities ?? {})) {
|
|
4973
|
+
await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
4974
|
+
}
|
|
4975
|
+
}
|
|
4596
4976
|
}
|
|
4597
4977
|
/**
|
|
4598
4978
|
* Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
|
|
@@ -4613,7 +4993,28 @@ var WikiMemory = class {
|
|
|
4613
4993
|
* or call `runExternalDeletions()`.
|
|
4614
4994
|
*/
|
|
4615
4995
|
async forget(entityId, params, opts) {
|
|
4616
|
-
|
|
4996
|
+
try {
|
|
4997
|
+
return await this.maintenanceService.forget(entityId, params, opts);
|
|
4998
|
+
} finally {
|
|
4999
|
+
if (!opts?.dryRun) {
|
|
5000
|
+
await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
5001
|
+
}
|
|
5002
|
+
}
|
|
5003
|
+
}
|
|
5004
|
+
/** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */
|
|
5005
|
+
async storeSource(entityId, params) {
|
|
5006
|
+
assertEntityId2(entityId);
|
|
5007
|
+
const result = await this.sourceStoreService.storeSource(entityId, params);
|
|
5008
|
+
if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
5009
|
+
return result;
|
|
5010
|
+
}
|
|
5011
|
+
async getStoredSource(entityId, sourceRef) {
|
|
5012
|
+
assertEntityId2(entityId);
|
|
5013
|
+
return this.sourceStoreService.getStoredSource(entityId, sourceRef);
|
|
5014
|
+
}
|
|
5015
|
+
async listStoredSources(entityId) {
|
|
5016
|
+
assertEntityId2(entityId);
|
|
5017
|
+
return this.sourceStoreService.listStoredSources(entityId);
|
|
4617
5018
|
}
|
|
4618
5019
|
/**
|
|
4619
5020
|
* End `oldId`'s validity and link it to its replacement (spec §4.3). One
|
|
@@ -4970,6 +5371,10 @@ function renderEventPlain(event) {
|
|
|
4970
5371
|
const ts = new Date(event.created_at).toISOString();
|
|
4971
5372
|
return `[${event.event_type} @ ${ts}] ${event.summary}`;
|
|
4972
5373
|
}
|
|
5374
|
+
function renderSourceLabel(p, includeEntityId) {
|
|
5375
|
+
const entity = includeEntityId ? `${p.entityId} ` : "";
|
|
5376
|
+
return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
|
|
5377
|
+
}
|
|
4973
5378
|
function formatContext(bundle, options) {
|
|
4974
5379
|
const opts = {
|
|
4975
5380
|
format: options?.format ?? "markdown",
|
|
@@ -4995,7 +5400,8 @@ function formatContext(bundle, options) {
|
|
|
4995
5400
|
const sortedFacts = bundle.factScores ? [...bundle.facts].slice(0, opts.maxFacts) : [...bundle.facts].sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now)).slice(0, opts.maxFacts);
|
|
4996
5401
|
const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
|
|
4997
5402
|
const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
|
|
4998
|
-
|
|
5403
|
+
const sources = bundle.sources ?? [];
|
|
5404
|
+
if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
|
|
4999
5405
|
return "";
|
|
5000
5406
|
}
|
|
5001
5407
|
const isMarkdown = opts.format === "markdown";
|
|
@@ -5023,6 +5429,13 @@ function formatContext(bundle, options) {
|
|
|
5023
5429
|
lines.push(renderEventMarkdown(event));
|
|
5024
5430
|
}
|
|
5025
5431
|
}
|
|
5432
|
+
if (sources.length > 0) {
|
|
5433
|
+
lines.push("");
|
|
5434
|
+
lines.push("### Sources");
|
|
5435
|
+
for (const p of sources) {
|
|
5436
|
+
lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
|
|
5437
|
+
}
|
|
5438
|
+
}
|
|
5026
5439
|
} else {
|
|
5027
5440
|
if (sortedFacts.length > 0) {
|
|
5028
5441
|
lines.push("KNOWN FACTS:");
|
|
@@ -5042,6 +5455,12 @@ function formatContext(bundle, options) {
|
|
|
5042
5455
|
lines.push(renderEventPlain(event));
|
|
5043
5456
|
}
|
|
5044
5457
|
}
|
|
5458
|
+
if (sources.length > 0) {
|
|
5459
|
+
lines.push("SOURCES:");
|
|
5460
|
+
for (const p of sources) {
|
|
5461
|
+
lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
|
|
5462
|
+
}
|
|
5463
|
+
}
|
|
5045
5464
|
}
|
|
5046
5465
|
return lines.join("\n");
|
|
5047
5466
|
}
|