@equationalapplications/core-llm-wiki 8.2.0 → 8.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{chunk-FOX6TNFO.mjs → chunk-EKYWAR2E.mjs} +1210 -136
- package/dist/chunk-EKYWAR2E.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1514 -319
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +331 -211
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-D6So3dKX.d.mts → testing-Og5x9rFu.d.mts} +385 -56
- package/dist/{testing-D6So3dKX.d.ts → testing-Og5x9rFu.d.ts} +385 -56
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +641 -120
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-FOX6TNFO.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { BaseRepository, WikiGraphNodeOwnershipConflict, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, MetadataRepository, EmbeddingService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, 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, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-
|
|
3
|
-
import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
|
|
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-EKYWAR2E.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-EKYWAR2E.mjs';
|
|
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
|
|
|
6
6
|
// src/db/migrationGate.ts
|
|
@@ -671,20 +671,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
671
671
|
* Used by runPrune(). Returns total number of deleted rows.
|
|
672
672
|
* `tx` is REQUIRED so outbox deletion events are staged atomically.
|
|
673
673
|
*/
|
|
674
|
-
async bulkDeletePruned(entityId, cutoff, ids, tx) {
|
|
674
|
+
async bulkDeletePruned(entityId, cutoff, ids, tx, opts = {}) {
|
|
675
675
|
const executor = this.getExecutor(tx);
|
|
676
|
+
const guard = opts.keepUnconfirmedRemovals ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)` : "";
|
|
676
677
|
let totalChanges = 0;
|
|
677
678
|
const chunkSize = 500;
|
|
678
679
|
for (let i = 0; i < ids.length; i += chunkSize) {
|
|
679
680
|
const chunk = ids.slice(i, i + chunkSize);
|
|
680
681
|
const placeholders = chunk.map(() => "?").join(",");
|
|
681
|
-
const
|
|
682
|
-
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,
|
|
682
|
+
const deleted = (await executor.getAllAsync(
|
|
683
|
+
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
|
|
683
684
|
[entityId, cutoff, ...chunk]
|
|
684
|
-
);
|
|
685
|
-
totalChanges +=
|
|
686
|
-
|
|
687
|
-
|
|
685
|
+
)).map((r) => r.id);
|
|
686
|
+
totalChanges += deleted.length;
|
|
687
|
+
opts.deletedIds?.push(...deleted);
|
|
688
|
+
if (deleted.length > 0) {
|
|
689
|
+
for (const id of deleted) {
|
|
688
690
|
await this.outbox.push({
|
|
689
691
|
entityId,
|
|
690
692
|
tableName: "entries",
|
|
@@ -791,11 +793,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
791
793
|
const executor = this.getExecutor(tx);
|
|
792
794
|
const now = Date.now();
|
|
793
795
|
const placeholders = ids.map(() => "?").join(",");
|
|
794
|
-
await executor.
|
|
795
|
-
`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id =
|
|
796
|
+
const updated = await executor.getAllAsync(
|
|
797
|
+
`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,
|
|
796
798
|
[now, now, ...ids, entityId]
|
|
797
799
|
);
|
|
798
|
-
for (const id of
|
|
800
|
+
for (const { id } of updated) {
|
|
799
801
|
await this.outbox.push({
|
|
800
802
|
entityId,
|
|
801
803
|
tableName: "entries",
|
|
@@ -955,18 +957,20 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
955
957
|
}
|
|
956
958
|
return rows;
|
|
957
959
|
}
|
|
960
|
+
/** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */
|
|
958
961
|
async updateEmbeddingBlob(id, blob, tx) {
|
|
959
962
|
const executor = this.getExecutor(tx);
|
|
960
|
-
await executor.runAsync(
|
|
963
|
+
const r = await executor.runAsync(
|
|
961
964
|
`UPDATE ${this.prefix}entries
|
|
962
965
|
SET embedding_blob = ?,
|
|
963
966
|
embedding = NULL,
|
|
964
967
|
embedding_failed_at = NULL,
|
|
965
968
|
embedding_failure_kind = NULL,
|
|
966
969
|
embedding_attempts = 0
|
|
967
|
-
WHERE id =
|
|
970
|
+
WHERE id = ? AND deleted_at IS NULL`,
|
|
968
971
|
[blob, id]
|
|
969
972
|
);
|
|
973
|
+
return { changes: r?.changes ?? 0 };
|
|
970
974
|
}
|
|
971
975
|
/**
|
|
972
976
|
* Record a failed embedding attempt. Deliberately does NOT touch updated_at
|
|
@@ -1573,6 +1577,19 @@ var SourceRefIndexRepository = class extends BaseRepository {
|
|
|
1573
1577
|
[generateId("sri_"), entityId, sourceHash, sourceRef, Date.now()]
|
|
1574
1578
|
);
|
|
1575
1579
|
}
|
|
1580
|
+
/**
|
|
1581
|
+
* Hard-delete every row of the entity, live or soft-deleted (forget clearAll,
|
|
1582
|
+
* spec import-followups §6 rev 4). Nothing reads a soft-deleted row and
|
|
1583
|
+
* runPrune never sweeps this table, so a wipe leaves no tombstones.
|
|
1584
|
+
*/
|
|
1585
|
+
async deleteByEntityId(entityId, tx) {
|
|
1586
|
+
const executor = this.getExecutor(tx);
|
|
1587
|
+
const result = await executor.runAsync(
|
|
1588
|
+
`DELETE FROM ${this.prefix}source_ref_index WHERE entity_id = ?`,
|
|
1589
|
+
[entityId]
|
|
1590
|
+
);
|
|
1591
|
+
return result.changes;
|
|
1592
|
+
}
|
|
1576
1593
|
/**
|
|
1577
1594
|
* Idempotent soft-delete of the live row for (entity_id, source_ref).
|
|
1578
1595
|
* Called at the start of every ingestDocument to remove the prior run's
|
|
@@ -2015,6 +2032,10 @@ var EventRepository = class extends BaseRepository {
|
|
|
2015
2032
|
);
|
|
2016
2033
|
return rows.map(mapEvent);
|
|
2017
2034
|
}
|
|
2035
|
+
/** Hard-delete every event of the entity, read or not (requested wipe, spec import-followups §6). */
|
|
2036
|
+
async deleteByEntityId(entityId, tx) {
|
|
2037
|
+
return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]);
|
|
2038
|
+
}
|
|
2018
2039
|
/**
|
|
2019
2040
|
* Delete events for an entity that were created at or before the given cutoff timestamp.
|
|
2020
2041
|
* Returns the number of deleted rows.
|
|
@@ -2160,183 +2181,6 @@ var EventRepository = class extends BaseRepository {
|
|
|
2160
2181
|
return row?.total ?? 0;
|
|
2161
2182
|
}
|
|
2162
2183
|
};
|
|
2163
|
-
|
|
2164
|
-
// src/repositories/EdgeRepository.ts
|
|
2165
|
-
var CONFIDENCE_RANK = {
|
|
2166
|
-
tentative: 0,
|
|
2167
|
-
inferred: 1,
|
|
2168
|
-
certain: 2
|
|
2169
|
-
};
|
|
2170
|
-
var EdgeRepository = class extends BaseRepository {
|
|
2171
|
-
/**
|
|
2172
|
-
* Insert an edge, silently skipping on primary-key or uniqueness conflicts.
|
|
2173
|
-
* Returns true when a row was inserted, false when skipped as a duplicate.
|
|
2174
|
-
* Throws when the insert was skipped due to an id collision with a different edge tuple.
|
|
2175
|
-
*/
|
|
2176
|
-
async addIgnoreDuplicate(edge, tx) {
|
|
2177
|
-
const executor = this.getExecutor(tx);
|
|
2178
|
-
const result = await executor.runAsync(
|
|
2179
|
-
`INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)
|
|
2180
|
-
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
2181
|
-
[edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at]
|
|
2182
|
-
);
|
|
2183
|
-
if (result.changes > 0) return true;
|
|
2184
|
-
const existing = await executor.getFirstAsync(
|
|
2185
|
-
`SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,
|
|
2186
|
-
[edge.id]
|
|
2187
|
-
);
|
|
2188
|
-
if (!existing) return false;
|
|
2189
|
-
if (String(existing.entity_id) !== edge.entity_id || String(existing.source_id) !== edge.source_id || String(existing.target_id) !== edge.target_id || String(existing.edge_type) !== edge.edge_type) {
|
|
2190
|
-
throw new Error(
|
|
2191
|
-
`Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`
|
|
2192
|
-
);
|
|
2193
|
-
}
|
|
2194
|
-
return false;
|
|
2195
|
-
}
|
|
2196
|
-
async getByEntityId(entityId, tx) {
|
|
2197
|
-
const executor = this.getExecutor(tx);
|
|
2198
|
-
const rows = await executor.getAllAsync(
|
|
2199
|
-
`SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,
|
|
2200
|
-
[entityId]
|
|
2201
|
-
);
|
|
2202
|
-
return rows.map(mapRowToEdge);
|
|
2203
|
-
}
|
|
2204
|
-
/** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
|
|
2205
|
-
async bulkDeleteByEntityId(entityId, tx) {
|
|
2206
|
-
const executor = this.getExecutor(tx);
|
|
2207
|
-
await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
|
|
2208
|
-
}
|
|
2209
|
-
/**
|
|
2210
|
-
* Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
|
|
2211
|
-
* `entityId`. Returns the number of rows deleted. Edges have no soft-delete
|
|
2212
|
-
* concept; this method is named `softDeleteBySourceFactIds` for symmetry with
|
|
2213
|
-
* `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
|
|
2214
|
-
* semantics are immediate presence/absence removal. Use ONLY inside an open
|
|
2215
|
-
* transaction — the method requires `tx` and performs no autocommit.
|
|
2216
|
-
*
|
|
2217
|
-
* Used by `IngestionService.upsertGraphCore` to retire the prior parse's
|
|
2218
|
-
* edges whose source facts are being superseded by `softDeleteBySource`.
|
|
2219
|
-
*/
|
|
2220
|
-
async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
|
|
2221
|
-
if (sourceFactIds.length === 0) return 0;
|
|
2222
|
-
const executor = this.getExecutor(tx);
|
|
2223
|
-
const chunkSize = 500;
|
|
2224
|
-
let totalChanges = 0;
|
|
2225
|
-
for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
|
|
2226
|
-
const chunk = sourceFactIds.slice(i, i + chunkSize);
|
|
2227
|
-
const placeholders = chunk.map(() => "?").join(",");
|
|
2228
|
-
const result = await executor.runAsync(
|
|
2229
|
-
`DELETE FROM ${this.prefix}edges
|
|
2230
|
-
WHERE entity_id = ? AND source_id IN (${placeholders})`,
|
|
2231
|
-
[entityId, ...chunk]
|
|
2232
|
-
);
|
|
2233
|
-
totalChanges += result.changes;
|
|
2234
|
-
}
|
|
2235
|
-
return totalChanges;
|
|
2236
|
-
}
|
|
2237
|
-
/**
|
|
2238
|
-
* Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
|
|
2239
|
-
* dead-ending, cycle-guarding, capping, and ordering happens in this one query.
|
|
2240
|
-
* The anchor is validated (exists, right entity, not soft-deleted) but never gated
|
|
2241
|
-
* by confidence/source_type — only nodes discovered beyond it are.
|
|
2242
|
-
*/
|
|
2243
|
-
async getNeighborhood(entityId, sourceId, opts, tx) {
|
|
2244
|
-
const executor = this.getExecutor(tx);
|
|
2245
|
-
if (opts.edgeTypes && opts.edgeTypes.length === 0) {
|
|
2246
|
-
const anchor = await executor.getFirstAsync(
|
|
2247
|
-
`SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
|
|
2248
|
-
[sourceId, entityId]
|
|
2249
|
-
);
|
|
2250
|
-
return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
|
|
2251
|
-
}
|
|
2252
|
-
const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
|
|
2253
|
-
const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
|
|
2254
|
-
const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
|
|
2255
|
-
const sql = `
|
|
2256
|
-
WITH RECURSIVE walk(node_id, depth, visited) AS (
|
|
2257
|
-
SELECT id, 0, ',' || id || ','
|
|
2258
|
-
FROM ${this.prefix}entries
|
|
2259
|
-
WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
|
|
2260
|
-
|
|
2261
|
-
UNION
|
|
2262
|
-
|
|
2263
|
-
SELECT
|
|
2264
|
-
CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
|
|
2265
|
-
w.depth + 1,
|
|
2266
|
-
w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
|
|
2267
|
-
FROM walk w
|
|
2268
|
-
JOIN ${this.prefix}edges e
|
|
2269
|
-
ON e.entity_id = ?
|
|
2270
|
-
AND (
|
|
2271
|
-
(? != 'inbound' AND e.source_id = w.node_id) OR
|
|
2272
|
-
(? != 'outbound' AND e.target_id = w.node_id)
|
|
2273
|
-
)
|
|
2274
|
-
AND (${edgeTypesClause})
|
|
2275
|
-
JOIN ${this.prefix}entries n
|
|
2276
|
-
ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
|
|
2277
|
-
AND n.entity_id = ?
|
|
2278
|
-
AND n.deleted_at IS NULL
|
|
2279
|
-
AND (
|
|
2280
|
-
CASE n.confidence
|
|
2281
|
-
WHEN 'tentative' THEN 0
|
|
2282
|
-
WHEN 'inferred' THEN 1
|
|
2283
|
-
WHEN 'certain' THEN 2
|
|
2284
|
-
ELSE -1
|
|
2285
|
-
END
|
|
2286
|
-
) >= ?
|
|
2287
|
-
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
2288
|
-
AND (? = 0 OR n.lifecycle_status != 'draft')
|
|
2289
|
-
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
2290
|
-
WHERE w.depth < ?
|
|
2291
|
-
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
2292
|
-
)
|
|
2293
|
-
SELECT node_id, MIN(depth) AS depth
|
|
2294
|
-
FROM walk
|
|
2295
|
-
GROUP BY node_id
|
|
2296
|
-
ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
|
|
2297
|
-
LIMIT ?
|
|
2298
|
-
`;
|
|
2299
|
-
const params = [
|
|
2300
|
-
sourceId,
|
|
2301
|
-
entityId,
|
|
2302
|
-
entityId,
|
|
2303
|
-
opts.direction,
|
|
2304
|
-
opts.direction,
|
|
2305
|
-
...opts.edgeTypes ?? [],
|
|
2306
|
-
entityId,
|
|
2307
|
-
minConfidenceRank,
|
|
2308
|
-
...opts.excludeSourceTypes,
|
|
2309
|
-
opts.excludeDrafts === true ? 1 : 0,
|
|
2310
|
-
opts.live.t,
|
|
2311
|
-
opts.live.t,
|
|
2312
|
-
opts.maxDepth,
|
|
2313
|
-
opts.maxNodes
|
|
2314
|
-
];
|
|
2315
|
-
const rows = await executor.getAllAsync(sql, params);
|
|
2316
|
-
const nodeIds = rows.map((r) => r.node_id);
|
|
2317
|
-
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
2318
|
-
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
2319
|
-
const edgeRows = await executor.getAllAsync(
|
|
2320
|
-
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
2321
|
-
SELECT e.* FROM ${this.prefix}edges e
|
|
2322
|
-
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
2323
|
-
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
2324
|
-
WHERE e.entity_id = ?`,
|
|
2325
|
-
[...nodeIds, entityId]
|
|
2326
|
-
);
|
|
2327
|
-
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
2328
|
-
}
|
|
2329
|
-
};
|
|
2330
|
-
function mapRowToEdge(row) {
|
|
2331
|
-
return {
|
|
2332
|
-
id: String(row.id),
|
|
2333
|
-
entity_id: String(row.entity_id),
|
|
2334
|
-
source_id: String(row.source_id),
|
|
2335
|
-
target_id: String(row.target_id),
|
|
2336
|
-
edge_type: String(row.edge_type),
|
|
2337
|
-
created_at: Number(row.created_at)
|
|
2338
|
-
};
|
|
2339
|
-
}
|
|
2340
2184
|
var MiniSearchIndexStrategy = class {
|
|
2341
2185
|
constructor() {
|
|
2342
2186
|
/**
|
|
@@ -3121,7 +2965,7 @@ async function createIndexStrategy(db, prefix, metadataRepo, preferred, opts = {
|
|
|
3121
2965
|
|
|
3122
2966
|
// src/services/MaintenanceScheduler.ts
|
|
3123
2967
|
var MaintenanceScheduler = class {
|
|
3124
|
-
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
|
|
2968
|
+
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
|
|
3125
2969
|
this.db = db;
|
|
3126
2970
|
this.options = options;
|
|
3127
2971
|
this.maintenanceService = maintenanceService;
|
|
@@ -3129,6 +2973,8 @@ var MaintenanceScheduler = class {
|
|
|
3129
2973
|
this.eventRepo = eventRepo;
|
|
3130
2974
|
this.entryRepo = entryRepo;
|
|
3131
2975
|
this.jobManager = jobManager;
|
|
2976
|
+
this.vectorRemovalService = vectorRemovalService;
|
|
2977
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
3132
2978
|
}
|
|
3133
2979
|
/**
|
|
3134
2980
|
* Entities with **any** pending work only, sorted by `pendingEvents` desc
|
|
@@ -3140,7 +2986,17 @@ var MaintenanceScheduler = class {
|
|
|
3140
2986
|
const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
|
|
3141
2987
|
const canEmbed = typeof this.options.llmProvider.embed === "function";
|
|
3142
2988
|
const out = [];
|
|
3143
|
-
|
|
2989
|
+
const owed = /* @__PURE__ */ new Map();
|
|
2990
|
+
if (this.vectorRemovalService.gate() !== "none" && await this.vectorRemovalService.ledgerPresent()) {
|
|
2991
|
+
const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
|
|
2992
|
+
for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {
|
|
2993
|
+
if (scope !== void 0 && !scope.has(e)) continue;
|
|
2994
|
+
owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
const listed = new Set(ids);
|
|
2998
|
+
const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];
|
|
2999
|
+
for (const entityId of scan) {
|
|
3144
3000
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
3145
3001
|
const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
|
|
3146
3002
|
const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
|
|
@@ -3150,8 +3006,16 @@ var MaintenanceScheduler = class {
|
|
|
3150
3006
|
if (healCheckpoint > eventCount) healCheckpoint = 0;
|
|
3151
3007
|
const healDue = eventCount - healCheckpoint >= autoHealThreshold;
|
|
3152
3008
|
const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
|
|
3153
|
-
|
|
3154
|
-
|
|
3009
|
+
const owedCount = owed.get(entityId) ?? 0;
|
|
3010
|
+
if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
|
|
3011
|
+
out.push({
|
|
3012
|
+
entityId,
|
|
3013
|
+
pendingEvents,
|
|
3014
|
+
pendingTokensEstimate: Math.ceil(chars / 4),
|
|
3015
|
+
healDue,
|
|
3016
|
+
reembedPending,
|
|
3017
|
+
...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
|
|
3018
|
+
});
|
|
3155
3019
|
}
|
|
3156
3020
|
}
|
|
3157
3021
|
return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
|
|
@@ -3177,8 +3041,9 @@ var MaintenanceScheduler = class {
|
|
|
3177
3041
|
const meter = new UsageMeter(opts.tokenBudget);
|
|
3178
3042
|
const budget = opts.tokenBudget;
|
|
3179
3043
|
const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
|
|
3180
|
-
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
|
|
3181
|
-
const
|
|
3044
|
+
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
|
|
3045
|
+
const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
|
|
3046
|
+
const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
|
|
3182
3047
|
const states = pending.map((p) => ({
|
|
3183
3048
|
p,
|
|
3184
3049
|
report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
|
|
@@ -3310,9 +3175,43 @@ var MaintenanceScheduler = class {
|
|
|
3310
3175
|
tokensUsed: meter.used,
|
|
3311
3176
|
estimated: meter.estimated,
|
|
3312
3177
|
remaining: budget === void 0 ? null : meter.remaining,
|
|
3313
|
-
stoppedReason: stopped
|
|
3178
|
+
stoppedReason: stopped,
|
|
3179
|
+
externalDeletions
|
|
3314
3180
|
};
|
|
3315
3181
|
}
|
|
3182
|
+
/**
|
|
3183
|
+
* Runs first and outside the token budget: delivers owed vector-index
|
|
3184
|
+
* removals per entity (wiped entities included), without backoff. Pending is
|
|
3185
|
+
* reported even when the job is not listed or no hook is configured.
|
|
3186
|
+
*/
|
|
3187
|
+
async runExternalDeletions(entityIds, enabled, deadline) {
|
|
3188
|
+
if (!await this.vectorRemovalService.ledgerPresent()) return { confirmed: 0, pending: 0 };
|
|
3189
|
+
const all = await this.vectorRemovalRepo.entitiesWithPending();
|
|
3190
|
+
const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
|
|
3191
|
+
const entities = scope === void 0 ? all : all.filter((e) => scope.has(e));
|
|
3192
|
+
let confirmed = 0;
|
|
3193
|
+
let pending = 0;
|
|
3194
|
+
const counted = /* @__PURE__ */ new Set();
|
|
3195
|
+
if (enabled) {
|
|
3196
|
+
for (const e of entities) {
|
|
3197
|
+
if (Date.now() >= deadline) break;
|
|
3198
|
+
const r = await this.vectorRemovalService.drain(
|
|
3199
|
+
{ entityId: e },
|
|
3200
|
+
{ trigger: "call", ...deadline === Infinity ? {} : { deadlineAt: deadline } }
|
|
3201
|
+
);
|
|
3202
|
+
confirmed += r.confirmed;
|
|
3203
|
+
if (!r.transient) {
|
|
3204
|
+
pending += r.pending;
|
|
3205
|
+
counted.add(e);
|
|
3206
|
+
}
|
|
3207
|
+
if (r.timedOut) break;
|
|
3208
|
+
}
|
|
3209
|
+
}
|
|
3210
|
+
for (const e of entities) {
|
|
3211
|
+
if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;
|
|
3212
|
+
}
|
|
3213
|
+
return { confirmed, pending };
|
|
3214
|
+
}
|
|
3316
3215
|
};
|
|
3317
3216
|
|
|
3318
3217
|
// src/prompts/ontology.ts
|
|
@@ -3934,11 +3833,15 @@ var WikiMemory = class {
|
|
|
3934
3833
|
this.upsertIdStashSize = 0;
|
|
3935
3834
|
/** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
|
|
3936
3835
|
this.upsertIdStashGen = 0;
|
|
3836
|
+
/** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */
|
|
3837
|
+
this.removalStash = /* @__PURE__ */ new Map();
|
|
3838
|
+
this.removalStashSize = 0;
|
|
3937
3839
|
this.reinitSearch = null;
|
|
3938
3840
|
/** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
|
|
3939
3841
|
this.reinitRetryAt = 0;
|
|
3940
3842
|
/** Consecutive failed re-inits; drives the exponential backoff. */
|
|
3941
3843
|
this.reinitFailures = 0;
|
|
3844
|
+
this.setupRemovalDrain = null;
|
|
3942
3845
|
this.db = withSerializedTransactions(db);
|
|
3943
3846
|
this.options = options;
|
|
3944
3847
|
warnChangedDefaultsOnce(options.config);
|
|
@@ -3963,6 +3866,9 @@ var WikiMemory = class {
|
|
|
3963
3866
|
);
|
|
3964
3867
|
this.lintService = new LintService(this.lintRepo, this.ontologyService);
|
|
3965
3868
|
this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);
|
|
3869
|
+
this.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);
|
|
3870
|
+
this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);
|
|
3871
|
+
this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);
|
|
3966
3872
|
this.searchService = new SearchService(
|
|
3967
3873
|
this.entryRepo,
|
|
3968
3874
|
new MiniSearchIndexStrategy()
|
|
@@ -3983,7 +3889,8 @@ var WikiMemory = class {
|
|
|
3983
3889
|
this.jobManager,
|
|
3984
3890
|
this.embeddingService,
|
|
3985
3891
|
this.promptService,
|
|
3986
|
-
this.ontologyService
|
|
3892
|
+
this.ontologyService,
|
|
3893
|
+
this.vectorRemovalService
|
|
3987
3894
|
);
|
|
3988
3895
|
this.maintenanceService = new MaintenanceService(
|
|
3989
3896
|
this.db,
|
|
@@ -3998,7 +3905,10 @@ var WikiMemory = class {
|
|
|
3998
3905
|
this.jobManager,
|
|
3999
3906
|
this.embeddingService,
|
|
4000
3907
|
this.promptService,
|
|
4001
|
-
this.ontologyService
|
|
3908
|
+
this.ontologyService,
|
|
3909
|
+
this.edgeRepo,
|
|
3910
|
+
this.vectorRemovalService,
|
|
3911
|
+
this.vectorRemovalRepo
|
|
4002
3912
|
);
|
|
4003
3913
|
this.maintenanceScheduler = new MaintenanceScheduler(
|
|
4004
3914
|
this.db,
|
|
@@ -4007,7 +3917,9 @@ var WikiMemory = class {
|
|
|
4007
3917
|
this.metadataRepo,
|
|
4008
3918
|
this.eventRepo,
|
|
4009
3919
|
this.entryRepo,
|
|
4010
|
-
this.jobManager
|
|
3920
|
+
this.jobManager,
|
|
3921
|
+
this.vectorRemovalService,
|
|
3922
|
+
this.vectorRemovalRepo
|
|
4011
3923
|
);
|
|
4012
3924
|
this.importExportService = new ImportExportService(
|
|
4013
3925
|
this.db,
|
|
@@ -4019,7 +3931,8 @@ var WikiMemory = class {
|
|
|
4019
3931
|
this.searchService,
|
|
4020
3932
|
this.jobManager,
|
|
4021
3933
|
this.embeddingService,
|
|
4022
|
-
this.options
|
|
3934
|
+
this.options,
|
|
3935
|
+
this.vectorRemovalService
|
|
4023
3936
|
);
|
|
4024
3937
|
this.retrievalService = new RetrievalService(
|
|
4025
3938
|
this.options,
|
|
@@ -4087,6 +4000,33 @@ var WikiMemory = class {
|
|
|
4087
4000
|
}
|
|
4088
4001
|
if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
|
|
4089
4002
|
}
|
|
4003
|
+
/**
|
|
4004
|
+
* Overflow past the cap drops the id from the stash only: the trigger already
|
|
4005
|
+
* put it on the ledger, so it stays owed and runExternalDeletions or
|
|
4006
|
+
* runPendingMaintenance delivers it later.
|
|
4007
|
+
*/
|
|
4008
|
+
stashRemovalIds(entityId, ids) {
|
|
4009
|
+
const cap = this.constructor.REMOVAL_STASH_CAP;
|
|
4010
|
+
const stash = this.removalStash.get(entityId) ?? /* @__PURE__ */ new Set();
|
|
4011
|
+
for (const id of ids) {
|
|
4012
|
+
if (stash.has(id)) continue;
|
|
4013
|
+
if (this.removalStashSize >= cap) continue;
|
|
4014
|
+
stash.add(id);
|
|
4015
|
+
this.removalStashSize++;
|
|
4016
|
+
}
|
|
4017
|
+
if (stash.size > 0) this.removalStash.set(entityId, stash);
|
|
4018
|
+
}
|
|
4019
|
+
/** Removes and returns the stashed removal ids (one entity, or all). */
|
|
4020
|
+
takeRemovalIds(entityId) {
|
|
4021
|
+
const out = /* @__PURE__ */ new Map();
|
|
4022
|
+
for (const [e, set] of [...this.removalStash]) {
|
|
4023
|
+
if (entityId !== void 0 && e !== entityId) continue;
|
|
4024
|
+
out.set(e, [...set]);
|
|
4025
|
+
this.removalStashSize -= set.size;
|
|
4026
|
+
this.removalStash.delete(e);
|
|
4027
|
+
}
|
|
4028
|
+
return out;
|
|
4029
|
+
}
|
|
4090
4030
|
/** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
|
|
4091
4031
|
peekStashedIds(entityId) {
|
|
4092
4032
|
const snapshot = /* @__PURE__ */ new Map();
|
|
@@ -4175,6 +4115,84 @@ var WikiMemory = class {
|
|
|
4175
4115
|
)
|
|
4176
4116
|
);
|
|
4177
4117
|
await this.searchService.sync(void 0, { deadline: openDeadline });
|
|
4118
|
+
await this.startSetupRemovalDrain();
|
|
4119
|
+
}
|
|
4120
|
+
/** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
|
|
4121
|
+
async startSetupRemovalDrain() {
|
|
4122
|
+
if (this.setupRemovalDrain) return;
|
|
4123
|
+
const gate = this.vectorRemovalService.gate();
|
|
4124
|
+
if (gate === "none") return;
|
|
4125
|
+
const prelude = (async () => {
|
|
4126
|
+
if (gate === "hook" && !await this.vectorRemovalService.externalIndexInUse()) {
|
|
4127
|
+
await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));
|
|
4128
|
+
}
|
|
4129
|
+
if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {
|
|
4130
|
+
if (gate === "force") await this.vectorRemovalService.clearExternalIndexMarker();
|
|
4131
|
+
return { drain: null };
|
|
4132
|
+
}
|
|
4133
|
+
if (this.options.drainExternalDeletionsOnSetup !== true) {
|
|
4134
|
+
if (gate === "hook") await this.vectorRemovalService.emitPending(void 0, "auto");
|
|
4135
|
+
return { drain: null };
|
|
4136
|
+
}
|
|
4137
|
+
const drain = (async () => {
|
|
4138
|
+
try {
|
|
4139
|
+
const r = await this.vectorRemovalService.drain(
|
|
4140
|
+
{ all: true },
|
|
4141
|
+
{ backoff: true, deadlineAt: Date.now() + 1e4, trigger: "auto" }
|
|
4142
|
+
);
|
|
4143
|
+
if (r.pending > 0) await this.vectorRemovalService.emitPending(void 0, "auto");
|
|
4144
|
+
} catch {
|
|
4145
|
+
emitDiagnostic(this.options, {
|
|
4146
|
+
code: "background_job_failed",
|
|
4147
|
+
operation: "externalDeletion",
|
|
4148
|
+
trigger: "auto",
|
|
4149
|
+
entityId: "",
|
|
4150
|
+
// store-wide drain
|
|
4151
|
+
detail: { reason: "unhandled_rejection" }
|
|
4152
|
+
});
|
|
4153
|
+
}
|
|
4154
|
+
})();
|
|
4155
|
+
return { drain };
|
|
4156
|
+
})();
|
|
4157
|
+
const joined = prelude.then((r) => r.drain ?? void 0, () => void 0);
|
|
4158
|
+
this.setupRemovalDrain = joined;
|
|
4159
|
+
void joined.then(() => {
|
|
4160
|
+
if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null;
|
|
4161
|
+
});
|
|
4162
|
+
await prelude;
|
|
4163
|
+
}
|
|
4164
|
+
/**
|
|
4165
|
+
* Delivers owed vector-index removals now (spec §5.9). No backoff. With an
|
|
4166
|
+
* entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.
|
|
4167
|
+
* `transient: true` means a ledger read or write could not run (for example,
|
|
4168
|
+
* you held a transaction open on the connection); the rows stay pending.
|
|
4169
|
+
*/
|
|
4170
|
+
async runExternalDeletions(entityId, opts) {
|
|
4171
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
4172
|
+
const ms = opts?.deadlineMs;
|
|
4173
|
+
if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
|
|
4174
|
+
throw new TypeError("deadlineMs must be a finite number >= 0");
|
|
4175
|
+
}
|
|
4176
|
+
if (!await this.vectorRemovalService.ledgerPresent()) {
|
|
4177
|
+
return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
|
|
4178
|
+
}
|
|
4179
|
+
const r = await this.vectorRemovalService.drain(
|
|
4180
|
+
entityId === void 0 ? { all: true } : { entityId },
|
|
4181
|
+
{ trigger: "call", ...ms !== void 0 ? { deadlineAt: Date.now() + ms } : {} }
|
|
4182
|
+
);
|
|
4183
|
+
return {
|
|
4184
|
+
confirmed: r.confirmed,
|
|
4185
|
+
pending: r.pending,
|
|
4186
|
+
failedIds: r.failedIds,
|
|
4187
|
+
timedOut: r.timedOut,
|
|
4188
|
+
...r.transient ? { transient: true } : {}
|
|
4189
|
+
};
|
|
4190
|
+
}
|
|
4191
|
+
/** Removals still owed to the host's vector index (all entities, or one). */
|
|
4192
|
+
async getPendingExternalDeletions(entityId) {
|
|
4193
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
4194
|
+
if (!await this.vectorRemovalService.ledgerPresent()) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };
|
|
4195
|
+
return this.vectorRemovalRepo.pendingStats(entityId);
|
|
4178
4196
|
}
|
|
4179
4197
|
async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
|
|
4180
4198
|
if (typeof sourceRefOrEntries === "string") {
|
|
@@ -4342,8 +4360,9 @@ var WikiMemory = class {
|
|
|
4342
4360
|
async write(entityId, event) {
|
|
4343
4361
|
return this.writeService.write(entityId, event);
|
|
4344
4362
|
}
|
|
4345
|
-
/** Await auto-mode background librarian/heal jobs started by write()
|
|
4363
|
+
/** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */
|
|
4346
4364
|
async drain() {
|
|
4365
|
+
await this.setupRemovalDrain;
|
|
4347
4366
|
return this.writeService.drain();
|
|
4348
4367
|
}
|
|
4349
4368
|
/**
|
|
@@ -4355,9 +4374,32 @@ var WikiMemory = class {
|
|
|
4355
4374
|
async getPendingMaintenance(entityIds) {
|
|
4356
4375
|
return this.maintenanceScheduler.getPending(entityIds);
|
|
4357
4376
|
}
|
|
4358
|
-
/** Run pending librarian
|
|
4377
|
+
/** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */
|
|
4359
4378
|
async runPendingMaintenance(options) {
|
|
4360
|
-
|
|
4379
|
+
let opts = options;
|
|
4380
|
+
const ms = options?.deadlineMs;
|
|
4381
|
+
if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
|
|
4382
|
+
throw new TypeError("deadlineMs must be a finite number >= 0");
|
|
4383
|
+
}
|
|
4384
|
+
const setupDrain = this.setupRemovalDrain;
|
|
4385
|
+
if (setupDrain) {
|
|
4386
|
+
if (ms !== void 0) {
|
|
4387
|
+
const started = Date.now();
|
|
4388
|
+
let handle;
|
|
4389
|
+
await Promise.race([
|
|
4390
|
+
setupDrain,
|
|
4391
|
+
new Promise((resolve) => {
|
|
4392
|
+
handle = setTimeout(resolve, ms);
|
|
4393
|
+
})
|
|
4394
|
+
]).finally(() => {
|
|
4395
|
+
if (handle) clearTimeout(handle);
|
|
4396
|
+
});
|
|
4397
|
+
opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };
|
|
4398
|
+
} else {
|
|
4399
|
+
await setupDrain;
|
|
4400
|
+
}
|
|
4401
|
+
}
|
|
4402
|
+
return this.maintenanceScheduler.run(opts);
|
|
4361
4403
|
}
|
|
4362
4404
|
/**
|
|
4363
4405
|
* @param options.promptOverride - Applies only to this manual call. Does NOT affect
|
|
@@ -4438,6 +4480,11 @@ var WikiMemory = class {
|
|
|
4438
4480
|
* waits at least 5 s, doubling per consecutive failure up to 5 min (longer
|
|
4439
4481
|
* when an attempt is itself slow), before retrying again.
|
|
4440
4482
|
*
|
|
4483
|
+
* It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for
|
|
4484
|
+
* the stashed ids that `upsertGraph` superseded, and can take up to
|
|
4485
|
+
* `deletionHookTimeoutMs` per id when the host's index is slow. It never
|
|
4486
|
+
* drains an entity's wider removal backlog.
|
|
4487
|
+
*
|
|
4441
4488
|
* Call only after the host's transaction commits: called inside it, the
|
|
4442
4489
|
* rebuild may index rows that later roll back, or miss them and clear the
|
|
4443
4490
|
* stale flag anyway. Serialized with core's internal index syncs and takes
|
|
@@ -4453,6 +4500,19 @@ var WikiMemory = class {
|
|
|
4453
4500
|
* @throws {TypeError} when `entityId` is given but is not a non-empty string.
|
|
4454
4501
|
*/
|
|
4455
4502
|
async syncSearchIndex(entityId) {
|
|
4503
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
4504
|
+
const removals = this.takeRemovalIds(entityId);
|
|
4505
|
+
try {
|
|
4506
|
+
await this.syncSearchIndexCore(entityId);
|
|
4507
|
+
} catch (err) {
|
|
4508
|
+
for (const [e, ids] of removals) this.stashRemovalIds(e, ids);
|
|
4509
|
+
throw err;
|
|
4510
|
+
}
|
|
4511
|
+
for (const [e, ids] of removals) {
|
|
4512
|
+
await this.vectorRemovalService.deliverRemovals(e, ids, "upsertGraph", "call");
|
|
4513
|
+
}
|
|
4514
|
+
}
|
|
4515
|
+
async syncSearchIndexCore(entityId) {
|
|
4456
4516
|
if (entityId === void 0) {
|
|
4457
4517
|
if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
|
|
4458
4518
|
this.reinitSearch ?? (this.reinitSearch = (async () => {
|
|
@@ -4511,6 +4571,24 @@ var WikiMemory = class {
|
|
|
4511
4571
|
async importDump(dump, opts) {
|
|
4512
4572
|
return this.importExportService.importDump(dump, opts);
|
|
4513
4573
|
}
|
|
4574
|
+
/**
|
|
4575
|
+
* Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
|
|
4576
|
+
* `clearAll` also deletes the entity's edges and its source-ref index rows.
|
|
4577
|
+
* Add `includeEvents: true` to `clearAll` to hard-delete every event too,
|
|
4578
|
+
* read or not, and reset the librarian's position: without it a later
|
|
4579
|
+
* maintenance run can read the events into facts again. `runPrune()` then
|
|
4580
|
+
* hard-deletes the soft-deleted rows once they are older than
|
|
4581
|
+
* `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
|
|
4582
|
+
* `dryRun` previews the counts.
|
|
4583
|
+
*
|
|
4584
|
+
* With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted
|
|
4585
|
+
* facts are recorded as owed in the same transaction and then delivered to
|
|
4586
|
+
* the hook before this resolves.
|
|
4587
|
+
*
|
|
4588
|
+
* @throws {WikiExternalDeletionError} when the hook didn't confirm every
|
|
4589
|
+
* removal. The local delete stays committed and the rest stay owed; retry,
|
|
4590
|
+
* or call `runExternalDeletions()`.
|
|
4591
|
+
*/
|
|
4514
4592
|
async forget(entityId, params, opts) {
|
|
4515
4593
|
return this.maintenanceService.forget(entityId, params, opts);
|
|
4516
4594
|
}
|
|
@@ -4562,12 +4640,15 @@ var WikiMemory = class {
|
|
|
4562
4640
|
* semantics identical to `ingestDocument`, minus the LLM extraction step.
|
|
4563
4641
|
*
|
|
4564
4642
|
* MUST be called from inside an open `db.withTransactionAsync` callback —
|
|
4565
|
-
* the third argument is the caller's `tx
|
|
4643
|
+
* the third argument is the caller's `tx`, and that transaction must be
|
|
4644
|
+
* opened through the adapter given to `createWiki` (the removal ledger is
|
|
4645
|
+
* filled by triggers inside it, and a rollback discards the rows). The method does not open a
|
|
4566
4646
|
* nested transaction, does not acquire any lock, and does not perform
|
|
4567
4647
|
* post-commit work (search sync, embedding, cache eviction). After the
|
|
4568
4648
|
* transaction commits, call `syncSearchIndex(entityId)` — or
|
|
4569
4649
|
* `syncSearchIndex()` after writing several entities in one transaction —
|
|
4570
|
-
* to make the new nodes keyword-searchable
|
|
4650
|
+
* to make the new nodes keyword-searchable and to deliver, through the
|
|
4651
|
+
* host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids
|
|
4571
4652
|
* first, to completion, so the nodes are searchable under any backlog (up to
|
|
4572
4653
|
* `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
|
|
4573
4654
|
* the backlog). Embeddings still come from the maintenance
|
|
@@ -4627,6 +4708,7 @@ var WikiMemory = class {
|
|
|
4627
4708
|
{ diag: { buffer: diagBuffer, operation: "upsertGraph" } }
|
|
4628
4709
|
);
|
|
4629
4710
|
this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
|
|
4711
|
+
this.stashRemovalIds(entityId, supersededFactIds);
|
|
4630
4712
|
this.searchService.markStale(entityId);
|
|
4631
4713
|
diagBuffer.flush(this.options);
|
|
4632
4714
|
return result;
|
|
@@ -4809,8 +4891,10 @@ var WikiMemory = class {
|
|
|
4809
4891
|
}
|
|
4810
4892
|
};
|
|
4811
4893
|
_testAccessNonTestEnvWarned = new WeakMap();
|
|
4812
|
-
/** Max upsertGraph node ids held for their post-commit sync (spec #280 id threading). */
|
|
4894
|
+
/** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
|
|
4813
4895
|
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
4896
|
+
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
4897
|
+
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
4814
4898
|
function assertEntityId2(entityId) {
|
|
4815
4899
|
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
4816
4900
|
throw new TypeError("Invalid entityId: must be a non-empty string.");
|
|
@@ -5437,6 +5521,24 @@ function parseStaleAfterRaw(raw) {
|
|
|
5437
5521
|
}
|
|
5438
5522
|
return ms;
|
|
5439
5523
|
}
|
|
5524
|
+
function replaceLoneSurrogates(s) {
|
|
5525
|
+
let out = "";
|
|
5526
|
+
for (let i = 0; i < s.length; i++) {
|
|
5527
|
+
const c = s.charCodeAt(i);
|
|
5528
|
+
if (c >= 55296 && c <= 56319) {
|
|
5529
|
+
const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
5530
|
+
if (n >= 56320 && n <= 57343) {
|
|
5531
|
+
out += s[i] + s[i + 1];
|
|
5532
|
+
i++;
|
|
5533
|
+
} else out += "\uFFFD";
|
|
5534
|
+
} else if (c >= 56320 && c <= 57343) {
|
|
5535
|
+
out += "\uFFFD";
|
|
5536
|
+
} else {
|
|
5537
|
+
out += s[i];
|
|
5538
|
+
}
|
|
5539
|
+
}
|
|
5540
|
+
return out;
|
|
5541
|
+
}
|
|
5440
5542
|
function unescapeLogSummary(summary) {
|
|
5441
5543
|
return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
|
|
5442
5544
|
}
|
|
@@ -5449,7 +5551,7 @@ function parseLogEntryText(text) {
|
|
|
5449
5551
|
if (linkPath) {
|
|
5450
5552
|
return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
|
|
5451
5553
|
}
|
|
5452
|
-
return { event_type, summary: (plainSummary ?? "").trim() };
|
|
5554
|
+
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
5453
5555
|
}
|
|
5454
5556
|
function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
5455
5557
|
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
@@ -5661,6 +5763,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5661
5763
|
}
|
|
5662
5764
|
const events = [];
|
|
5663
5765
|
if (logContent != null) {
|
|
5766
|
+
const pending = [];
|
|
5664
5767
|
const logPath = logMdPath ?? `entities/${entityId}/log.md`;
|
|
5665
5768
|
for (const entry of parseLogMd(logContent)) {
|
|
5666
5769
|
const { text, eventId } = parseEventIdComment(entry.text);
|
|
@@ -5678,8 +5781,9 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5678
5781
|
}
|
|
5679
5782
|
const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
|
|
5680
5783
|
if (!Number.isFinite(created_at)) continue;
|
|
5784
|
+
if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
|
|
5681
5785
|
events.push({
|
|
5682
|
-
id: eventId ??
|
|
5786
|
+
id: eventId ?? "",
|
|
5683
5787
|
entity_id: entityId,
|
|
5684
5788
|
event_type: parsed.event_type,
|
|
5685
5789
|
summary: parsed.summary,
|
|
@@ -5687,6 +5791,22 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
5687
5791
|
created_at
|
|
5688
5792
|
});
|
|
5689
5793
|
}
|
|
5794
|
+
const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
|
|
5795
|
+
const nextOccurrence = /* @__PURE__ */ new Map();
|
|
5796
|
+
for (const { index, date } of pending) {
|
|
5797
|
+
const e = events[index];
|
|
5798
|
+
const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
|
|
5799
|
+
let occurrence = nextOccurrence.get(key) ?? 0;
|
|
5800
|
+
const derive = createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
|
|
5801
|
+
let id = derive(occurrence);
|
|
5802
|
+
while (taken.has(id)) {
|
|
5803
|
+
occurrence += 1;
|
|
5804
|
+
id = derive(occurrence);
|
|
5805
|
+
}
|
|
5806
|
+
taken.add(id);
|
|
5807
|
+
nextOccurrence.set(key, occurrence + 1);
|
|
5808
|
+
e.id = id;
|
|
5809
|
+
}
|
|
5690
5810
|
}
|
|
5691
5811
|
return {
|
|
5692
5812
|
generatedAt: now,
|