@equationalapplications/core-llm-wiki 8.3.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/dist/{chunk-V432RHCG.mjs → chunk-EKYWAR2E.mjs} +975 -111
- 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 +1376 -278
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +264 -31
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BT5qSnGB.d.mts → testing-Og5x9rFu.d.mts} +336 -30
- package/dist/{testing-BT5qSnGB.d.ts → testing-Og5x9rFu.d.ts} +336 -30
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +397 -105
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-V432RHCG.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, 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-
|
|
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
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
|
|
|
@@ -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
|
|
@@ -2961,7 +2965,7 @@ async function createIndexStrategy(db, prefix, metadataRepo, preferred, opts = {
|
|
|
2961
2965
|
|
|
2962
2966
|
// src/services/MaintenanceScheduler.ts
|
|
2963
2967
|
var MaintenanceScheduler = class {
|
|
2964
|
-
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
|
|
2968
|
+
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
|
|
2965
2969
|
this.db = db;
|
|
2966
2970
|
this.options = options;
|
|
2967
2971
|
this.maintenanceService = maintenanceService;
|
|
@@ -2969,6 +2973,8 @@ var MaintenanceScheduler = class {
|
|
|
2969
2973
|
this.eventRepo = eventRepo;
|
|
2970
2974
|
this.entryRepo = entryRepo;
|
|
2971
2975
|
this.jobManager = jobManager;
|
|
2976
|
+
this.vectorRemovalService = vectorRemovalService;
|
|
2977
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
2972
2978
|
}
|
|
2973
2979
|
/**
|
|
2974
2980
|
* Entities with **any** pending work only, sorted by `pendingEvents` desc
|
|
@@ -2980,7 +2986,17 @@ var MaintenanceScheduler = class {
|
|
|
2980
2986
|
const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
|
|
2981
2987
|
const canEmbed = typeof this.options.llmProvider.embed === "function";
|
|
2982
2988
|
const out = [];
|
|
2983
|
-
|
|
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) {
|
|
2984
3000
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
2985
3001
|
const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
|
|
2986
3002
|
const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
|
|
@@ -2990,8 +3006,16 @@ var MaintenanceScheduler = class {
|
|
|
2990
3006
|
if (healCheckpoint > eventCount) healCheckpoint = 0;
|
|
2991
3007
|
const healDue = eventCount - healCheckpoint >= autoHealThreshold;
|
|
2992
3008
|
const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
|
|
2993
|
-
|
|
2994
|
-
|
|
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
|
+
});
|
|
2995
3019
|
}
|
|
2996
3020
|
}
|
|
2997
3021
|
return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
|
|
@@ -3017,8 +3041,9 @@ var MaintenanceScheduler = class {
|
|
|
3017
3041
|
const meter = new UsageMeter(opts.tokenBudget);
|
|
3018
3042
|
const budget = opts.tokenBudget;
|
|
3019
3043
|
const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
|
|
3020
|
-
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
|
|
3021
|
-
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);
|
|
3022
3047
|
const states = pending.map((p) => ({
|
|
3023
3048
|
p,
|
|
3024
3049
|
report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
|
|
@@ -3150,9 +3175,43 @@ var MaintenanceScheduler = class {
|
|
|
3150
3175
|
tokensUsed: meter.used,
|
|
3151
3176
|
estimated: meter.estimated,
|
|
3152
3177
|
remaining: budget === void 0 ? null : meter.remaining,
|
|
3153
|
-
stoppedReason: stopped
|
|
3178
|
+
stoppedReason: stopped,
|
|
3179
|
+
externalDeletions
|
|
3154
3180
|
};
|
|
3155
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
|
+
}
|
|
3156
3215
|
};
|
|
3157
3216
|
|
|
3158
3217
|
// src/prompts/ontology.ts
|
|
@@ -3774,11 +3833,15 @@ var WikiMemory = class {
|
|
|
3774
3833
|
this.upsertIdStashSize = 0;
|
|
3775
3834
|
/** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
|
|
3776
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;
|
|
3777
3839
|
this.reinitSearch = null;
|
|
3778
3840
|
/** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
|
|
3779
3841
|
this.reinitRetryAt = 0;
|
|
3780
3842
|
/** Consecutive failed re-inits; drives the exponential backoff. */
|
|
3781
3843
|
this.reinitFailures = 0;
|
|
3844
|
+
this.setupRemovalDrain = null;
|
|
3782
3845
|
this.db = withSerializedTransactions(db);
|
|
3783
3846
|
this.options = options;
|
|
3784
3847
|
warnChangedDefaultsOnce(options.config);
|
|
@@ -3803,6 +3866,9 @@ var WikiMemory = class {
|
|
|
3803
3866
|
);
|
|
3804
3867
|
this.lintService = new LintService(this.lintRepo, this.ontologyService);
|
|
3805
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);
|
|
3806
3872
|
this.searchService = new SearchService(
|
|
3807
3873
|
this.entryRepo,
|
|
3808
3874
|
new MiniSearchIndexStrategy()
|
|
@@ -3823,7 +3889,8 @@ var WikiMemory = class {
|
|
|
3823
3889
|
this.jobManager,
|
|
3824
3890
|
this.embeddingService,
|
|
3825
3891
|
this.promptService,
|
|
3826
|
-
this.ontologyService
|
|
3892
|
+
this.ontologyService,
|
|
3893
|
+
this.vectorRemovalService
|
|
3827
3894
|
);
|
|
3828
3895
|
this.maintenanceService = new MaintenanceService(
|
|
3829
3896
|
this.db,
|
|
@@ -3839,7 +3906,9 @@ var WikiMemory = class {
|
|
|
3839
3906
|
this.embeddingService,
|
|
3840
3907
|
this.promptService,
|
|
3841
3908
|
this.ontologyService,
|
|
3842
|
-
this.edgeRepo
|
|
3909
|
+
this.edgeRepo,
|
|
3910
|
+
this.vectorRemovalService,
|
|
3911
|
+
this.vectorRemovalRepo
|
|
3843
3912
|
);
|
|
3844
3913
|
this.maintenanceScheduler = new MaintenanceScheduler(
|
|
3845
3914
|
this.db,
|
|
@@ -3848,7 +3917,9 @@ var WikiMemory = class {
|
|
|
3848
3917
|
this.metadataRepo,
|
|
3849
3918
|
this.eventRepo,
|
|
3850
3919
|
this.entryRepo,
|
|
3851
|
-
this.jobManager
|
|
3920
|
+
this.jobManager,
|
|
3921
|
+
this.vectorRemovalService,
|
|
3922
|
+
this.vectorRemovalRepo
|
|
3852
3923
|
);
|
|
3853
3924
|
this.importExportService = new ImportExportService(
|
|
3854
3925
|
this.db,
|
|
@@ -3860,7 +3931,8 @@ var WikiMemory = class {
|
|
|
3860
3931
|
this.searchService,
|
|
3861
3932
|
this.jobManager,
|
|
3862
3933
|
this.embeddingService,
|
|
3863
|
-
this.options
|
|
3934
|
+
this.options,
|
|
3935
|
+
this.vectorRemovalService
|
|
3864
3936
|
);
|
|
3865
3937
|
this.retrievalService = new RetrievalService(
|
|
3866
3938
|
this.options,
|
|
@@ -3928,6 +4000,33 @@ var WikiMemory = class {
|
|
|
3928
4000
|
}
|
|
3929
4001
|
if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
|
|
3930
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
|
+
}
|
|
3931
4030
|
/** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
|
|
3932
4031
|
peekStashedIds(entityId) {
|
|
3933
4032
|
const snapshot = /* @__PURE__ */ new Map();
|
|
@@ -4016,6 +4115,84 @@ var WikiMemory = class {
|
|
|
4016
4115
|
)
|
|
4017
4116
|
);
|
|
4018
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);
|
|
4019
4196
|
}
|
|
4020
4197
|
async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
|
|
4021
4198
|
if (typeof sourceRefOrEntries === "string") {
|
|
@@ -4183,8 +4360,9 @@ var WikiMemory = class {
|
|
|
4183
4360
|
async write(entityId, event) {
|
|
4184
4361
|
return this.writeService.write(entityId, event);
|
|
4185
4362
|
}
|
|
4186
|
-
/** 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`. */
|
|
4187
4364
|
async drain() {
|
|
4365
|
+
await this.setupRemovalDrain;
|
|
4188
4366
|
return this.writeService.drain();
|
|
4189
4367
|
}
|
|
4190
4368
|
/**
|
|
@@ -4196,9 +4374,32 @@ var WikiMemory = class {
|
|
|
4196
4374
|
async getPendingMaintenance(entityIds) {
|
|
4197
4375
|
return this.maintenanceScheduler.getPending(entityIds);
|
|
4198
4376
|
}
|
|
4199
|
-
/** 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. */
|
|
4200
4378
|
async runPendingMaintenance(options) {
|
|
4201
|
-
|
|
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);
|
|
4202
4403
|
}
|
|
4203
4404
|
/**
|
|
4204
4405
|
* @param options.promptOverride - Applies only to this manual call. Does NOT affect
|
|
@@ -4279,6 +4480,11 @@ var WikiMemory = class {
|
|
|
4279
4480
|
* waits at least 5 s, doubling per consecutive failure up to 5 min (longer
|
|
4280
4481
|
* when an attempt is itself slow), before retrying again.
|
|
4281
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
|
+
*
|
|
4282
4488
|
* Call only after the host's transaction commits: called inside it, the
|
|
4283
4489
|
* rebuild may index rows that later roll back, or miss them and clear the
|
|
4284
4490
|
* stale flag anyway. Serialized with core's internal index syncs and takes
|
|
@@ -4294,6 +4500,19 @@ var WikiMemory = class {
|
|
|
4294
4500
|
* @throws {TypeError} when `entityId` is given but is not a non-empty string.
|
|
4295
4501
|
*/
|
|
4296
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) {
|
|
4297
4516
|
if (entityId === void 0) {
|
|
4298
4517
|
if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
|
|
4299
4518
|
this.reinitSearch ?? (this.reinitSearch = (async () => {
|
|
@@ -4361,6 +4580,14 @@ var WikiMemory = class {
|
|
|
4361
4580
|
* hard-deletes the soft-deleted rows once they are older than
|
|
4362
4581
|
* `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
|
|
4363
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()`.
|
|
4364
4591
|
*/
|
|
4365
4592
|
async forget(entityId, params, opts) {
|
|
4366
4593
|
return this.maintenanceService.forget(entityId, params, opts);
|
|
@@ -4413,12 +4640,15 @@ var WikiMemory = class {
|
|
|
4413
4640
|
* semantics identical to `ingestDocument`, minus the LLM extraction step.
|
|
4414
4641
|
*
|
|
4415
4642
|
* MUST be called from inside an open `db.withTransactionAsync` callback —
|
|
4416
|
-
* 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
|
|
4417
4646
|
* nested transaction, does not acquire any lock, and does not perform
|
|
4418
4647
|
* post-commit work (search sync, embedding, cache eviction). After the
|
|
4419
4648
|
* transaction commits, call `syncSearchIndex(entityId)` — or
|
|
4420
4649
|
* `syncSearchIndex()` after writing several entities in one transaction —
|
|
4421
|
-
* 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
|
|
4422
4652
|
* first, to completion, so the nodes are searchable under any backlog (up to
|
|
4423
4653
|
* `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
|
|
4424
4654
|
* the backlog). Embeddings still come from the maintenance
|
|
@@ -4478,6 +4708,7 @@ var WikiMemory = class {
|
|
|
4478
4708
|
{ diag: { buffer: diagBuffer, operation: "upsertGraph" } }
|
|
4479
4709
|
);
|
|
4480
4710
|
this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
|
|
4711
|
+
this.stashRemovalIds(entityId, supersededFactIds);
|
|
4481
4712
|
this.searchService.markStale(entityId);
|
|
4482
4713
|
diagBuffer.flush(this.options);
|
|
4483
4714
|
return result;
|
|
@@ -4660,8 +4891,10 @@ var WikiMemory = class {
|
|
|
4660
4891
|
}
|
|
4661
4892
|
};
|
|
4662
4893
|
_testAccessNonTestEnvWarned = new WeakMap();
|
|
4663
|
-
/** 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). */
|
|
4664
4895
|
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
4896
|
+
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
4897
|
+
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
4665
4898
|
function assertEntityId2(entityId) {
|
|
4666
4899
|
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
4667
4900
|
throw new TypeError("Invalid entityId: must be a non-empty string.");
|