@equationalapplications/core-llm-wiki 9.0.0 → 9.2.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-G2H6TJUC.mjs → chunk-E3JCZMJL.mjs} +916 -24
- package/dist/chunk-E3JCZMJL.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1540 -293
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +577 -224
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-s6DBqXxQ.d.mts → testing-BQScWWSA.d.mts} +224 -17
- package/dist/{testing-s6DBqXxQ.d.ts → testing-BQScWWSA.d.ts} +224 -17
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +737 -33
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-G2H6TJUC.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { BaseRepository, WikiGraphNodeOwnershipConflict, 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, 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-E3JCZMJL.mjs';
|
|
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-E3JCZMJL.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
|
|
|
@@ -78,7 +78,8 @@ function mapRowToFact(row) {
|
|
|
78
78
|
const okf_verified = parseJsonArray(row.okf_verified, []);
|
|
79
79
|
const now = Date.now();
|
|
80
80
|
const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
|
|
81
|
-
|
|
81
|
+
const sourcePointer = parseStoredSourcePointer(row.source_pointer);
|
|
82
|
+
const mapped = {
|
|
82
83
|
id: row.id,
|
|
83
84
|
entity_id: row.entity_id,
|
|
84
85
|
title: row.title,
|
|
@@ -111,8 +112,13 @@ function mapRowToFact(row) {
|
|
|
111
112
|
...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
|
|
112
113
|
...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
|
|
113
114
|
...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
|
|
114
|
-
...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}
|
|
115
|
+
...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
|
|
116
|
+
// Source pointer (specs/source-pointers): key appears only when non-null,
|
|
117
|
+
// same temporal-fields pattern. Tolerant read: a malformed stored value
|
|
118
|
+
// reads as null without throwing (test 1).
|
|
119
|
+
...sourcePointer ? { source_pointer: sourcePointer } : {}
|
|
115
120
|
};
|
|
121
|
+
return mapped;
|
|
116
122
|
}
|
|
117
123
|
function normalizeEmbeddingBlobValue(blob) {
|
|
118
124
|
if (blob instanceof Uint8Array) return blob;
|
|
@@ -227,7 +233,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
227
233
|
const existingRow = await executor.getFirstAsync(
|
|
228
234
|
`SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
|
|
229
235
|
okf_sources, okf_verified, okf_usage_window,
|
|
230
|
-
last_verified_at, last_verified_by
|
|
236
|
+
last_verified_at, last_verified_by, source_pointer
|
|
231
237
|
FROM ${this.prefix}entries WHERE id = ?`,
|
|
232
238
|
[fact.id]
|
|
233
239
|
);
|
|
@@ -241,8 +247,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
241
247
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
242
248
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
243
249
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
244
|
-
okf_sources, okf_verified, okf_usage_window
|
|
245
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
250
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
251
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
246
252
|
ON CONFLICT(id) DO UPDATE SET
|
|
247
253
|
title = excluded.title,
|
|
248
254
|
body = excluded.body,
|
|
@@ -290,7 +296,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
290
296
|
fact.last_verified_by ?? null,
|
|
291
297
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
292
298
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
293
|
-
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
|
|
299
|
+
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
300
|
+
serializeSourcePointer(fact.source_pointer)
|
|
294
301
|
]
|
|
295
302
|
);
|
|
296
303
|
if (result.changes === 0) {
|
|
@@ -313,7 +320,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
313
320
|
okf_verified: parseJsonArray(existingRow.okf_verified, []),
|
|
314
321
|
okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
|
|
315
322
|
last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
|
|
316
|
-
last_verified_by: existingRow.last_verified_by ?? null
|
|
323
|
+
last_verified_by: existingRow.last_verified_by ?? null,
|
|
324
|
+
source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
|
|
317
325
|
} : null;
|
|
318
326
|
await this.outbox.push({
|
|
319
327
|
entityId: fact.entity_id,
|
|
@@ -373,7 +381,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
373
381
|
const rows = await executor.getAllAsync(sql, args);
|
|
374
382
|
return rows.map((row) => row.id);
|
|
375
383
|
}
|
|
376
|
-
async upsertForImport(fact, tx) {
|
|
384
|
+
async upsertForImport(fact, tx, sourcePointerPresent = false) {
|
|
377
385
|
const executor = this.getExecutor(tx);
|
|
378
386
|
const tagsJson = JSON.stringify(fact.tags);
|
|
379
387
|
const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
|
|
@@ -383,8 +391,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
383
391
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
384
392
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
385
393
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
386
|
-
okf_sources, okf_verified, okf_usage_window
|
|
387
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
394
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
395
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
388
396
|
ON CONFLICT(id) DO UPDATE SET
|
|
389
397
|
entity_id = excluded.entity_id,
|
|
390
398
|
title = excluded.title,
|
|
@@ -412,7 +420,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
412
420
|
last_verified_by = excluded.last_verified_by,
|
|
413
421
|
okf_sources = excluded.okf_sources,
|
|
414
422
|
okf_verified = excluded.okf_verified,
|
|
415
|
-
okf_usage_window = excluded.okf_usage_window
|
|
423
|
+
okf_usage_window = excluded.okf_usage_window,
|
|
424
|
+
source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
|
|
416
425
|
[
|
|
417
426
|
fact.id,
|
|
418
427
|
fact.entity_id,
|
|
@@ -439,7 +448,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
439
448
|
fact.last_verified_by ?? null,
|
|
440
449
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
441
450
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
442
|
-
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
|
|
451
|
+
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
452
|
+
serializeSourcePointer(fact.source_pointer),
|
|
453
|
+
// The presence flag binds to the SET clause's CASE, AFTER the INSERT
|
|
454
|
+
// values above.
|
|
455
|
+
sourcePointerPresent ? 1 : 0
|
|
443
456
|
]
|
|
444
457
|
);
|
|
445
458
|
return result;
|
|
@@ -1175,20 +1188,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
1175
1188
|
FROM ${this.prefix}entries
|
|
1176
1189
|
WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
|
|
1177
1190
|
)
|
|
1178
|
-
SELECT source_ref,
|
|
1179
|
-
source_hash AS source_hash,
|
|
1180
|
-
fact_count AS fact_count,
|
|
1181
|
-
updated_at AS last_ingested_at
|
|
1191
|
+
SELECT ranked.source_ref,
|
|
1192
|
+
ranked.source_hash AS source_hash,
|
|
1193
|
+
ranked.fact_count AS fact_count,
|
|
1194
|
+
ranked.updated_at AS last_ingested_at,
|
|
1195
|
+
d.source_hash AS stored_hash,
|
|
1196
|
+
d.char_count AS stored_chars
|
|
1182
1197
|
FROM ranked
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1198
|
+
LEFT JOIN ${this.prefix}source_documents d
|
|
1199
|
+
ON d.entity_id = ? AND d.source_ref = ranked.source_ref
|
|
1200
|
+
WHERE ranked.rn = 1
|
|
1201
|
+
ORDER BY ranked.source_ref COLLATE BINARY`,
|
|
1202
|
+
[entityId, entityId]
|
|
1186
1203
|
);
|
|
1187
1204
|
return rows.map((r) => ({
|
|
1188
1205
|
sourceRef: r.source_ref,
|
|
1189
1206
|
sourceHash: r.source_hash,
|
|
1190
1207
|
factCount: Number(r.fact_count),
|
|
1191
|
-
lastIngestedAt: Number(r.last_ingested_at)
|
|
1208
|
+
lastIngestedAt: Number(r.last_ingested_at),
|
|
1209
|
+
// Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.
|
|
1210
|
+
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 }
|
|
1192
1211
|
}));
|
|
1193
1212
|
}
|
|
1194
1213
|
/**
|
|
@@ -2181,195 +2200,6 @@ var EventRepository = class extends BaseRepository {
|
|
|
2181
2200
|
return row?.total ?? 0;
|
|
2182
2201
|
}
|
|
2183
2202
|
};
|
|
2184
|
-
var MiniSearchIndexStrategy = class {
|
|
2185
|
-
constructor() {
|
|
2186
|
-
/**
|
|
2187
|
-
* Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
|
|
2188
|
-
* `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
|
|
2189
|
-
* not see this map; it only sees `hasIndexedEntity`. The previous
|
|
2190
|
-
* `miniSearchEntryIdsByEntity` lived on `SearchService`.
|
|
2191
|
-
*/
|
|
2192
|
-
this.entryIdsByEntity = /* @__PURE__ */ new Map();
|
|
2193
|
-
/**
|
|
2194
|
-
* Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
|
|
2195
|
-
* decide which ids are owned by `entityId` (the only safe membership test
|
|
2196
|
-
* — a rebuild that failed between its discard pass and the set replacement
|
|
2197
|
-
* can leave the forward set claiming ids the MiniSearch instance does not
|
|
2198
|
-
* hold). The pre-extraction `syncEntries` deleted from one set per id, not
|
|
2199
|
-
* from every entity's set.
|
|
2200
|
-
*/
|
|
2201
|
-
this.entityIdById = /* @__PURE__ */ new Map();
|
|
2202
|
-
this.index = this.createIndex();
|
|
2203
|
-
}
|
|
2204
|
-
/**
|
|
2205
|
-
* Build a fresh MiniSearch instance with the project's index options.
|
|
2206
|
-
* Called from the constructor and from `replaceAll`. We do not use
|
|
2207
|
-
* `removeAll()` on an existing instance because that empties the index but
|
|
2208
|
-
* leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
|
|
2209
|
-
* `syncEntries`' conditional vacuum early after a clear.
|
|
2210
|
-
*/
|
|
2211
|
-
createIndex() {
|
|
2212
|
-
return new MiniSearch({
|
|
2213
|
-
fields: ["title", "body", "tags"],
|
|
2214
|
-
storeFields: ["entity_id"],
|
|
2215
|
-
// Vacuuming is driven explicitly at the end of each serialized rebuild
|
|
2216
|
-
// (see SearchService.syncEntries). Auto-vacuum fires on its own
|
|
2217
|
-
// schedule, asynchronously with respect to the caller, and traversing
|
|
2218
|
-
// the tree mid-rebuild is what threw the uncaught TypeError in
|
|
2219
|
-
// MiniSearch.performVacuuming (#64).
|
|
2220
|
-
autoVacuum: false,
|
|
2221
|
-
searchOptions: {
|
|
2222
|
-
boost: { title: 2 },
|
|
2223
|
-
fuzzy: 0.2,
|
|
2224
|
-
prefix: true
|
|
2225
|
-
}
|
|
2226
|
-
});
|
|
2227
|
-
}
|
|
2228
|
-
/**
|
|
2229
|
-
* Incremental sync. Removes only ids currently tracked under `entityId`
|
|
2230
|
-
* (other entities' docs are untouched), then upserts `documents` by id.
|
|
2231
|
-
* The same id appearing in both `ids` and `documents` is discarded first
|
|
2232
|
-
* so the upsert does not throw on a duplicate id.
|
|
2233
|
-
*
|
|
2234
|
-
* Every document must carry `entityId` as its `entity_id`; a mismatch is
|
|
2235
|
-
* rejected before the write mutates anything. A tracking-only call
|
|
2236
|
-
* (`replace(entityId, [], [])`) registers the entity as indexed, matching
|
|
2237
|
-
* the interface contract.
|
|
2238
|
-
*
|
|
2239
|
-
* Atomicity: never awaits between the discard pass and `addDocuments`, so
|
|
2240
|
-
* a concurrent `search()` sees the index wholly before or wholly after,
|
|
2241
|
-
* never half-updated. This is the precondition the pre-extraction
|
|
2242
|
-
* `syncEntries` kept with its "no await from here to `addAll`" comment.
|
|
2243
|
-
*/
|
|
2244
|
-
async replace(entityId, ids, documents) {
|
|
2245
|
-
assertOwnedBy(entityId, documents);
|
|
2246
|
-
this.discardIds(ids, entityId);
|
|
2247
|
-
if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2248
|
-
this.addDocuments(documents);
|
|
2249
|
-
}
|
|
2250
|
-
/**
|
|
2251
|
-
* Per-entity rebuild. Removes every id tracked under `entityId` (with the
|
|
2252
|
-
* `index.has(id)` guard so a stale tracking set cannot make `discard()`
|
|
2253
|
-
* throw), then writes `documents`. The entity stays registered as
|
|
2254
|
-
* indexed — even when `documents` is empty — so the next `syncEntries`
|
|
2255
|
-
* call can take the fast path. Every document must belong to `entityId`.
|
|
2256
|
-
*/
|
|
2257
|
-
async replaceEntity(entityId, documents) {
|
|
2258
|
-
assertOwnedBy(entityId, documents);
|
|
2259
|
-
const previous = this.entryIdsByEntity.get(entityId);
|
|
2260
|
-
if (previous) this.discardIds([...previous]);
|
|
2261
|
-
this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2262
|
-
this.addDocuments(documents);
|
|
2263
|
-
}
|
|
2264
|
-
/**
|
|
2265
|
-
* Global rebuild / clear. Replaces the MiniSearch instance and clears both
|
|
2266
|
-
* id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
|
|
2267
|
-
* `SearchService.clearAll()` calls `replaceAll([])`.
|
|
2268
|
-
*/
|
|
2269
|
-
async replaceAll(documents) {
|
|
2270
|
-
this.index = this.createIndex();
|
|
2271
|
-
this.entryIdsByEntity.clear();
|
|
2272
|
-
this.entityIdById.clear();
|
|
2273
|
-
this.addDocuments(documents);
|
|
2274
|
-
}
|
|
2275
|
-
/**
|
|
2276
|
-
* Best-match-first search over the documents whose `entity_id` is in
|
|
2277
|
-
* `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
|
|
2278
|
-
* uses this to over-fetch candidates before the `limit` cap). Scores are
|
|
2279
|
-
* raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
|
|
2280
|
-
* any scaling, not the strategy.
|
|
2281
|
-
*/
|
|
2282
|
-
async search(query, options) {
|
|
2283
|
-
if (options.entityIds.length === 0) return [];
|
|
2284
|
-
const entityIdSet = new Set(options.entityIds);
|
|
2285
|
-
const limit = options.preFilterLimit ?? options.limit;
|
|
2286
|
-
const raw = this.index.search(query, {
|
|
2287
|
-
filter: (r) => entityIdSet.has(r.entity_id),
|
|
2288
|
-
combineWith: "OR"
|
|
2289
|
-
});
|
|
2290
|
-
raw.sort((a, b) => {
|
|
2291
|
-
const scoreDiff = b.score - a.score;
|
|
2292
|
-
if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
|
|
2293
|
-
return a.id.localeCompare(b.id);
|
|
2294
|
-
});
|
|
2295
|
-
return raw.slice(0, limit).map((r) => ({
|
|
2296
|
-
id: r.id,
|
|
2297
|
-
entity_id: r.entity_id,
|
|
2298
|
-
score: r.score
|
|
2299
|
-
}));
|
|
2300
|
-
}
|
|
2301
|
-
/**
|
|
2302
|
-
* Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
|
|
2303
|
-
* un-vacuumed discard inverts the relative scores of term-sharing
|
|
2304
|
-
* documents at any index size. `SearchService.syncEntries` calls this
|
|
2305
|
-
* after a discard-bearing turn. No-op when `dirtCount === 0`.
|
|
2306
|
-
*/
|
|
2307
|
-
async vacuum() {
|
|
2308
|
-
if (this.index.dirtCount > 0) {
|
|
2309
|
-
await this.index.vacuum();
|
|
2310
|
-
}
|
|
2311
|
-
}
|
|
2312
|
-
/**
|
|
2313
|
-
* `true` when `entityId` has been indexed at least once under the current
|
|
2314
|
-
* strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
|
|
2315
|
-
* kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
|
|
2316
|
-
*/
|
|
2317
|
-
hasIndexedEntity(entityId) {
|
|
2318
|
-
return this.entryIdsByEntity.has(entityId);
|
|
2319
|
-
}
|
|
2320
|
-
/**
|
|
2321
|
-
* Add `documents` to the MiniSearch instance and register them in
|
|
2322
|
-
* `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
|
|
2323
|
-
* during `add`, so each doc is copied first. `add` throws on an id the
|
|
2324
|
-
* index already holds — `replace` and `replaceEntity` discard first for
|
|
2325
|
-
* that reason.
|
|
2326
|
-
*
|
|
2327
|
-
* Adds and registers one document at a time: if a duplicate id throws
|
|
2328
|
-
* part-way through, every document already in the index is tracked, so
|
|
2329
|
-
* the next rebuild can discard it instead of failing on it again. This is
|
|
2330
|
-
* the precondition the per-turn recovery path relies on (#258 review).
|
|
2331
|
-
*/
|
|
2332
|
-
addDocuments(documents) {
|
|
2333
|
-
for (const d of documents) {
|
|
2334
|
-
const doc = { ...d };
|
|
2335
|
-
this.index.add(doc);
|
|
2336
|
-
const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
|
|
2337
|
-
set.add(doc.id);
|
|
2338
|
-
this.entryIdsByEntity.set(doc.entity_id, set);
|
|
2339
|
-
this.entityIdById.set(doc.id, doc.entity_id);
|
|
2340
|
-
}
|
|
2341
|
-
}
|
|
2342
|
-
/**
|
|
2343
|
-
* Discard `ids` from the MiniSearch instance and from both id maps, but
|
|
2344
|
-
* only for ids currently owned by `entityId` (the second argument). When
|
|
2345
|
-
* `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
|
|
2346
|
-
* path), every id is discarded regardless of owning entity.
|
|
2347
|
-
*
|
|
2348
|
-
* `index.has(id)` is the membership test of record: a rebuild that failed
|
|
2349
|
-
* between its own discard pass and the set replacement can leave the
|
|
2350
|
-
* tracking set claiming ids the index no longer holds — `discard()` throws
|
|
2351
|
-
* on those, so we guard.
|
|
2352
|
-
*/
|
|
2353
|
-
discardIds(ids, entityId) {
|
|
2354
|
-
for (const id of ids) {
|
|
2355
|
-
const owning = this.entityIdById.get(id);
|
|
2356
|
-
if (owning === void 0) continue;
|
|
2357
|
-
if (entityId !== void 0 && owning !== entityId) continue;
|
|
2358
|
-
if (this.index.has(id)) this.index.discard(id);
|
|
2359
|
-
this.entryIdsByEntity.get(owning)?.delete(id);
|
|
2360
|
-
this.entityIdById.delete(id);
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
};
|
|
2364
|
-
function assertOwnedBy(entityId, documents) {
|
|
2365
|
-
for (const doc of documents) {
|
|
2366
|
-
if (doc.entity_id !== entityId) {
|
|
2367
|
-
throw new Error(
|
|
2368
|
-
`IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
|
|
2369
|
-
);
|
|
2370
|
-
}
|
|
2371
|
-
}
|
|
2372
|
-
}
|
|
2373
2203
|
|
|
2374
2204
|
// src/utils/monotonicNow.ts
|
|
2375
2205
|
var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
|
|
@@ -2387,12 +2217,46 @@ function buildFtsMatchQuery(query) {
|
|
|
2387
2217
|
}
|
|
2388
2218
|
|
|
2389
2219
|
// src/services/search/Fts5IndexStrategy.ts
|
|
2220
|
+
async function hydratePassageHits(db, prefix, raw) {
|
|
2221
|
+
const docs = /* @__PURE__ */ new Map();
|
|
2222
|
+
const out = [];
|
|
2223
|
+
for (const r of raw) {
|
|
2224
|
+
const pas = await db.getFirstAsync(
|
|
2225
|
+
`SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`,
|
|
2226
|
+
[r.id, r.entity_id]
|
|
2227
|
+
);
|
|
2228
|
+
if (!pas) continue;
|
|
2229
|
+
const dk = `${r.entity_id}\0${r.document_id}`;
|
|
2230
|
+
if (!docs.has(dk)) {
|
|
2231
|
+
docs.set(dk, await db.getFirstAsync(
|
|
2232
|
+
`SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`,
|
|
2233
|
+
[r.document_id, r.entity_id]
|
|
2234
|
+
) ?? null);
|
|
2235
|
+
}
|
|
2236
|
+
const doc = docs.get(dk);
|
|
2237
|
+
if (!doc) continue;
|
|
2238
|
+
const start = Number(pas.start_offset);
|
|
2239
|
+
const end = Number(pas.end_offset);
|
|
2240
|
+
out.push({
|
|
2241
|
+
...r,
|
|
2242
|
+
seq: Number(pas.seq),
|
|
2243
|
+
start_offset: start,
|
|
2244
|
+
end_offset: end,
|
|
2245
|
+
source_ref: doc.source_ref,
|
|
2246
|
+
source_hash: doc.source_hash,
|
|
2247
|
+
text: doc.text.slice(start, end)
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
return out;
|
|
2251
|
+
}
|
|
2390
2252
|
var Fts5IndexStrategy = class {
|
|
2391
2253
|
constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
|
|
2392
2254
|
this.db = db;
|
|
2393
2255
|
this.prefix = prefix;
|
|
2394
2256
|
this.metadataRepo = metadataRepo;
|
|
2395
2257
|
this.budgetMs = budgetMs;
|
|
2258
|
+
/** Set when passage-index init failed; passage drain and search become no-ops. */
|
|
2259
|
+
this.passagesDisabled = false;
|
|
2396
2260
|
}
|
|
2397
2261
|
/**
|
|
2398
2262
|
* Resolves the index state (spec #280 Change 3 transition table). Every
|
|
@@ -2400,6 +2264,120 @@ var Fts5IndexStrategy = class {
|
|
|
2400
2264
|
* failure leaves zero mutation (Change 4 ordering).
|
|
2401
2265
|
*/
|
|
2402
2266
|
async init(opts = {}) {
|
|
2267
|
+
await this.initEntries(opts);
|
|
2268
|
+
try {
|
|
2269
|
+
await this.ensurePassageObjects();
|
|
2270
|
+
} catch (err) {
|
|
2271
|
+
this.passagesDisabled = true;
|
|
2272
|
+
console.warn("[WikiMemory] passage index init failed; passage search returns [] until a later open:", err);
|
|
2273
|
+
}
|
|
2274
|
+
}
|
|
2275
|
+
/**
|
|
2276
|
+
* Source-store passage index objects (spec source-store §6): created here,
|
|
2277
|
+
* the way the entries_fts objects are, never by setupDatabase. Skipped when
|
|
2278
|
+
* the store tables are absent (a pre-v17 database).
|
|
2279
|
+
*/
|
|
2280
|
+
async ensurePassageObjects() {
|
|
2281
|
+
const p = this.prefix;
|
|
2282
|
+
if (!await this.metadataRepo.tableExists(`${p}source_passages`)) return;
|
|
2283
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
2284
|
+
await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));
|
|
2285
|
+
const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);
|
|
2286
|
+
const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
|
|
2287
|
+
if (mapped === null && queued === null) {
|
|
2288
|
+
await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
|
|
2289
|
+
await tx.runAsync(
|
|
2290
|
+
`INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
|
|
2291
|
+
SELECT entity_id, id FROM ${p}source_documents`
|
|
2292
|
+
);
|
|
2293
|
+
}
|
|
2294
|
+
});
|
|
2295
|
+
}
|
|
2296
|
+
/**
|
|
2297
|
+
* Drain the passage ledger one document at a time (spec §6, the stated
|
|
2298
|
+
* departure from all-SQL): the document's text is read into JS and sliced at
|
|
2299
|
+
* the offsets the cutter stored, so transient memory is bounded by
|
|
2300
|
+
* `maxCharsPerSource` for the ONE document, never the store. Each document
|
|
2301
|
+
* is one transaction. `entityId` limits the drain to that entity's ledger rows.
|
|
2302
|
+
*/
|
|
2303
|
+
async drainPassages(opts = {}) {
|
|
2304
|
+
if (this.passagesDisabled) return;
|
|
2305
|
+
const p = this.prefix;
|
|
2306
|
+
if (!await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`)) return;
|
|
2307
|
+
for (; ; ) {
|
|
2308
|
+
if (opts.deadline !== void 0 && monotonicNow() >= opts.deadline) return;
|
|
2309
|
+
let ran = false;
|
|
2310
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
2311
|
+
const first = opts.entityId === void 0 ? await tx.getFirstAsync(
|
|
2312
|
+
`SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`
|
|
2313
|
+
) : await tx.getFirstAsync(
|
|
2314
|
+
`SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,
|
|
2315
|
+
[opts.entityId]
|
|
2316
|
+
);
|
|
2317
|
+
if (!first) return;
|
|
2318
|
+
const docId = first.doc_id;
|
|
2319
|
+
const ent = first.entity_id;
|
|
2320
|
+
const hi = await tx.getFirstAsync(
|
|
2321
|
+
`SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`,
|
|
2322
|
+
[docId, ent]
|
|
2323
|
+
);
|
|
2324
|
+
await tx.runAsync(
|
|
2325
|
+
`DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,
|
|
2326
|
+
[docId]
|
|
2327
|
+
);
|
|
2328
|
+
await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);
|
|
2329
|
+
const doc = await tx.getFirstAsync(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);
|
|
2330
|
+
if (doc) {
|
|
2331
|
+
const rows = await tx.getAllAsync(
|
|
2332
|
+
`SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`,
|
|
2333
|
+
[docId, ent]
|
|
2334
|
+
);
|
|
2335
|
+
for (const r of rows) {
|
|
2336
|
+
const { lastInsertRowId } = await tx.runAsync(
|
|
2337
|
+
`INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`,
|
|
2338
|
+
[r.id, docId]
|
|
2339
|
+
);
|
|
2340
|
+
await tx.runAsync(
|
|
2341
|
+
`INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,
|
|
2342
|
+
[lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
}
|
|
2346
|
+
await tx.runAsync(
|
|
2347
|
+
`DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`,
|
|
2348
|
+
[docId, hi?.hi ?? 0]
|
|
2349
|
+
);
|
|
2350
|
+
ran = true;
|
|
2351
|
+
});
|
|
2352
|
+
if (!ran) return;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
/**
|
|
2356
|
+
* Best-match-first passage search. A hit counts only while its
|
|
2357
|
+
* `source_passages` row exists, so a stalled drain never surfaces a deleted
|
|
2358
|
+
* passage (spec §5).
|
|
2359
|
+
*/
|
|
2360
|
+
async searchPassages(query, options) {
|
|
2361
|
+
if (this.passagesDisabled || options.entityIds.length === 0) return [];
|
|
2362
|
+
const match = buildFtsMatchQuery(query);
|
|
2363
|
+
if (match === null) return [];
|
|
2364
|
+
const p = this.prefix;
|
|
2365
|
+
const t = `${p}source_passages_fts`;
|
|
2366
|
+
const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;
|
|
2367
|
+
const raw = await this.db.getAllAsync(
|
|
2368
|
+
`SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (
|
|
2369
|
+
SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw
|
|
2370
|
+
FROM ${t}
|
|
2371
|
+
WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
|
|
2372
|
+
AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))
|
|
2373
|
+
ORDER BY raw, passage_id
|
|
2374
|
+
LIMIT ?)
|
|
2375
|
+
ORDER BY raw, id`,
|
|
2376
|
+
[match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit]
|
|
2377
|
+
);
|
|
2378
|
+
return hydratePassageHits(this.db, p, raw);
|
|
2379
|
+
}
|
|
2380
|
+
async initEntries(opts) {
|
|
2403
2381
|
try {
|
|
2404
2382
|
await this.initOnce(opts);
|
|
2405
2383
|
} catch (err) {
|
|
@@ -2881,6 +2859,281 @@ function assertEntity(entityId, documents) {
|
|
|
2881
2859
|
}
|
|
2882
2860
|
}
|
|
2883
2861
|
|
|
2862
|
+
// src/services/search/MiniSearchIndexStrategy.ts
|
|
2863
|
+
async function loadStoredPassages(db, prefix, entityId) {
|
|
2864
|
+
const out = [];
|
|
2865
|
+
const docs = await db.getAllAsync(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);
|
|
2866
|
+
for (const d of docs) {
|
|
2867
|
+
const doc = await db.getFirstAsync(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);
|
|
2868
|
+
if (!doc) continue;
|
|
2869
|
+
const rows = await db.getAllAsync(
|
|
2870
|
+
`SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`,
|
|
2871
|
+
[d.id]
|
|
2872
|
+
);
|
|
2873
|
+
for (const r of rows) {
|
|
2874
|
+
out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2877
|
+
return out;
|
|
2878
|
+
}
|
|
2879
|
+
var MiniSearchIndexStrategy = class {
|
|
2880
|
+
constructor() {
|
|
2881
|
+
/**
|
|
2882
|
+
* Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
|
|
2883
|
+
* `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
|
|
2884
|
+
* not see this map; it only sees `hasIndexedEntity`. The previous
|
|
2885
|
+
* `miniSearchEntryIdsByEntity` lived on `SearchService`.
|
|
2886
|
+
*/
|
|
2887
|
+
this.entryIdsByEntity = /* @__PURE__ */ new Map();
|
|
2888
|
+
/**
|
|
2889
|
+
* Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
|
|
2890
|
+
* decide which ids are owned by `entityId` (the only safe membership test
|
|
2891
|
+
* — a rebuild that failed between its discard pass and the set replacement
|
|
2892
|
+
* can leave the forward set claiming ids the MiniSearch instance does not
|
|
2893
|
+
* hold). The pre-extraction `syncEntries` deleted from one set per id, not
|
|
2894
|
+
* from every entity's set.
|
|
2895
|
+
*/
|
|
2896
|
+
this.entityIdById = /* @__PURE__ */ new Map();
|
|
2897
|
+
// ---- Source-store passage index (spec source-store §6) --------------------
|
|
2898
|
+
// A second in-heap instance over the same passage slices as the FTS5 path.
|
|
2899
|
+
this.passageIndex = this.createPassageIndex();
|
|
2900
|
+
this.passageIdsByEntity = /* @__PURE__ */ new Map();
|
|
2901
|
+
/** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */
|
|
2902
|
+
this.passageSource = null;
|
|
2903
|
+
this.index = this.createIndex();
|
|
2904
|
+
}
|
|
2905
|
+
/**
|
|
2906
|
+
* Build a fresh MiniSearch instance with the project's index options.
|
|
2907
|
+
* Called from the constructor and from `replaceAll`. We do not use
|
|
2908
|
+
* `removeAll()` on an existing instance because that empties the index but
|
|
2909
|
+
* leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
|
|
2910
|
+
* `syncEntries`' conditional vacuum early after a clear.
|
|
2911
|
+
*/
|
|
2912
|
+
createIndex() {
|
|
2913
|
+
return new MiniSearch({
|
|
2914
|
+
fields: ["title", "body", "tags"],
|
|
2915
|
+
storeFields: ["entity_id"],
|
|
2916
|
+
// Vacuuming is driven explicitly at the end of each serialized rebuild
|
|
2917
|
+
// (see SearchService.syncEntries). Auto-vacuum fires on its own
|
|
2918
|
+
// schedule, asynchronously with respect to the caller, and traversing
|
|
2919
|
+
// the tree mid-rebuild is what threw the uncaught TypeError in
|
|
2920
|
+
// MiniSearch.performVacuuming (#64).
|
|
2921
|
+
autoVacuum: false,
|
|
2922
|
+
searchOptions: {
|
|
2923
|
+
boost: { title: 2 },
|
|
2924
|
+
fuzzy: 0.2,
|
|
2925
|
+
prefix: true
|
|
2926
|
+
}
|
|
2927
|
+
});
|
|
2928
|
+
}
|
|
2929
|
+
/**
|
|
2930
|
+
* Incremental sync. Removes only ids currently tracked under `entityId`
|
|
2931
|
+
* (other entities' docs are untouched), then upserts `documents` by id.
|
|
2932
|
+
* The same id appearing in both `ids` and `documents` is discarded first
|
|
2933
|
+
* so the upsert does not throw on a duplicate id.
|
|
2934
|
+
*
|
|
2935
|
+
* Every document must carry `entityId` as its `entity_id`; a mismatch is
|
|
2936
|
+
* rejected before the write mutates anything. A tracking-only call
|
|
2937
|
+
* (`replace(entityId, [], [])`) registers the entity as indexed, matching
|
|
2938
|
+
* the interface contract.
|
|
2939
|
+
*
|
|
2940
|
+
* Atomicity: never awaits between the discard pass and `addDocuments`, so
|
|
2941
|
+
* a concurrent `search()` sees the index wholly before or wholly after,
|
|
2942
|
+
* never half-updated. This is the precondition the pre-extraction
|
|
2943
|
+
* `syncEntries` kept with its "no await from here to `addAll`" comment.
|
|
2944
|
+
*/
|
|
2945
|
+
async replace(entityId, ids, documents) {
|
|
2946
|
+
assertOwnedBy(entityId, documents);
|
|
2947
|
+
this.discardIds(ids, entityId);
|
|
2948
|
+
if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2949
|
+
this.addDocuments(documents);
|
|
2950
|
+
}
|
|
2951
|
+
/**
|
|
2952
|
+
* Per-entity rebuild. Removes every id tracked under `entityId` (with the
|
|
2953
|
+
* `index.has(id)` guard so a stale tracking set cannot make `discard()`
|
|
2954
|
+
* throw), then writes `documents`. The entity stays registered as
|
|
2955
|
+
* indexed — even when `documents` is empty — so the next `syncEntries`
|
|
2956
|
+
* call can take the fast path. Every document must belong to `entityId`.
|
|
2957
|
+
*/
|
|
2958
|
+
async replaceEntity(entityId, documents) {
|
|
2959
|
+
assertOwnedBy(entityId, documents);
|
|
2960
|
+
const previous = this.entryIdsByEntity.get(entityId);
|
|
2961
|
+
if (previous) this.discardIds([...previous]);
|
|
2962
|
+
this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
|
|
2963
|
+
this.addDocuments(documents);
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* Global rebuild / clear. Replaces the MiniSearch instance and clears both
|
|
2967
|
+
* id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
|
|
2968
|
+
* `SearchService.clearAll()` calls `replaceAll([])`.
|
|
2969
|
+
*/
|
|
2970
|
+
async replaceAll(documents) {
|
|
2971
|
+
this.index = this.createIndex();
|
|
2972
|
+
this.entryIdsByEntity.clear();
|
|
2973
|
+
this.entityIdById.clear();
|
|
2974
|
+
this.addDocuments(documents);
|
|
2975
|
+
}
|
|
2976
|
+
/**
|
|
2977
|
+
* Best-match-first search over the documents whose `entity_id` is in
|
|
2978
|
+
* `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
|
|
2979
|
+
* uses this to over-fetch candidates before the `limit` cap). Scores are
|
|
2980
|
+
* raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
|
|
2981
|
+
* any scaling, not the strategy.
|
|
2982
|
+
*/
|
|
2983
|
+
async search(query, options) {
|
|
2984
|
+
if (options.entityIds.length === 0) return [];
|
|
2985
|
+
const entityIdSet = new Set(options.entityIds);
|
|
2986
|
+
const limit = options.preFilterLimit ?? options.limit;
|
|
2987
|
+
const raw = this.index.search(query, {
|
|
2988
|
+
filter: (r) => entityIdSet.has(r.entity_id),
|
|
2989
|
+
combineWith: "OR"
|
|
2990
|
+
});
|
|
2991
|
+
raw.sort((a, b) => {
|
|
2992
|
+
const scoreDiff = b.score - a.score;
|
|
2993
|
+
if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
|
|
2994
|
+
return a.id.localeCompare(b.id);
|
|
2995
|
+
});
|
|
2996
|
+
return raw.slice(0, limit).map((r) => ({
|
|
2997
|
+
id: r.id,
|
|
2998
|
+
entity_id: r.entity_id,
|
|
2999
|
+
score: r.score
|
|
3000
|
+
}));
|
|
3001
|
+
}
|
|
3002
|
+
createPassageIndex() {
|
|
3003
|
+
return new MiniSearch({
|
|
3004
|
+
fields: ["text"],
|
|
3005
|
+
storeFields: ["entity_id", "document_id"],
|
|
3006
|
+
autoVacuum: false,
|
|
3007
|
+
// explicit vacuum below, same reason as the facts instance (#64)
|
|
3008
|
+
searchOptions: { fuzzy: 0.2, prefix: true }
|
|
3009
|
+
});
|
|
3010
|
+
}
|
|
3011
|
+
/**
|
|
3012
|
+
* Re-index stored passages from SQLite: one entity, or every stored entity
|
|
3013
|
+
* when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per
|
|
3014
|
+
* entity, and the heap grows with the number of stored entities, spec §6).
|
|
3015
|
+
* It is also the post-commit sync after forget/clearAll: deleted passages
|
|
3016
|
+
* drop out because the reload no longer finds their rows (spec §5).
|
|
3017
|
+
* Reads happen first; the discard and add are synchronous, so the swap is
|
|
3018
|
+
* atomic (a concurrent search sees the index wholly before or wholly after),
|
|
3019
|
+
* and the vacuum runs after the swap.
|
|
3020
|
+
*/
|
|
3021
|
+
async reindexSourcePassages(db, prefix, entityId) {
|
|
3022
|
+
this.passageSource = { db, prefix };
|
|
3023
|
+
const entityIds = entityId !== void 0 ? [entityId] : [.../* @__PURE__ */ new Set([
|
|
3024
|
+
...(await db.getAllAsync(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),
|
|
3025
|
+
...this.passageIdsByEntity.keys()
|
|
3026
|
+
])];
|
|
3027
|
+
for (const id of entityIds) {
|
|
3028
|
+
const passages = await loadStoredPassages(db, prefix, id);
|
|
3029
|
+
for (const old of this.passageIdsByEntity.get(id) ?? []) {
|
|
3030
|
+
if (this.passageIndex.has(old)) this.passageIndex.discard(old);
|
|
3031
|
+
}
|
|
3032
|
+
const ids = /* @__PURE__ */ new Set();
|
|
3033
|
+
for (const d of passages) {
|
|
3034
|
+
this.passageIndex.add({ ...d });
|
|
3035
|
+
ids.add(d.id);
|
|
3036
|
+
}
|
|
3037
|
+
if (ids.size > 0) this.passageIdsByEntity.set(id, ids);
|
|
3038
|
+
else this.passageIdsByEntity.delete(id);
|
|
3039
|
+
if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
/** Best-match-first passage search over the entities in `options.entityIds`. */
|
|
3043
|
+
async searchPassages(query, options) {
|
|
3044
|
+
if (options.entityIds.length === 0 || !this.passageSource) return [];
|
|
3045
|
+
const allowed = new Set(options.entityIds);
|
|
3046
|
+
const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id), combineWith: "OR" });
|
|
3047
|
+
raw.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
|
|
3048
|
+
const live = /* @__PURE__ */ new Set();
|
|
3049
|
+
for (const eid of options.entityIds) {
|
|
3050
|
+
const rows = await this.passageSource.db.getAllAsync(
|
|
3051
|
+
`SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`,
|
|
3052
|
+
[eid]
|
|
3053
|
+
);
|
|
3054
|
+
for (const row of rows) live.add(row.id);
|
|
3055
|
+
}
|
|
3056
|
+
const hits = raw.filter((r) => live.has(r.id)).slice(0, options.limit).map((r) => ({
|
|
3057
|
+
id: r.id,
|
|
3058
|
+
entity_id: r.entity_id,
|
|
3059
|
+
document_id: r.document_id,
|
|
3060
|
+
score: r.score
|
|
3061
|
+
}));
|
|
3062
|
+
return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);
|
|
3063
|
+
}
|
|
3064
|
+
/**
|
|
3065
|
+
* Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
|
|
3066
|
+
* un-vacuumed discard inverts the relative scores of term-sharing
|
|
3067
|
+
* documents at any index size. `SearchService.syncEntries` calls this
|
|
3068
|
+
* after a discard-bearing turn. No-op when `dirtCount === 0`.
|
|
3069
|
+
*/
|
|
3070
|
+
async vacuum() {
|
|
3071
|
+
if (this.index.dirtCount > 0) {
|
|
3072
|
+
await this.index.vacuum();
|
|
3073
|
+
}
|
|
3074
|
+
}
|
|
3075
|
+
/**
|
|
3076
|
+
* `true` when `entityId` has been indexed at least once under the current
|
|
3077
|
+
* strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
|
|
3078
|
+
* kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
|
|
3079
|
+
*/
|
|
3080
|
+
hasIndexedEntity(entityId) {
|
|
3081
|
+
return this.entryIdsByEntity.has(entityId);
|
|
3082
|
+
}
|
|
3083
|
+
/**
|
|
3084
|
+
* Add `documents` to the MiniSearch instance and register them in
|
|
3085
|
+
* `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
|
|
3086
|
+
* during `add`, so each doc is copied first. `add` throws on an id the
|
|
3087
|
+
* index already holds — `replace` and `replaceEntity` discard first for
|
|
3088
|
+
* that reason.
|
|
3089
|
+
*
|
|
3090
|
+
* Adds and registers one document at a time: if a duplicate id throws
|
|
3091
|
+
* part-way through, every document already in the index is tracked, so
|
|
3092
|
+
* the next rebuild can discard it instead of failing on it again. This is
|
|
3093
|
+
* the precondition the per-turn recovery path relies on (#258 review).
|
|
3094
|
+
*/
|
|
3095
|
+
addDocuments(documents) {
|
|
3096
|
+
for (const d of documents) {
|
|
3097
|
+
const doc = { ...d };
|
|
3098
|
+
this.index.add(doc);
|
|
3099
|
+
const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
|
|
3100
|
+
set.add(doc.id);
|
|
3101
|
+
this.entryIdsByEntity.set(doc.entity_id, set);
|
|
3102
|
+
this.entityIdById.set(doc.id, doc.entity_id);
|
|
3103
|
+
}
|
|
3104
|
+
}
|
|
3105
|
+
/**
|
|
3106
|
+
* Discard `ids` from the MiniSearch instance and from both id maps, but
|
|
3107
|
+
* only for ids currently owned by `entityId` (the second argument). When
|
|
3108
|
+
* `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
|
|
3109
|
+
* path), every id is discarded regardless of owning entity.
|
|
3110
|
+
*
|
|
3111
|
+
* `index.has(id)` is the membership test of record: a rebuild that failed
|
|
3112
|
+
* between its own discard pass and the set replacement can leave the
|
|
3113
|
+
* tracking set claiming ids the index no longer holds — `discard()` throws
|
|
3114
|
+
* on those, so we guard.
|
|
3115
|
+
*/
|
|
3116
|
+
discardIds(ids, entityId) {
|
|
3117
|
+
for (const id of ids) {
|
|
3118
|
+
const owning = this.entityIdById.get(id);
|
|
3119
|
+
if (owning === void 0) continue;
|
|
3120
|
+
if (entityId !== void 0 && owning !== entityId) continue;
|
|
3121
|
+
if (this.index.has(id)) this.index.discard(id);
|
|
3122
|
+
this.entryIdsByEntity.get(owning)?.delete(id);
|
|
3123
|
+
this.entityIdById.delete(id);
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
};
|
|
3127
|
+
function assertOwnedBy(entityId, documents) {
|
|
3128
|
+
for (const doc of documents) {
|
|
3129
|
+
if (doc.entity_id !== entityId) {
|
|
3130
|
+
throw new Error(
|
|
3131
|
+
`IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
|
|
3132
|
+
);
|
|
3133
|
+
}
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
|
|
2884
3137
|
// src/services/search/createIndexStrategy.ts
|
|
2885
3138
|
var FTS5_INIT_RETRY_MS = 250;
|
|
2886
3139
|
function isModuleAbsentError(err) {
|
|
@@ -2918,6 +3171,22 @@ async function probeFts5(db, prefix) {
|
|
|
2918
3171
|
}
|
|
2919
3172
|
}
|
|
2920
3173
|
async function detachFts5(db, prefix, metadataRepo) {
|
|
3174
|
+
const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);
|
|
3175
|
+
if (passageLedger) {
|
|
3176
|
+
const [ai, ad] = passageFtsTriggerNames(prefix);
|
|
3177
|
+
await db.withTransactionAsync(async (tx) => {
|
|
3178
|
+
await tx.execAsync(
|
|
3179
|
+
`DROP TRIGGER IF EXISTS ${ai};
|
|
3180
|
+
DROP TRIGGER IF EXISTS ${ad};
|
|
3181
|
+
DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;
|
|
3182
|
+
DROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`
|
|
3183
|
+
);
|
|
3184
|
+
});
|
|
3185
|
+
try {
|
|
3186
|
+
await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`);
|
|
3187
|
+
} catch {
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
2921
3190
|
const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
|
|
2922
3191
|
const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
|
|
2923
3192
|
if (!hasLedger && state !== "live") return;
|
|
@@ -3932,7 +4201,8 @@ var WikiMemory = class {
|
|
|
3932
4201
|
this.jobManager,
|
|
3933
4202
|
this.embeddingService,
|
|
3934
4203
|
this.options,
|
|
3935
|
-
this.vectorRemovalService
|
|
4204
|
+
this.vectorRemovalService,
|
|
4205
|
+
this.prefix
|
|
3936
4206
|
);
|
|
3937
4207
|
this.retrievalService = new RetrievalService(
|
|
3938
4208
|
this.options,
|
|
@@ -3942,6 +4212,7 @@ var WikiMemory = class {
|
|
|
3942
4212
|
this.metadataRepo,
|
|
3943
4213
|
this.searchService
|
|
3944
4214
|
);
|
|
4215
|
+
this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
|
|
3945
4216
|
this.writeService = new WriteService(
|
|
3946
4217
|
this.db,
|
|
3947
4218
|
this.options,
|
|
@@ -4069,9 +4340,13 @@ var WikiMemory = class {
|
|
|
4069
4340
|
* host runs a plain `setup()` outside the lease.
|
|
4070
4341
|
*
|
|
4071
4342
|
* Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
|
|
4072
|
-
* left converges on later opens and no-arg `syncSearchIndex()` calls
|
|
4073
|
-
*
|
|
4074
|
-
*
|
|
4343
|
+
* left converges on later opens, and on no-arg `syncSearchIndex()` calls for
|
|
4344
|
+
* the entries ledger. Passage-ledger leftover converges on later opens and on
|
|
4345
|
+
* passage-store writes for the entity (`storeSource`, `forget`,
|
|
4346
|
+
* `importDump`), which drain that entity's rows; no-arg calls do not touch
|
|
4347
|
+
* the passage ledger. Not bounded: an index reset (tokenizer change, re-attach
|
|
4348
|
+
* after detach, a lost or inconsistent index), which runs as one unchunked
|
|
4349
|
+
* transaction.
|
|
4075
4350
|
*/
|
|
4076
4351
|
async setup(opts) {
|
|
4077
4352
|
const setupBudgetMs = this.setupBudgetMs();
|
|
@@ -4115,6 +4390,7 @@ var WikiMemory = class {
|
|
|
4115
4390
|
)
|
|
4116
4391
|
);
|
|
4117
4392
|
await this.searchService.sync(void 0, { deadline: openDeadline });
|
|
4393
|
+
await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
|
|
4118
4394
|
await this.startSetupRemovalDrain();
|
|
4119
4395
|
}
|
|
4120
4396
|
/** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
|
|
@@ -4537,6 +4813,7 @@ var WikiMemory = class {
|
|
|
4537
4813
|
);
|
|
4538
4814
|
this.searchService.setIndexStrategy(strategy);
|
|
4539
4815
|
if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();
|
|
4816
|
+
if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);
|
|
4540
4817
|
} finally {
|
|
4541
4818
|
if (this.searchService.isKeywordAvailable()) {
|
|
4542
4819
|
this.reinitFailures = 0;
|
|
@@ -4579,7 +4856,13 @@ var WikiMemory = class {
|
|
|
4579
4856
|
return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
|
|
4580
4857
|
}
|
|
4581
4858
|
async importDump(dump, opts) {
|
|
4582
|
-
|
|
4859
|
+
try {
|
|
4860
|
+
return await this.importExportService.importDump(dump, opts);
|
|
4861
|
+
} finally {
|
|
4862
|
+
for (const entityId of Object.keys(dump?.entities ?? {})) {
|
|
4863
|
+
await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
4864
|
+
}
|
|
4865
|
+
}
|
|
4583
4866
|
}
|
|
4584
4867
|
/**
|
|
4585
4868
|
* Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
|
|
@@ -4600,7 +4883,28 @@ var WikiMemory = class {
|
|
|
4600
4883
|
* or call `runExternalDeletions()`.
|
|
4601
4884
|
*/
|
|
4602
4885
|
async forget(entityId, params, opts) {
|
|
4603
|
-
|
|
4886
|
+
try {
|
|
4887
|
+
return await this.maintenanceService.forget(entityId, params, opts);
|
|
4888
|
+
} finally {
|
|
4889
|
+
if (!opts?.dryRun) {
|
|
4890
|
+
await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
4891
|
+
}
|
|
4892
|
+
}
|
|
4893
|
+
}
|
|
4894
|
+
/** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */
|
|
4895
|
+
async storeSource(entityId, params) {
|
|
4896
|
+
assertEntityId2(entityId);
|
|
4897
|
+
const result = await this.sourceStoreService.storeSource(entityId, params);
|
|
4898
|
+
if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);
|
|
4899
|
+
return result;
|
|
4900
|
+
}
|
|
4901
|
+
async getStoredSource(entityId, sourceRef) {
|
|
4902
|
+
assertEntityId2(entityId);
|
|
4903
|
+
return this.sourceStoreService.getStoredSource(entityId, sourceRef);
|
|
4904
|
+
}
|
|
4905
|
+
async listStoredSources(entityId) {
|
|
4906
|
+
assertEntityId2(entityId);
|
|
4907
|
+
return this.sourceStoreService.listStoredSources(entityId);
|
|
4604
4908
|
}
|
|
4605
4909
|
/**
|
|
4606
4910
|
* End `oldId`'s validity and link it to its replacement (spec §4.3). One
|
|
@@ -4957,6 +5261,10 @@ function renderEventPlain(event) {
|
|
|
4957
5261
|
const ts = new Date(event.created_at).toISOString();
|
|
4958
5262
|
return `[${event.event_type} @ ${ts}] ${event.summary}`;
|
|
4959
5263
|
}
|
|
5264
|
+
function renderSourceLabel(p, includeEntityId) {
|
|
5265
|
+
const entity = includeEntityId ? `${p.entityId} ` : "";
|
|
5266
|
+
return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
|
|
5267
|
+
}
|
|
4960
5268
|
function formatContext(bundle, options) {
|
|
4961
5269
|
const opts = {
|
|
4962
5270
|
format: options?.format ?? "markdown",
|
|
@@ -4982,7 +5290,8 @@ function formatContext(bundle, options) {
|
|
|
4982
5290
|
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);
|
|
4983
5291
|
const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
|
|
4984
5292
|
const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
|
|
4985
|
-
|
|
5293
|
+
const sources = bundle.sources ?? [];
|
|
5294
|
+
if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
|
|
4986
5295
|
return "";
|
|
4987
5296
|
}
|
|
4988
5297
|
const isMarkdown = opts.format === "markdown";
|
|
@@ -5010,6 +5319,13 @@ function formatContext(bundle, options) {
|
|
|
5010
5319
|
lines.push(renderEventMarkdown(event));
|
|
5011
5320
|
}
|
|
5012
5321
|
}
|
|
5322
|
+
if (sources.length > 0) {
|
|
5323
|
+
lines.push("");
|
|
5324
|
+
lines.push("### Sources");
|
|
5325
|
+
for (const p of sources) {
|
|
5326
|
+
lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
|
|
5327
|
+
}
|
|
5328
|
+
}
|
|
5013
5329
|
} else {
|
|
5014
5330
|
if (sortedFacts.length > 0) {
|
|
5015
5331
|
lines.push("KNOWN FACTS:");
|
|
@@ -5029,6 +5345,12 @@ function formatContext(bundle, options) {
|
|
|
5029
5345
|
lines.push(renderEventPlain(event));
|
|
5030
5346
|
}
|
|
5031
5347
|
}
|
|
5348
|
+
if (sources.length > 0) {
|
|
5349
|
+
lines.push("SOURCES:");
|
|
5350
|
+
for (const p of sources) {
|
|
5351
|
+
lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
|
|
5352
|
+
}
|
|
5353
|
+
}
|
|
5032
5354
|
}
|
|
5033
5355
|
return lines.join("\n");
|
|
5034
5356
|
}
|
|
@@ -5225,6 +5547,15 @@ function isoDateOrOmit(ms) {
|
|
|
5225
5547
|
if (!Number.isFinite(d.getTime())) return void 0;
|
|
5226
5548
|
return d.toISOString().slice(0, 10);
|
|
5227
5549
|
}
|
|
5550
|
+
function sourcePointerFrontmatter(p) {
|
|
5551
|
+
if (!p) return void 0;
|
|
5552
|
+
return {
|
|
5553
|
+
...p.event_id != null ? { event_id: p.event_id } : {},
|
|
5554
|
+
...p.ref != null ? { ref: p.ref } : {},
|
|
5555
|
+
...p.quote != null ? { quote: p.quote } : {},
|
|
5556
|
+
...p.position != null ? { position: p.position } : {}
|
|
5557
|
+
};
|
|
5558
|
+
}
|
|
5228
5559
|
function factFrontmatterV2(f) {
|
|
5229
5560
|
return {
|
|
5230
5561
|
type: f.okf_type ?? "fact",
|
|
@@ -5263,7 +5594,9 @@ function factFrontmatterV2(f) {
|
|
|
5263
5594
|
...f.valid_from != null ? { valid_from: f.valid_from } : {},
|
|
5264
5595
|
...f.valid_to != null ? { valid_to: f.valid_to } : {},
|
|
5265
5596
|
...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
|
|
5266
|
-
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {}
|
|
5597
|
+
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
|
|
5598
|
+
// Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
|
|
5599
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
5267
5600
|
};
|
|
5268
5601
|
}
|
|
5269
5602
|
function taskFrontmatterV2(t) {
|
|
@@ -5307,7 +5640,9 @@ function factFrontmatterV1(f) {
|
|
|
5307
5640
|
created_at: f.created_at,
|
|
5308
5641
|
access_count: f.access_count,
|
|
5309
5642
|
last_accessed_at: f.last_accessed_at,
|
|
5310
|
-
deleted_at: f.deleted_at
|
|
5643
|
+
deleted_at: f.deleted_at,
|
|
5644
|
+
// Source pointer (specs/source-pointers): same map rule as the v2 path.
|
|
5645
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
5311
5646
|
};
|
|
5312
5647
|
}
|
|
5313
5648
|
function taskFrontmatterV1(t) {
|
|
@@ -5563,7 +5898,7 @@ function parseLogEntryText(text) {
|
|
|
5563
5898
|
}
|
|
5564
5899
|
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
5565
5900
|
}
|
|
5566
|
-
function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
5901
|
+
function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
|
|
5567
5902
|
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
5568
5903
|
const updated_at = parseFrontmatterTimestamp(
|
|
5569
5904
|
frontmatter.generated?.at,
|
|
@@ -5617,7 +5952,23 @@ function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
|
5617
5952
|
...optionalEpoch("valid_from", frontmatter.valid_from),
|
|
5618
5953
|
...optionalEpoch("valid_to", frontmatter.valid_to),
|
|
5619
5954
|
...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
|
|
5620
|
-
...optionalEpoch("superseded_at", frontmatter.superseded_at)
|
|
5955
|
+
...optionalEpoch("superseded_at", frontmatter.superseded_at),
|
|
5956
|
+
// Source pointer (specs/source-pointers §Export, import, and OKF): the
|
|
5957
|
+
// parse path has no diagnostic channel, so it reports through the result.
|
|
5958
|
+
// ABSENT key → the property is omitted (not null), so the import
|
|
5959
|
+
// presence guard survives the parse. Malformed → the property is omitted
|
|
5960
|
+
// AND the drop is reported as entry id + reason slug — never the raw
|
|
5961
|
+
// value, which can carry quote text.
|
|
5962
|
+
...(() => {
|
|
5963
|
+
const raw = frontmatter.source_pointer;
|
|
5964
|
+
if (raw === void 0) return {};
|
|
5965
|
+
const v = validateSourcePointerValue(raw);
|
|
5966
|
+
if (v === void 0) {
|
|
5967
|
+
droppedPointerValues.push({ factId: id, reason: "malformed" });
|
|
5968
|
+
return {};
|
|
5969
|
+
}
|
|
5970
|
+
return { source_pointer: v };
|
|
5971
|
+
})()
|
|
5621
5972
|
};
|
|
5622
5973
|
}
|
|
5623
5974
|
function optionalEpoch(key, v) {
|
|
@@ -5738,6 +6089,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5738
6089
|
}
|
|
5739
6090
|
const facts = [];
|
|
5740
6091
|
const tasks = [];
|
|
6092
|
+
const droppedPointerValues = [];
|
|
5741
6093
|
const edges = [];
|
|
5742
6094
|
let logContent = null;
|
|
5743
6095
|
const logMdPath = findLogMdPath(allowedFiles);
|
|
@@ -5755,7 +6107,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5755
6107
|
const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...extractMarkdownLinks(storedBody)];
|
|
5756
6108
|
const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
|
|
5757
6109
|
if (route === "fact") {
|
|
5758
|
-
facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));
|
|
6110
|
+
facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
|
|
5759
6111
|
} else {
|
|
5760
6112
|
tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
|
|
5761
6113
|
}
|
|
@@ -5822,7 +6174,8 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5822
6174
|
generatedAt: now,
|
|
5823
6175
|
entities: {
|
|
5824
6176
|
[entityId]: { facts, tasks, events, edges, summary: entitySummary }
|
|
5825
|
-
}
|
|
6177
|
+
},
|
|
6178
|
+
...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
|
|
5826
6179
|
};
|
|
5827
6180
|
}
|
|
5828
6181
|
|