@equationalapplications/core-llm-wiki 9.2.0 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-E3JCZMJL.mjs → chunk-H436I7OM.mjs} +964 -386
- package/dist/chunk-H436I7OM.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +846 -156
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +142 -32
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BQScWWSA.d.mts → testing-DsD-idCv.d.mts} +218 -19
- package/dist/{testing-BQScWWSA.d.ts → testing-DsD-idCv.d.ts} +218 -19
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +675 -136
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-E3JCZMJL.mjs.map +0 -1
|
@@ -935,6 +935,273 @@ function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
|
|
|
935
935
|
return valid;
|
|
936
936
|
}
|
|
937
937
|
|
|
938
|
+
// src/repositories/BaseRepository.ts
|
|
939
|
+
var BaseRepository = class {
|
|
940
|
+
constructor(db, prefix) {
|
|
941
|
+
this.db = db;
|
|
942
|
+
this.prefix = prefix;
|
|
943
|
+
}
|
|
944
|
+
/**
|
|
945
|
+
* Return the DB executor for a given transaction handle.
|
|
946
|
+
* If tx is provided, use it; otherwise fall back to this.db.
|
|
947
|
+
*/
|
|
948
|
+
getExecutor(tx) {
|
|
949
|
+
return tx ?? this.db;
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
|
|
953
|
+
// src/repositories/MetadataRepository.ts
|
|
954
|
+
function entitySummaryMetaKey(entityId) {
|
|
955
|
+
return `entity_summary:${entityId}`;
|
|
956
|
+
}
|
|
957
|
+
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
958
|
+
var CheckpointIncompleteError = class extends Error {
|
|
959
|
+
constructor() {
|
|
960
|
+
super(...arguments);
|
|
961
|
+
this.code = "erase_checkpoint_incomplete";
|
|
962
|
+
}
|
|
963
|
+
};
|
|
964
|
+
var MetadataRepository = class extends BaseRepository {
|
|
965
|
+
// CHECKPOINTS TABLE METHODS
|
|
966
|
+
async getCheckpoint(entityId, tx) {
|
|
967
|
+
const executor = this.getExecutor(tx);
|
|
968
|
+
const row = await executor.getFirstAsync(
|
|
969
|
+
`SELECT memory_checkpoint, heal_checkpoint FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
970
|
+
[entityId]
|
|
971
|
+
);
|
|
972
|
+
if (!row) return {};
|
|
973
|
+
return {
|
|
974
|
+
memory: row.memory_checkpoint ?? void 0,
|
|
975
|
+
heal: row.heal_checkpoint ?? void 0
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
async updateCheckpoint(entityId, updates, tx) {
|
|
979
|
+
const fields = [];
|
|
980
|
+
const values = [];
|
|
981
|
+
if (updates.memory !== void 0) {
|
|
982
|
+
fields.push("memory_checkpoint = ?");
|
|
983
|
+
values.push(updates.memory);
|
|
984
|
+
}
|
|
985
|
+
if (updates.heal !== void 0) {
|
|
986
|
+
fields.push("heal_checkpoint = ?");
|
|
987
|
+
values.push(updates.heal);
|
|
988
|
+
}
|
|
989
|
+
if (fields.length === 0) return;
|
|
990
|
+
const executor = this.getExecutor(tx);
|
|
991
|
+
await executor.runAsync(
|
|
992
|
+
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint)
|
|
993
|
+
VALUES (?, ?, ?)
|
|
994
|
+
ON CONFLICT(entity_id) DO UPDATE SET ${fields.join(", ")}`,
|
|
995
|
+
[entityId, updates.memory ?? 0, updates.heal ?? 0, ...values]
|
|
996
|
+
);
|
|
997
|
+
}
|
|
998
|
+
async deleteCheckpoint(entityId, tx) {
|
|
999
|
+
const executor = this.getExecutor(tx);
|
|
1000
|
+
await executor.runAsync(
|
|
1001
|
+
`DELETE FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
1002
|
+
[entityId]
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Read the op-based librarian's high-water mark. Returns `null` when the
|
|
1007
|
+
* entity has never had its watermark set.
|
|
1008
|
+
*/
|
|
1009
|
+
async getLibrarianWatermark(entityId, tx) {
|
|
1010
|
+
const executor = this.getExecutor(tx);
|
|
1011
|
+
const row = await executor.getFirstAsync(
|
|
1012
|
+
`SELECT librarian_watermark_at, librarian_watermark_id FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
1013
|
+
[entityId]
|
|
1014
|
+
);
|
|
1015
|
+
if (!row || row.librarian_watermark_at == null || row.librarian_watermark_id == null) {
|
|
1016
|
+
return null;
|
|
1017
|
+
}
|
|
1018
|
+
return { at: row.librarian_watermark_at, id: row.librarian_watermark_id };
|
|
1019
|
+
}
|
|
1020
|
+
/**
|
|
1021
|
+
* Write the op-based librarian's high-water mark. Uses `ON CONFLICT`
|
|
1022
|
+
* `DO UPDATE` so existing `memory_checkpoint` / `heal_checkpoint` rows
|
|
1023
|
+
* are preserved verbatim.
|
|
1024
|
+
*/
|
|
1025
|
+
async setLibrarianWatermark(entityId, wm, tx) {
|
|
1026
|
+
const executor = this.getExecutor(tx);
|
|
1027
|
+
await executor.runAsync(
|
|
1028
|
+
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint, librarian_watermark_at, librarian_watermark_id)
|
|
1029
|
+
VALUES (?, 0, 0, ?, ?)
|
|
1030
|
+
ON CONFLICT(entity_id) DO UPDATE SET
|
|
1031
|
+
librarian_watermark_at = excluded.librarian_watermark_at,
|
|
1032
|
+
librarian_watermark_id = excluded.librarian_watermark_id`,
|
|
1033
|
+
[entityId, wm.at, wm.id]
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
// META TABLE METHODS
|
|
1037
|
+
async getMeta(key, tx) {
|
|
1038
|
+
const executor = this.getExecutor(tx);
|
|
1039
|
+
const row = await executor.getFirstAsync(
|
|
1040
|
+
`SELECT value FROM ${this.prefix}meta WHERE key = ?`,
|
|
1041
|
+
[key]
|
|
1042
|
+
);
|
|
1043
|
+
return row ? row.value : null;
|
|
1044
|
+
}
|
|
1045
|
+
async setMeta(key, value, tx) {
|
|
1046
|
+
const executor = this.getExecutor(tx);
|
|
1047
|
+
await executor.runAsync(
|
|
1048
|
+
`INSERT INTO ${this.prefix}meta (key, value) VALUES (?, ?)
|
|
1049
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
1050
|
+
[key, value]
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
async deleteMeta(key, tx) {
|
|
1054
|
+
const executor = this.getExecutor(tx);
|
|
1055
|
+
await executor.runAsync(
|
|
1056
|
+
`DELETE FROM ${this.prefix}meta WHERE key = ?`,
|
|
1057
|
+
[key]
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
async clearDimensionMismatch(tx) {
|
|
1061
|
+
const executor = this.getExecutor(tx);
|
|
1062
|
+
await executor.runAsync(
|
|
1063
|
+
`DELETE FROM ${this.prefix}meta WHERE key = 'embedding_dimension_mismatch'`
|
|
1064
|
+
);
|
|
1065
|
+
}
|
|
1066
|
+
async tableExists(tableName, tx) {
|
|
1067
|
+
const executor = this.getExecutor(tx);
|
|
1068
|
+
const row = await executor.getFirstAsync(
|
|
1069
|
+
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
|
|
1070
|
+
[tableName]
|
|
1071
|
+
);
|
|
1072
|
+
return row != null;
|
|
1073
|
+
}
|
|
1074
|
+
async getTableDdl(tableName, tx) {
|
|
1075
|
+
const executor = this.getExecutor(tx);
|
|
1076
|
+
const row = await executor.getFirstAsync(
|
|
1077
|
+
`SELECT sql FROM sqlite_master WHERE type='table' AND name=?`,
|
|
1078
|
+
[tableName]
|
|
1079
|
+
);
|
|
1080
|
+
return row?.sql ?? null;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* `PRAGMA wal_checkpoint(TRUNCATE)`, verified: `busy !== 0` or
|
|
1084
|
+
* `log !== checkpointed` means frames survive in the WAL, so a deleted
|
|
1085
|
+
* row's bytes may still be on disk. Non-WAL reports (0,-1,-1) = complete.
|
|
1086
|
+
*/
|
|
1087
|
+
async checkpointTruncateVerified() {
|
|
1088
|
+
const row = await this.db.getFirstAsync(
|
|
1089
|
+
`PRAGMA wal_checkpoint(TRUNCATE)`
|
|
1090
|
+
);
|
|
1091
|
+
if (row && (row.busy !== 0 || row.log !== row.checkpointed)) {
|
|
1092
|
+
throw new CheckpointIncompleteError(
|
|
1093
|
+
`wal_checkpoint(TRUNCATE) incomplete (busy=${row?.busy}, log=${row?.log}, checkpointed=${row?.checkpointed})`
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
async vacuum() {
|
|
1098
|
+
await this.checkpointTruncateVerified();
|
|
1099
|
+
await this.db.execAsync(`VACUUM`);
|
|
1100
|
+
await this.checkpointTruncateVerified();
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Returns the set of distinct `entity_id` values across entries/tasks/events.
|
|
1104
|
+
*
|
|
1105
|
+
* Deliberately widened from a prior `WHERE deleted_at IS NULL` form: the
|
|
1106
|
+
* returned set intentionally includes entities whose only rows are
|
|
1107
|
+
* soft-deleted, so the host's maintenance sweep can visit such
|
|
1108
|
+
* "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
|
|
1109
|
+
* is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
|
|
1110
|
+
*
|
|
1111
|
+
* With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
|
|
1112
|
+
* at least one soft-deleted entry or task with `deleted_at` at or before
|
|
1113
|
+
* that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
|
|
1114
|
+
* the option the host-facing semantics above are unchanged.
|
|
1115
|
+
*/
|
|
1116
|
+
async getDistinctEntityIds(tx, opts) {
|
|
1117
|
+
const executor = this.getExecutor(tx);
|
|
1118
|
+
if (opts?.softDeletedAll) {
|
|
1119
|
+
const rows2 = await executor.getAllAsync(
|
|
1120
|
+
`SELECT DISTINCT entity_id FROM (
|
|
1121
|
+
SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
|
|
1122
|
+
UNION
|
|
1123
|
+
SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
|
|
1124
|
+
) ORDER BY entity_id COLLATE BINARY`
|
|
1125
|
+
);
|
|
1126
|
+
return rows2.map((r) => r.entity_id);
|
|
1127
|
+
}
|
|
1128
|
+
if (opts?.softDeletedAtOrBefore !== void 0) {
|
|
1129
|
+
const cutoff = opts.softDeletedAtOrBefore;
|
|
1130
|
+
const rows2 = await executor.getAllAsync(
|
|
1131
|
+
`SELECT DISTINCT entity_id FROM (
|
|
1132
|
+
SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
|
|
1133
|
+
UNION
|
|
1134
|
+
SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
|
|
1135
|
+
) ORDER BY entity_id COLLATE BINARY`,
|
|
1136
|
+
[cutoff, cutoff]
|
|
1137
|
+
);
|
|
1138
|
+
return rows2.map((r) => r.entity_id);
|
|
1139
|
+
}
|
|
1140
|
+
const rows = await executor.getAllAsync(
|
|
1141
|
+
`SELECT DISTINCT entity_id FROM (
|
|
1142
|
+
SELECT entity_id FROM ${this.prefix}entries
|
|
1143
|
+
UNION
|
|
1144
|
+
SELECT entity_id FROM ${this.prefix}tasks
|
|
1145
|
+
UNION
|
|
1146
|
+
SELECT entity_id FROM ${this.prefix}events
|
|
1147
|
+
) ORDER BY entity_id COLLATE BINARY`
|
|
1148
|
+
);
|
|
1149
|
+
return rows.map((r) => r.entity_id);
|
|
1150
|
+
}
|
|
1151
|
+
async getManifest(entityId, tx) {
|
|
1152
|
+
const executor = this.getExecutor(tx);
|
|
1153
|
+
const row = await executor.getFirstAsync(`SELECT mode, manifest_json FROM ${this.prefix}entity_manifests WHERE entity_id = ?`, [entityId]);
|
|
1154
|
+
if (!row) return null;
|
|
1155
|
+
if (row.mode !== "off" && row.mode !== "strict" && row.mode !== "emergent") {
|
|
1156
|
+
throw new Error(`Invalid ontology mode for entity ${entityId}: ${JSON.stringify(row.mode)}`);
|
|
1157
|
+
}
|
|
1158
|
+
let manifest;
|
|
1159
|
+
try {
|
|
1160
|
+
manifest = JSON.parse(row.manifest_json);
|
|
1161
|
+
} catch (error) {
|
|
1162
|
+
throw new Error(`Invalid manifest_json for entity ${entityId}: ${error.message}`);
|
|
1163
|
+
}
|
|
1164
|
+
validateManifest(manifest);
|
|
1165
|
+
return {
|
|
1166
|
+
mode: row.mode,
|
|
1167
|
+
manifest
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
/**
|
|
1171
|
+
* Write an entity's manifest.
|
|
1172
|
+
*
|
|
1173
|
+
* `opts.ifAbsent` selects the conflict behaviour:
|
|
1174
|
+
* - omitted / `false` — upsert. An existing row is replaced.
|
|
1175
|
+
* - `true` — create-if-absent. An existing row is left exactly as it is.
|
|
1176
|
+
*
|
|
1177
|
+
* Returns whether this call actually wrote a row. Under `ifAbsent` a `false`
|
|
1178
|
+
* result means another writer got there first; the check and the write are one
|
|
1179
|
+
* statement, so there is no window between them.
|
|
1180
|
+
*/
|
|
1181
|
+
async setManifest(entityId, data, tx, opts) {
|
|
1182
|
+
validateManifest(data.manifest);
|
|
1183
|
+
const executor = this.getExecutor(tx);
|
|
1184
|
+
const conflictClause = opts?.ifAbsent ? "ON CONFLICT(entity_id) DO NOTHING" : `ON CONFLICT(entity_id) DO UPDATE SET
|
|
1185
|
+
mode = excluded.mode, manifest_json = excluded.manifest_json, updated_at = excluded.updated_at`;
|
|
1186
|
+
const result = await executor.runAsync(
|
|
1187
|
+
`INSERT INTO ${this.prefix}entity_manifests (entity_id, mode, manifest_json, updated_at)
|
|
1188
|
+
VALUES (?, ?, ?, ?)
|
|
1189
|
+
${conflictClause}`,
|
|
1190
|
+
[entityId, data.mode, JSON.stringify(data.manifest), Date.now()]
|
|
1191
|
+
);
|
|
1192
|
+
return result.changes > 0;
|
|
1193
|
+
}
|
|
1194
|
+
async mergeManifestUpdates(entityId, updates, tx) {
|
|
1195
|
+
const current = await this.getManifest(entityId, tx) ?? {
|
|
1196
|
+
mode: "emergent",
|
|
1197
|
+
manifest: emptyManifest()
|
|
1198
|
+
};
|
|
1199
|
+
const merged = mergeOntologyUpdates(current.manifest, updates);
|
|
1200
|
+
await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
|
|
1201
|
+
return merged;
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
|
|
938
1205
|
// src/utils/embedding.ts
|
|
939
1206
|
function parseEmbedding(blob, text) {
|
|
940
1207
|
if (blob && blob.byteLength > 0) {
|
|
@@ -1259,6 +1526,61 @@ var _SearchService = class _SearchService {
|
|
|
1259
1526
|
this.syncChain = work;
|
|
1260
1527
|
return work;
|
|
1261
1528
|
}
|
|
1529
|
+
/** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
|
|
1530
|
+
chainSurfaced(fn) {
|
|
1531
|
+
const work = this.syncChain.then(fn);
|
|
1532
|
+
this.syncChain = work.then(() => void 0, () => void 0);
|
|
1533
|
+
return work;
|
|
1534
|
+
}
|
|
1535
|
+
/** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
|
|
1536
|
+
hasStrictDrain() {
|
|
1537
|
+
const s = this.indexStrategy;
|
|
1538
|
+
return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
|
|
1539
|
+
}
|
|
1540
|
+
/** Erase step 3: chained passage drain, no deadline, errors surfaced. */
|
|
1541
|
+
drainPassagesSurfaced() {
|
|
1542
|
+
const s = this.indexStrategy;
|
|
1543
|
+
if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
|
|
1544
|
+
});
|
|
1545
|
+
return this.chainSurfaced(() => s.drainPassagesStrict());
|
|
1546
|
+
}
|
|
1547
|
+
/** Erase step 4: listed retired FTS tables (empty for strategies without any). */
|
|
1548
|
+
async retiredTables() {
|
|
1549
|
+
const s = this.indexStrategy;
|
|
1550
|
+
return s.retiredTables ? s.retiredTables() : [];
|
|
1551
|
+
}
|
|
1552
|
+
/** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
|
|
1553
|
+
canReclaimRetired() {
|
|
1554
|
+
return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
|
|
1555
|
+
}
|
|
1556
|
+
/** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
|
|
1557
|
+
drainEntriesLedgerSurfaced() {
|
|
1558
|
+
const s = this.indexStrategy;
|
|
1559
|
+
if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
|
|
1560
|
+
});
|
|
1561
|
+
return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
|
|
1562
|
+
}
|
|
1563
|
+
/** Erase step 4: reclaim retired tables to completion; errors surfaced. */
|
|
1564
|
+
reclaimRetiredSurfaced() {
|
|
1565
|
+
const s = this.indexStrategy;
|
|
1566
|
+
if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
|
|
1567
|
+
});
|
|
1568
|
+
return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
|
|
1569
|
+
}
|
|
1570
|
+
/** Erase step 7: FTS optimize on every FTS table that exists. */
|
|
1571
|
+
optimizeSurfaced() {
|
|
1572
|
+
const s = this.indexStrategy;
|
|
1573
|
+
if (!s.optimizeFts) return this.chainSurfaced(async () => {
|
|
1574
|
+
});
|
|
1575
|
+
return this.chainSurfaced(() => s.optimizeFts());
|
|
1576
|
+
}
|
|
1577
|
+
/** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
|
|
1578
|
+
rebuildSurfaced() {
|
|
1579
|
+
const s = this.indexStrategy;
|
|
1580
|
+
if (!s.rebuildForErase) return this.chainSurfaced(async () => {
|
|
1581
|
+
});
|
|
1582
|
+
return this.chainSurfaced(() => s.rebuildForErase());
|
|
1583
|
+
}
|
|
1262
1584
|
/**
|
|
1263
1585
|
* Stored-source passage search for ONE entity (spec source-store section 7:
|
|
1264
1586
|
* ranking and caps are per entity). Rides the active strategy; a strategy
|
|
@@ -1414,7 +1736,7 @@ var JobManager = class {
|
|
|
1414
1736
|
this.statusSubscribers = /* @__PURE__ */ new Map();
|
|
1415
1737
|
/**
|
|
1416
1738
|
* Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
|
|
1417
|
-
* Excludes 'ingest' | 'global_reembed' | 'global_import', which those
|
|
1739
|
+
* Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
|
|
1418
1740
|
* methods already handle via explicit if/else branches before reaching
|
|
1419
1741
|
* this table.
|
|
1420
1742
|
*/
|
|
@@ -1483,6 +1805,9 @@ var JobManager = class {
|
|
|
1483
1805
|
_globalReembedKey() {
|
|
1484
1806
|
return `${this.prefix}:reembed`;
|
|
1485
1807
|
}
|
|
1808
|
+
_eraseKey() {
|
|
1809
|
+
return `${this.prefix}:erase`;
|
|
1810
|
+
}
|
|
1486
1811
|
_importKey(entityId) {
|
|
1487
1812
|
return `${this.prefix}:${entityId}:import`;
|
|
1488
1813
|
}
|
|
@@ -1563,11 +1888,19 @@ var JobManager = class {
|
|
|
1563
1888
|
_isIngestActiveFor(entityId) {
|
|
1564
1889
|
return this.activeIngestJobs.has(entityId);
|
|
1565
1890
|
}
|
|
1566
|
-
|
|
1891
|
+
/**
|
|
1892
|
+
* `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
|
|
1893
|
+
* `'erase'` marks the erase() pipeline's own per-entity prune, the only
|
|
1894
|
+
* operation exempt from the universal erase pre-check below.
|
|
1895
|
+
*/
|
|
1896
|
+
acquireLock(operation, entityId, sourceRef, owner = "host") {
|
|
1567
1897
|
let blockingOperation = null;
|
|
1568
1898
|
if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
|
|
1569
1899
|
throw new WikiBusyError("import", "*");
|
|
1570
1900
|
}
|
|
1901
|
+
if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
|
|
1902
|
+
throw new WikiBusyError("erase", "*");
|
|
1903
|
+
}
|
|
1571
1904
|
switch (operation) {
|
|
1572
1905
|
case "prune":
|
|
1573
1906
|
if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
|
|
@@ -1616,6 +1949,18 @@ var JobManager = class {
|
|
|
1616
1949
|
else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
|
|
1617
1950
|
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
1618
1951
|
break;
|
|
1952
|
+
case "erase":
|
|
1953
|
+
if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
|
|
1954
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
|
|
1955
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
|
|
1956
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
|
|
1957
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
|
|
1958
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
|
|
1959
|
+
else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
|
|
1960
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
|
|
1961
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
|
|
1962
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
1963
|
+
break;
|
|
1619
1964
|
case "import":
|
|
1620
1965
|
case "forget": {
|
|
1621
1966
|
const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
|
|
@@ -1660,7 +2005,7 @@ var JobManager = class {
|
|
|
1660
2005
|
if (blockingOperation) {
|
|
1661
2006
|
throw new WikiBusyError(
|
|
1662
2007
|
blockingOperation,
|
|
1663
|
-
operation === "global_reembed" || operation === "global_import" ? "*" : entityId
|
|
2008
|
+
operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
|
|
1664
2009
|
);
|
|
1665
2010
|
}
|
|
1666
2011
|
if (operation === "ingest") {
|
|
@@ -1669,6 +2014,8 @@ var JobManager = class {
|
|
|
1669
2014
|
this.activeMaintenanceJobs.add(this._globalReembedKey());
|
|
1670
2015
|
} else if (operation === "global_import") {
|
|
1671
2016
|
this.activeMaintenanceJobs.add(this._globalImportKey());
|
|
2017
|
+
} else if (operation === "erase") {
|
|
2018
|
+
this.activeMaintenanceJobs.add(this._eraseKey());
|
|
1672
2019
|
} else {
|
|
1673
2020
|
this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
|
|
1674
2021
|
}
|
|
@@ -1681,6 +2028,8 @@ var JobManager = class {
|
|
|
1681
2028
|
this.activeMaintenanceJobs.delete(this._globalReembedKey());
|
|
1682
2029
|
} else if (operation === "global_import") {
|
|
1683
2030
|
this.activeMaintenanceJobs.delete(this._globalImportKey());
|
|
2031
|
+
} else if (operation === "erase") {
|
|
2032
|
+
this.activeMaintenanceJobs.delete(this._eraseKey());
|
|
1684
2033
|
} else {
|
|
1685
2034
|
this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
|
|
1686
2035
|
}
|
|
@@ -1692,7 +2041,10 @@ var JobManager = class {
|
|
|
1692
2041
|
*/
|
|
1693
2042
|
isBlocked(operation, entityId) {
|
|
1694
2043
|
if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
|
|
2044
|
+
if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
|
|
1695
2045
|
switch (operation) {
|
|
2046
|
+
case "erase":
|
|
2047
|
+
return this.activeMaintenanceJobs.has(this._eraseKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
|
|
1696
2048
|
case "librarian":
|
|
1697
2049
|
case "heal":
|
|
1698
2050
|
case "ontologyBackfill":
|
|
@@ -1726,6 +2078,7 @@ var JobManager = class {
|
|
|
1726
2078
|
*/
|
|
1727
2079
|
tryAcquireAutoHealLock(entityId) {
|
|
1728
2080
|
if (this.isAnyReembedActive()) return false;
|
|
2081
|
+
if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
|
|
1729
2082
|
const healKey = this._healKey(entityId);
|
|
1730
2083
|
if (this.activeMaintenanceJobs.has(healKey)) return false;
|
|
1731
2084
|
this.activeMaintenanceJobs.add(healKey);
|
|
@@ -1769,6 +2122,7 @@ var JobManager = class {
|
|
|
1769
2122
|
* Validates all entities before acquiring any lock (same as current importDump semantics).
|
|
1770
2123
|
*/
|
|
1771
2124
|
acquireImportLocks(entityIds) {
|
|
2125
|
+
if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
|
|
1772
2126
|
for (const entityId of entityIds) {
|
|
1773
2127
|
if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
|
|
1774
2128
|
if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
|
|
@@ -2337,6 +2691,15 @@ var SEVERITY = {
|
|
|
2337
2691
|
resolve_failed: "warn",
|
|
2338
2692
|
read_budget: "info",
|
|
2339
2693
|
event_retention_held: "info",
|
|
2694
|
+
prune_checkpoint_incomplete: "warn",
|
|
2695
|
+
erase_secure_delete_off: "error",
|
|
2696
|
+
erase_entity_skipped: "warn",
|
|
2697
|
+
erase_retired_vtab_undroppable: "warn",
|
|
2698
|
+
erase_retired_remaining: "error",
|
|
2699
|
+
erase_tombstones_remaining: "error",
|
|
2700
|
+
erase_retired_read_failed: "error",
|
|
2701
|
+
erase_registry_sweep_skipped: "info",
|
|
2702
|
+
import_tombstone_skipped: "info",
|
|
2340
2703
|
event_created_at_clamped: "warn",
|
|
2341
2704
|
event_created_at_restamped: "info",
|
|
2342
2705
|
external_deletion_pending: "warn",
|
|
@@ -2372,6 +2735,15 @@ var MESSAGE = {
|
|
|
2372
2735
|
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
2373
2736
|
read_budget: "A read was packed to a token budget.",
|
|
2374
2737
|
event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
|
|
2738
|
+
prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
|
|
2739
|
+
erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
|
|
2740
|
+
erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow tables were emptied and the name stays listed until an FTS5-capable open drops it.",
|
|
2741
|
+
erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
|
|
2742
|
+
erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
|
|
2743
|
+
erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
|
|
2744
|
+
erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
|
|
2745
|
+
erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
|
|
2746
|
+
import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
|
|
2375
2747
|
event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
|
|
2376
2748
|
event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
|
|
2377
2749
|
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
@@ -3243,12 +3615,118 @@ function validateClassifierAnswer(response, key, question) {
|
|
|
3243
3615
|
} catch {
|
|
3244
3616
|
return { ok: false, reason: "malformed" };
|
|
3245
3617
|
}
|
|
3246
|
-
}
|
|
3247
|
-
function classifierStateForFact(fact) {
|
|
3248
|
-
const parts = [fact.title, fact.body];
|
|
3249
|
-
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
3250
|
-
return parts.join("\n\n");
|
|
3251
|
-
}
|
|
3618
|
+
}
|
|
3619
|
+
function classifierStateForFact(fact) {
|
|
3620
|
+
const parts = [fact.title, fact.body];
|
|
3621
|
+
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
3622
|
+
return parts.join("\n\n");
|
|
3623
|
+
}
|
|
3624
|
+
|
|
3625
|
+
// src/utils/temporal.ts
|
|
3626
|
+
function liveAtSql(mode, alias = "") {
|
|
3627
|
+
const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
|
|
3628
|
+
return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
|
|
3629
|
+
}
|
|
3630
|
+
function isLiveAt(f, mode, t) {
|
|
3631
|
+
if (f.deleted_at != null) return false;
|
|
3632
|
+
const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
|
|
3633
|
+
if (from != null && from > t) return false;
|
|
3634
|
+
return f.valid_to == null || f.valid_to > t;
|
|
3635
|
+
}
|
|
3636
|
+
function assertEpochMs(name, v) {
|
|
3637
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
|
|
3638
|
+
throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
|
|
3639
|
+
}
|
|
3640
|
+
return Math.trunc(v);
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
// src/services/TemporalService.ts
|
|
3644
|
+
var HISTORY_MAX_DEPTH = 100;
|
|
3645
|
+
var TemporalService = class {
|
|
3646
|
+
constructor(db, options, entryRepo, searchService, embeddingService) {
|
|
3647
|
+
this.db = db;
|
|
3648
|
+
this.options = options;
|
|
3649
|
+
this.entryRepo = entryRepo;
|
|
3650
|
+
this.searchService = searchService;
|
|
3651
|
+
this.embeddingService = embeddingService;
|
|
3652
|
+
}
|
|
3653
|
+
/**
|
|
3654
|
+
* Link `oldId` → `newId` inside the caller's transaction. `newId` must
|
|
3655
|
+
* already exist. Throws WikiSupersedeError on any rule violation; the
|
|
3656
|
+
* caller's transaction then rolls back.
|
|
3657
|
+
*/
|
|
3658
|
+
async supersedeInTx(tx, entityId, oldId, newId, t, now) {
|
|
3659
|
+
const old = await this.entryRepo.findTemporalRow(oldId, tx);
|
|
3660
|
+
if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
3661
|
+
if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
3662
|
+
if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
3663
|
+
if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
|
|
3664
|
+
if (newId === oldId) throw new WikiSupersedeError("cycle");
|
|
3665
|
+
const repl = await this.entryRepo.findTemporalRow(newId, tx);
|
|
3666
|
+
if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
3667
|
+
if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
3668
|
+
if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
3669
|
+
const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
|
|
3670
|
+
if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
|
|
3671
|
+
await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
|
|
3672
|
+
if (repl.valid_from == null) {
|
|
3673
|
+
await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
async supersede(entityId, oldId, replacement, options) {
|
|
3677
|
+
const now = Date.now();
|
|
3678
|
+
const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
|
|
3679
|
+
let created = null;
|
|
3680
|
+
if (typeof replacement !== "string") {
|
|
3681
|
+
if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
|
|
3682
|
+
throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
|
|
3683
|
+
}
|
|
3684
|
+
created = {
|
|
3685
|
+
id: generateId("fact_"),
|
|
3686
|
+
entity_id: entityId,
|
|
3687
|
+
title: replacement.title,
|
|
3688
|
+
body: replacement.body,
|
|
3689
|
+
tags: Array.isArray(replacement.tags) ? replacement.tags : [],
|
|
3690
|
+
confidence: replacement.confidence ?? "certain",
|
|
3691
|
+
source_type: replacement.source_type ?? "user_stated",
|
|
3692
|
+
source_hash: null,
|
|
3693
|
+
source_ref: null,
|
|
3694
|
+
created_at: now,
|
|
3695
|
+
updated_at: now,
|
|
3696
|
+
last_accessed_at: null,
|
|
3697
|
+
access_count: 0,
|
|
3698
|
+
deleted_at: null
|
|
3699
|
+
};
|
|
3700
|
+
}
|
|
3701
|
+
const newId = typeof replacement === "string" ? replacement : created.id;
|
|
3702
|
+
const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
|
|
3703
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
3704
|
+
if (created) {
|
|
3705
|
+
await this.entryRepo.upsert(created, tx);
|
|
3706
|
+
if (newValidFrom !== void 0) {
|
|
3707
|
+
await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
|
|
3708
|
+
}
|
|
3709
|
+
}
|
|
3710
|
+
await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
|
|
3711
|
+
});
|
|
3712
|
+
await this.searchService.syncEntries(entityId, [oldId, newId]);
|
|
3713
|
+
if (created) {
|
|
3714
|
+
await this.embeddingService.embedFact(
|
|
3715
|
+
{ id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
|
|
3716
|
+
{ operation: "supersede", trigger: "call" }
|
|
3717
|
+
);
|
|
3718
|
+
}
|
|
3719
|
+
this.searchService.evictCache(entityId);
|
|
3720
|
+
return { newId };
|
|
3721
|
+
}
|
|
3722
|
+
async history(entityId, factId) {
|
|
3723
|
+
const start = await this.entryRepo.findTemporalRow(factId);
|
|
3724
|
+
if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
|
|
3725
|
+
const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
|
|
3726
|
+
const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
|
|
3727
|
+
return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
|
|
3728
|
+
}
|
|
3729
|
+
};
|
|
3252
3730
|
|
|
3253
3731
|
// src/utils/engineDefaults.ts
|
|
3254
3732
|
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
@@ -3288,21 +3766,6 @@ function warnChangedDefaultsOnce(config) {
|
|
|
3288
3766
|
}
|
|
3289
3767
|
}
|
|
3290
3768
|
|
|
3291
|
-
// src/repositories/BaseRepository.ts
|
|
3292
|
-
var BaseRepository = class {
|
|
3293
|
-
constructor(db, prefix) {
|
|
3294
|
-
this.db = db;
|
|
3295
|
-
this.prefix = prefix;
|
|
3296
|
-
}
|
|
3297
|
-
/**
|
|
3298
|
-
* Return the DB executor for a given transaction handle.
|
|
3299
|
-
* If tx is provided, use it; otherwise fall back to this.db.
|
|
3300
|
-
*/
|
|
3301
|
-
getExecutor(tx) {
|
|
3302
|
-
return tx ?? this.db;
|
|
3303
|
-
}
|
|
3304
|
-
};
|
|
3305
|
-
|
|
3306
3769
|
// src/repositories/VectorRemovalRepository.ts
|
|
3307
3770
|
var CHUNK = 500;
|
|
3308
3771
|
function removalBackoffMs(attempts) {
|
|
@@ -3840,24 +4303,6 @@ function withBudget(p, ms) {
|
|
|
3840
4303
|
});
|
|
3841
4304
|
}
|
|
3842
4305
|
|
|
3843
|
-
// src/utils/temporal.ts
|
|
3844
|
-
function liveAtSql(mode, alias = "") {
|
|
3845
|
-
const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
|
|
3846
|
-
return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
|
|
3847
|
-
}
|
|
3848
|
-
function isLiveAt(f, mode, t) {
|
|
3849
|
-
if (f.deleted_at != null) return false;
|
|
3850
|
-
const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
|
|
3851
|
-
if (from != null && from > t) return false;
|
|
3852
|
-
return f.valid_to == null || f.valid_to > t;
|
|
3853
|
-
}
|
|
3854
|
-
function assertEpochMs(name, v) {
|
|
3855
|
-
if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
|
|
3856
|
-
throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
|
|
3857
|
-
}
|
|
3858
|
-
return Math.trunc(v);
|
|
3859
|
-
}
|
|
3860
|
-
|
|
3861
4306
|
// src/repositories/EdgeRepository.ts
|
|
3862
4307
|
var CONFIDENCE_RANK = {
|
|
3863
4308
|
tentative: 0,
|
|
@@ -4014,229 +4459,26 @@ var EdgeRepository = class extends BaseRepository {
|
|
|
4014
4459
|
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
4015
4460
|
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
4016
4461
|
const edgeRows = await executor.getAllAsync(
|
|
4017
|
-
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
4018
|
-
SELECT e.* FROM ${this.prefix}edges e
|
|
4019
|
-
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
4020
|
-
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
4021
|
-
WHERE e.entity_id = ?`,
|
|
4022
|
-
[...nodeIds, entityId]
|
|
4023
|
-
);
|
|
4024
|
-
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
4025
|
-
}
|
|
4026
|
-
};
|
|
4027
|
-
function mapRowToEdge(row) {
|
|
4028
|
-
return {
|
|
4029
|
-
id: String(row.id),
|
|
4030
|
-
entity_id: String(row.entity_id),
|
|
4031
|
-
source_id: String(row.source_id),
|
|
4032
|
-
target_id: String(row.target_id),
|
|
4033
|
-
edge_type: String(row.edge_type),
|
|
4034
|
-
created_at: Number(row.created_at)
|
|
4035
|
-
};
|
|
4036
|
-
}
|
|
4037
|
-
|
|
4038
|
-
// src/repositories/MetadataRepository.ts
|
|
4039
|
-
function entitySummaryMetaKey(entityId) {
|
|
4040
|
-
return `entity_summary:${entityId}`;
|
|
4041
|
-
}
|
|
4042
|
-
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
4043
|
-
var MetadataRepository = class extends BaseRepository {
|
|
4044
|
-
// CHECKPOINTS TABLE METHODS
|
|
4045
|
-
async getCheckpoint(entityId, tx) {
|
|
4046
|
-
const executor = this.getExecutor(tx);
|
|
4047
|
-
const row = await executor.getFirstAsync(
|
|
4048
|
-
`SELECT memory_checkpoint, heal_checkpoint FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
4049
|
-
[entityId]
|
|
4050
|
-
);
|
|
4051
|
-
if (!row) return {};
|
|
4052
|
-
return {
|
|
4053
|
-
memory: row.memory_checkpoint ?? void 0,
|
|
4054
|
-
heal: row.heal_checkpoint ?? void 0
|
|
4055
|
-
};
|
|
4056
|
-
}
|
|
4057
|
-
async updateCheckpoint(entityId, updates, tx) {
|
|
4058
|
-
const fields = [];
|
|
4059
|
-
const values = [];
|
|
4060
|
-
if (updates.memory !== void 0) {
|
|
4061
|
-
fields.push("memory_checkpoint = ?");
|
|
4062
|
-
values.push(updates.memory);
|
|
4063
|
-
}
|
|
4064
|
-
if (updates.heal !== void 0) {
|
|
4065
|
-
fields.push("heal_checkpoint = ?");
|
|
4066
|
-
values.push(updates.heal);
|
|
4067
|
-
}
|
|
4068
|
-
if (fields.length === 0) return;
|
|
4069
|
-
const executor = this.getExecutor(tx);
|
|
4070
|
-
await executor.runAsync(
|
|
4071
|
-
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint)
|
|
4072
|
-
VALUES (?, ?, ?)
|
|
4073
|
-
ON CONFLICT(entity_id) DO UPDATE SET ${fields.join(", ")}`,
|
|
4074
|
-
[entityId, updates.memory ?? 0, updates.heal ?? 0, ...values]
|
|
4075
|
-
);
|
|
4076
|
-
}
|
|
4077
|
-
async deleteCheckpoint(entityId, tx) {
|
|
4078
|
-
const executor = this.getExecutor(tx);
|
|
4079
|
-
await executor.runAsync(
|
|
4080
|
-
`DELETE FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
4081
|
-
[entityId]
|
|
4082
|
-
);
|
|
4083
|
-
}
|
|
4084
|
-
/**
|
|
4085
|
-
* Read the op-based librarian's high-water mark. Returns `null` when the
|
|
4086
|
-
* entity has never had its watermark set.
|
|
4087
|
-
*/
|
|
4088
|
-
async getLibrarianWatermark(entityId, tx) {
|
|
4089
|
-
const executor = this.getExecutor(tx);
|
|
4090
|
-
const row = await executor.getFirstAsync(
|
|
4091
|
-
`SELECT librarian_watermark_at, librarian_watermark_id FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
4092
|
-
[entityId]
|
|
4093
|
-
);
|
|
4094
|
-
if (!row || row.librarian_watermark_at == null || row.librarian_watermark_id == null) {
|
|
4095
|
-
return null;
|
|
4096
|
-
}
|
|
4097
|
-
return { at: row.librarian_watermark_at, id: row.librarian_watermark_id };
|
|
4098
|
-
}
|
|
4099
|
-
/**
|
|
4100
|
-
* Write the op-based librarian's high-water mark. Uses `ON CONFLICT`
|
|
4101
|
-
* `DO UPDATE` so existing `memory_checkpoint` / `heal_checkpoint` rows
|
|
4102
|
-
* are preserved verbatim.
|
|
4103
|
-
*/
|
|
4104
|
-
async setLibrarianWatermark(entityId, wm, tx) {
|
|
4105
|
-
const executor = this.getExecutor(tx);
|
|
4106
|
-
await executor.runAsync(
|
|
4107
|
-
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint, librarian_watermark_at, librarian_watermark_id)
|
|
4108
|
-
VALUES (?, 0, 0, ?, ?)
|
|
4109
|
-
ON CONFLICT(entity_id) DO UPDATE SET
|
|
4110
|
-
librarian_watermark_at = excluded.librarian_watermark_at,
|
|
4111
|
-
librarian_watermark_id = excluded.librarian_watermark_id`,
|
|
4112
|
-
[entityId, wm.at, wm.id]
|
|
4113
|
-
);
|
|
4114
|
-
}
|
|
4115
|
-
// META TABLE METHODS
|
|
4116
|
-
async getMeta(key, tx) {
|
|
4117
|
-
const executor = this.getExecutor(tx);
|
|
4118
|
-
const row = await executor.getFirstAsync(
|
|
4119
|
-
`SELECT value FROM ${this.prefix}meta WHERE key = ?`,
|
|
4120
|
-
[key]
|
|
4121
|
-
);
|
|
4122
|
-
return row ? row.value : null;
|
|
4123
|
-
}
|
|
4124
|
-
async setMeta(key, value, tx) {
|
|
4125
|
-
const executor = this.getExecutor(tx);
|
|
4126
|
-
await executor.runAsync(
|
|
4127
|
-
`INSERT INTO ${this.prefix}meta (key, value) VALUES (?, ?)
|
|
4128
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
4129
|
-
[key, value]
|
|
4130
|
-
);
|
|
4131
|
-
}
|
|
4132
|
-
async deleteMeta(key, tx) {
|
|
4133
|
-
const executor = this.getExecutor(tx);
|
|
4134
|
-
await executor.runAsync(
|
|
4135
|
-
`DELETE FROM ${this.prefix}meta WHERE key = ?`,
|
|
4136
|
-
[key]
|
|
4137
|
-
);
|
|
4138
|
-
}
|
|
4139
|
-
async clearDimensionMismatch(tx) {
|
|
4140
|
-
const executor = this.getExecutor(tx);
|
|
4141
|
-
await executor.runAsync(
|
|
4142
|
-
`DELETE FROM ${this.prefix}meta WHERE key = 'embedding_dimension_mismatch'`
|
|
4143
|
-
);
|
|
4144
|
-
}
|
|
4145
|
-
async tableExists(tableName, tx) {
|
|
4146
|
-
const executor = this.getExecutor(tx);
|
|
4147
|
-
const row = await executor.getFirstAsync(
|
|
4148
|
-
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
|
|
4149
|
-
[tableName]
|
|
4150
|
-
);
|
|
4151
|
-
return row != null;
|
|
4152
|
-
}
|
|
4153
|
-
async getTableDdl(tableName, tx) {
|
|
4154
|
-
const executor = this.getExecutor(tx);
|
|
4155
|
-
const row = await executor.getFirstAsync(
|
|
4156
|
-
`SELECT sql FROM sqlite_master WHERE type='table' AND name=?`,
|
|
4157
|
-
[tableName]
|
|
4158
|
-
);
|
|
4159
|
-
return row?.sql ?? null;
|
|
4160
|
-
}
|
|
4161
|
-
async vacuum() {
|
|
4162
|
-
await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
|
|
4163
|
-
await this.db.execAsync(`VACUUM`);
|
|
4164
|
-
}
|
|
4165
|
-
/**
|
|
4166
|
-
* Returns the set of distinct `entity_id` values across entries/tasks/events.
|
|
4167
|
-
*
|
|
4168
|
-
* Deliberately widened from a prior `WHERE deleted_at IS NULL` form: the
|
|
4169
|
-
* returned set intentionally includes entities whose only rows are
|
|
4170
|
-
* soft-deleted, so the host's maintenance sweep can visit such
|
|
4171
|
-
* "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
|
|
4172
|
-
* is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
|
|
4173
|
-
*/
|
|
4174
|
-
async getDistinctEntityIds(tx) {
|
|
4175
|
-
const executor = this.getExecutor(tx);
|
|
4176
|
-
const rows = await executor.getAllAsync(
|
|
4177
|
-
`SELECT DISTINCT entity_id FROM (
|
|
4178
|
-
SELECT entity_id FROM ${this.prefix}entries
|
|
4179
|
-
UNION
|
|
4180
|
-
SELECT entity_id FROM ${this.prefix}tasks
|
|
4181
|
-
UNION
|
|
4182
|
-
SELECT entity_id FROM ${this.prefix}events
|
|
4183
|
-
) ORDER BY entity_id COLLATE BINARY`
|
|
4184
|
-
);
|
|
4185
|
-
return rows.map((r) => r.entity_id);
|
|
4186
|
-
}
|
|
4187
|
-
async getManifest(entityId, tx) {
|
|
4188
|
-
const executor = this.getExecutor(tx);
|
|
4189
|
-
const row = await executor.getFirstAsync(`SELECT mode, manifest_json FROM ${this.prefix}entity_manifests WHERE entity_id = ?`, [entityId]);
|
|
4190
|
-
if (!row) return null;
|
|
4191
|
-
if (row.mode !== "off" && row.mode !== "strict" && row.mode !== "emergent") {
|
|
4192
|
-
throw new Error(`Invalid ontology mode for entity ${entityId}: ${JSON.stringify(row.mode)}`);
|
|
4193
|
-
}
|
|
4194
|
-
let manifest;
|
|
4195
|
-
try {
|
|
4196
|
-
manifest = JSON.parse(row.manifest_json);
|
|
4197
|
-
} catch (error) {
|
|
4198
|
-
throw new Error(`Invalid manifest_json for entity ${entityId}: ${error.message}`);
|
|
4199
|
-
}
|
|
4200
|
-
validateManifest(manifest);
|
|
4201
|
-
return {
|
|
4202
|
-
mode: row.mode,
|
|
4203
|
-
manifest
|
|
4204
|
-
};
|
|
4205
|
-
}
|
|
4206
|
-
/**
|
|
4207
|
-
* Write an entity's manifest.
|
|
4208
|
-
*
|
|
4209
|
-
* `opts.ifAbsent` selects the conflict behaviour:
|
|
4210
|
-
* - omitted / `false` — upsert. An existing row is replaced.
|
|
4211
|
-
* - `true` — create-if-absent. An existing row is left exactly as it is.
|
|
4212
|
-
*
|
|
4213
|
-
* Returns whether this call actually wrote a row. Under `ifAbsent` a `false`
|
|
4214
|
-
* result means another writer got there first; the check and the write are one
|
|
4215
|
-
* statement, so there is no window between them.
|
|
4216
|
-
*/
|
|
4217
|
-
async setManifest(entityId, data, tx, opts) {
|
|
4218
|
-
validateManifest(data.manifest);
|
|
4219
|
-
const executor = this.getExecutor(tx);
|
|
4220
|
-
const conflictClause = opts?.ifAbsent ? "ON CONFLICT(entity_id) DO NOTHING" : `ON CONFLICT(entity_id) DO UPDATE SET
|
|
4221
|
-
mode = excluded.mode, manifest_json = excluded.manifest_json, updated_at = excluded.updated_at`;
|
|
4222
|
-
const result = await executor.runAsync(
|
|
4223
|
-
`INSERT INTO ${this.prefix}entity_manifests (entity_id, mode, manifest_json, updated_at)
|
|
4224
|
-
VALUES (?, ?, ?, ?)
|
|
4225
|
-
${conflictClause}`,
|
|
4226
|
-
[entityId, data.mode, JSON.stringify(data.manifest), Date.now()]
|
|
4462
|
+
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
4463
|
+
SELECT e.* FROM ${this.prefix}edges e
|
|
4464
|
+
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
4465
|
+
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
4466
|
+
WHERE e.entity_id = ?`,
|
|
4467
|
+
[...nodeIds, entityId]
|
|
4227
4468
|
);
|
|
4228
|
-
return
|
|
4229
|
-
}
|
|
4230
|
-
async mergeManifestUpdates(entityId, updates, tx) {
|
|
4231
|
-
const current = await this.getManifest(entityId, tx) ?? {
|
|
4232
|
-
mode: "emergent",
|
|
4233
|
-
manifest: emptyManifest()
|
|
4234
|
-
};
|
|
4235
|
-
const merged = mergeOntologyUpdates(current.manifest, updates);
|
|
4236
|
-
await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
|
|
4237
|
-
return merged;
|
|
4469
|
+
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
4238
4470
|
}
|
|
4239
4471
|
};
|
|
4472
|
+
function mapRowToEdge(row) {
|
|
4473
|
+
return {
|
|
4474
|
+
id: String(row.id),
|
|
4475
|
+
entity_id: String(row.entity_id),
|
|
4476
|
+
source_id: String(row.source_id),
|
|
4477
|
+
target_id: String(row.target_id),
|
|
4478
|
+
edge_type: String(row.edge_type),
|
|
4479
|
+
created_at: Number(row.created_at)
|
|
4480
|
+
};
|
|
4481
|
+
}
|
|
4240
4482
|
|
|
4241
4483
|
// src/services/legacyWatermark.ts
|
|
4242
4484
|
async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
|
|
@@ -5838,94 +6080,6 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
5838
6080
|
return out;
|
|
5839
6081
|
}
|
|
5840
6082
|
|
|
5841
|
-
// src/services/TemporalService.ts
|
|
5842
|
-
var HISTORY_MAX_DEPTH = 100;
|
|
5843
|
-
var TemporalService = class {
|
|
5844
|
-
constructor(db, options, entryRepo, searchService, embeddingService) {
|
|
5845
|
-
this.db = db;
|
|
5846
|
-
this.options = options;
|
|
5847
|
-
this.entryRepo = entryRepo;
|
|
5848
|
-
this.searchService = searchService;
|
|
5849
|
-
this.embeddingService = embeddingService;
|
|
5850
|
-
}
|
|
5851
|
-
/**
|
|
5852
|
-
* Link `oldId` → `newId` inside the caller's transaction. `newId` must
|
|
5853
|
-
* already exist. Throws WikiSupersedeError on any rule violation; the
|
|
5854
|
-
* caller's transaction then rolls back.
|
|
5855
|
-
*/
|
|
5856
|
-
async supersedeInTx(tx, entityId, oldId, newId, t, now) {
|
|
5857
|
-
const old = await this.entryRepo.findTemporalRow(oldId, tx);
|
|
5858
|
-
if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
5859
|
-
if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
5860
|
-
if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
5861
|
-
if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
|
|
5862
|
-
if (newId === oldId) throw new WikiSupersedeError("cycle");
|
|
5863
|
-
const repl = await this.entryRepo.findTemporalRow(newId, tx);
|
|
5864
|
-
if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
5865
|
-
if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
5866
|
-
if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
5867
|
-
const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
|
|
5868
|
-
if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
|
|
5869
|
-
await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
|
|
5870
|
-
if (repl.valid_from == null) {
|
|
5871
|
-
await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
|
|
5872
|
-
}
|
|
5873
|
-
}
|
|
5874
|
-
async supersede(entityId, oldId, replacement, options) {
|
|
5875
|
-
const now = Date.now();
|
|
5876
|
-
const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
|
|
5877
|
-
let created = null;
|
|
5878
|
-
if (typeof replacement !== "string") {
|
|
5879
|
-
if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
|
|
5880
|
-
throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
|
|
5881
|
-
}
|
|
5882
|
-
created = {
|
|
5883
|
-
id: generateId("fact_"),
|
|
5884
|
-
entity_id: entityId,
|
|
5885
|
-
title: replacement.title,
|
|
5886
|
-
body: replacement.body,
|
|
5887
|
-
tags: Array.isArray(replacement.tags) ? replacement.tags : [],
|
|
5888
|
-
confidence: replacement.confidence ?? "certain",
|
|
5889
|
-
source_type: replacement.source_type ?? "user_stated",
|
|
5890
|
-
source_hash: null,
|
|
5891
|
-
source_ref: null,
|
|
5892
|
-
created_at: now,
|
|
5893
|
-
updated_at: now,
|
|
5894
|
-
last_accessed_at: null,
|
|
5895
|
-
access_count: 0,
|
|
5896
|
-
deleted_at: null
|
|
5897
|
-
};
|
|
5898
|
-
}
|
|
5899
|
-
const newId = typeof replacement === "string" ? replacement : created.id;
|
|
5900
|
-
const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
|
|
5901
|
-
await this.db.withTransactionAsync(async (tx) => {
|
|
5902
|
-
if (created) {
|
|
5903
|
-
await this.entryRepo.upsert(created, tx);
|
|
5904
|
-
if (newValidFrom !== void 0) {
|
|
5905
|
-
await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
|
|
5906
|
-
}
|
|
5907
|
-
}
|
|
5908
|
-
await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
|
|
5909
|
-
});
|
|
5910
|
-
await this.searchService.syncEntries(entityId, [oldId, newId]);
|
|
5911
|
-
if (created) {
|
|
5912
|
-
await this.embeddingService.embedFact(
|
|
5913
|
-
{ id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
|
|
5914
|
-
{ operation: "supersede", trigger: "call" }
|
|
5915
|
-
);
|
|
5916
|
-
}
|
|
5917
|
-
this.searchService.evictCache(entityId);
|
|
5918
|
-
return { newId };
|
|
5919
|
-
}
|
|
5920
|
-
async history(entityId, factId) {
|
|
5921
|
-
const start = await this.entryRepo.findTemporalRow(factId);
|
|
5922
|
-
if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
|
|
5923
|
-
const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
|
|
5924
|
-
const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
|
|
5925
|
-
return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
|
|
5926
|
-
}
|
|
5927
|
-
};
|
|
5928
|
-
|
|
5929
6083
|
// src/services/librarian/ops/apply.ts
|
|
5930
6084
|
function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
|
|
5931
6085
|
if (candidate.sourceEventId === null) return null;
|
|
@@ -6191,6 +6345,7 @@ async function runLibrarianStrategy(deps, ctx) {
|
|
|
6191
6345
|
}
|
|
6192
6346
|
|
|
6193
6347
|
// src/services/MaintenanceService.ts
|
|
6348
|
+
var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
|
|
6194
6349
|
var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
|
|
6195
6350
|
var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
6196
6351
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -6239,6 +6394,20 @@ var formatSkipError = (err) => {
|
|
|
6239
6394
|
}
|
|
6240
6395
|
return base;
|
|
6241
6396
|
};
|
|
6397
|
+
function eraseRuntime() {
|
|
6398
|
+
const g = globalThis;
|
|
6399
|
+
if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
|
|
6400
|
+
return g.HermesInternal ? "hermes" : "unknown";
|
|
6401
|
+
}
|
|
6402
|
+
var EraseStepError = class extends Error {
|
|
6403
|
+
constructor(code, message, report, cause) {
|
|
6404
|
+
super(message);
|
|
6405
|
+
this.code = code;
|
|
6406
|
+
this.report = report;
|
|
6407
|
+
this.name = "EraseStepError";
|
|
6408
|
+
if (cause !== void 0) this.cause = cause;
|
|
6409
|
+
}
|
|
6410
|
+
};
|
|
6242
6411
|
var MaintenanceService = class {
|
|
6243
6412
|
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
|
|
6244
6413
|
this.db = db;
|
|
@@ -6259,7 +6428,15 @@ var MaintenanceService = class {
|
|
|
6259
6428
|
this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
|
|
6260
6429
|
}
|
|
6261
6430
|
async runPrune(entityId, options) {
|
|
6262
|
-
this.
|
|
6431
|
+
return this._runPrune(entityId, options, "host");
|
|
6432
|
+
}
|
|
6433
|
+
/**
|
|
6434
|
+
* Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
|
|
6435
|
+
* through the universal erase fence in JobManager; the public `runPrune`
|
|
6436
|
+
* always passes `'host'`.
|
|
6437
|
+
*/
|
|
6438
|
+
async _runPrune(entityId, options, owner) {
|
|
6439
|
+
this.jobManager.acquireLock("prune", entityId, void 0, owner);
|
|
6263
6440
|
try {
|
|
6264
6441
|
const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
|
|
6265
6442
|
const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
|
|
@@ -6290,8 +6467,9 @@ var MaintenanceService = class {
|
|
|
6290
6467
|
}
|
|
6291
6468
|
}
|
|
6292
6469
|
if (retainSoftDeletedFor !== null) {
|
|
6293
|
-
const
|
|
6294
|
-
const
|
|
6470
|
+
const softDeletedAll = options?.softDeletedCutoff === "all";
|
|
6471
|
+
const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
|
|
6472
|
+
const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
|
|
6295
6473
|
const prunableIds = entriesToDelete.map((r) => r.id);
|
|
6296
6474
|
const vr = this.vectorRemoval;
|
|
6297
6475
|
const vrRepo = this.vectorRemovalRepo;
|
|
@@ -6337,7 +6515,7 @@ var MaintenanceService = class {
|
|
|
6337
6515
|
}
|
|
6338
6516
|
if (deletable.length > 0) {
|
|
6339
6517
|
const deletedIds = [];
|
|
6340
|
-
deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
|
|
6518
|
+
deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
|
|
6341
6519
|
if (hookLedger) {
|
|
6342
6520
|
const gone = new Set(deletedIds);
|
|
6343
6521
|
const skipped = deletable.filter((id) => !gone.has(id));
|
|
@@ -6352,7 +6530,7 @@ var MaintenanceService = class {
|
|
|
6352
6530
|
else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
|
|
6353
6531
|
}
|
|
6354
6532
|
}
|
|
6355
|
-
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
|
|
6533
|
+
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
|
|
6356
6534
|
});
|
|
6357
6535
|
if (hookLedger) {
|
|
6358
6536
|
const keptSet = new Set(kept);
|
|
@@ -6397,12 +6575,20 @@ var MaintenanceService = class {
|
|
|
6397
6575
|
}
|
|
6398
6576
|
}
|
|
6399
6577
|
}
|
|
6578
|
+
let vacuumCheckpointErr;
|
|
6400
6579
|
if (vacuum) {
|
|
6401
|
-
|
|
6402
|
-
|
|
6403
|
-
|
|
6580
|
+
try {
|
|
6581
|
+
await this._wrappedVacuum();
|
|
6582
|
+
} catch (err) {
|
|
6583
|
+
if (!(err instanceof CheckpointIncompleteError)) throw err;
|
|
6584
|
+
vacuumCheckpointErr = err;
|
|
6585
|
+
}
|
|
6404
6586
|
}
|
|
6587
|
+
if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
|
|
6405
6588
|
await this.searchService.syncEntries(entityId, syncedIds);
|
|
6589
|
+
if (prunePartial && vacuumCheckpointErr) {
|
|
6590
|
+
emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
|
|
6591
|
+
}
|
|
6406
6592
|
if (prunePartial) {
|
|
6407
6593
|
throw new PrunePartialFailureError(
|
|
6408
6594
|
deletedEntries,
|
|
@@ -6413,11 +6599,327 @@ var MaintenanceService = class {
|
|
|
6413
6599
|
deletedEvents
|
|
6414
6600
|
);
|
|
6415
6601
|
}
|
|
6602
|
+
if (vacuumCheckpointErr) throw vacuumCheckpointErr;
|
|
6416
6603
|
return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
|
|
6417
6604
|
} finally {
|
|
6418
6605
|
this.jobManager.releaseLock("prune", entityId);
|
|
6419
6606
|
}
|
|
6420
6607
|
}
|
|
6608
|
+
/** Shared by runPrune and erase step 5. */
|
|
6609
|
+
async _wrappedVacuum() {
|
|
6610
|
+
await resetNormalizeWatermarks(this.metadataRepo);
|
|
6611
|
+
let checkpointErr;
|
|
6612
|
+
try {
|
|
6613
|
+
await this.metadataRepo.vacuum();
|
|
6614
|
+
} catch (err) {
|
|
6615
|
+
if (!(err instanceof CheckpointIncompleteError)) throw err;
|
|
6616
|
+
checkpointErr = err;
|
|
6617
|
+
}
|
|
6618
|
+
await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
|
|
6619
|
+
if (checkpointErr) throw checkpointErr;
|
|
6620
|
+
}
|
|
6621
|
+
/**
|
|
6622
|
+
* Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
|
|
6623
|
+
* completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
|
|
6624
|
+
* success it cannot verify: a failed step throws {@link EraseStepError}
|
|
6625
|
+
* carrying the partial report with `verified: false`.
|
|
6626
|
+
*/
|
|
6627
|
+
async erase(opts) {
|
|
6628
|
+
const rebuild = opts?.rebuild === true;
|
|
6629
|
+
this.jobManager.acquireLock("erase", "*");
|
|
6630
|
+
const report = {
|
|
6631
|
+
verified: false,
|
|
6632
|
+
secureDelete: null,
|
|
6633
|
+
sqliteVersion: "",
|
|
6634
|
+
entities: [],
|
|
6635
|
+
holds: [],
|
|
6636
|
+
skipped: [],
|
|
6637
|
+
syncedIds: [],
|
|
6638
|
+
registrySweep: { skipped: false, deleted: 0 },
|
|
6639
|
+
retiredUndroppable: [],
|
|
6640
|
+
failedStep: null,
|
|
6641
|
+
runtime: eraseRuntime(),
|
|
6642
|
+
steps: []
|
|
6643
|
+
};
|
|
6644
|
+
const ok = (step, outcome = "ok") => {
|
|
6645
|
+
report.steps.push({ step, outcome });
|
|
6646
|
+
};
|
|
6647
|
+
try {
|
|
6648
|
+
const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
|
|
6649
|
+
let pragma;
|
|
6650
|
+
try {
|
|
6651
|
+
pragma = await readPragma();
|
|
6652
|
+
if (pragma !== 1) {
|
|
6653
|
+
await this.db.execAsync("PRAGMA secure_delete=ON");
|
|
6654
|
+
pragma = await readPragma();
|
|
6655
|
+
}
|
|
6656
|
+
report.secureDelete = pragma;
|
|
6657
|
+
report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
|
|
6658
|
+
} catch (err) {
|
|
6659
|
+
report.failedStep = "secure_delete";
|
|
6660
|
+
throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
|
|
6661
|
+
}
|
|
6662
|
+
if (pragma !== 1) {
|
|
6663
|
+
emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
|
|
6664
|
+
report.failedStep = "secure_delete";
|
|
6665
|
+
throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
|
|
6666
|
+
}
|
|
6667
|
+
ok("secure_delete");
|
|
6668
|
+
try {
|
|
6669
|
+
report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
|
|
6670
|
+
} catch (err) {
|
|
6671
|
+
report.failedStep = "prune";
|
|
6672
|
+
throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
|
|
6673
|
+
}
|
|
6674
|
+
const syncedByEntity = /* @__PURE__ */ new Map();
|
|
6675
|
+
for (const entityId of report.entities) {
|
|
6676
|
+
const syncedIds = [];
|
|
6677
|
+
syncedByEntity.set(entityId, syncedIds);
|
|
6678
|
+
try {
|
|
6679
|
+
await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
|
|
6680
|
+
} catch (err) {
|
|
6681
|
+
if (err instanceof PrunePartialFailureError) {
|
|
6682
|
+
report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
|
|
6683
|
+
} else if (err instanceof WikiBusyError) {
|
|
6684
|
+
report.skipped.push(entityId);
|
|
6685
|
+
emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
|
|
6686
|
+
} else {
|
|
6687
|
+
report.failedStep = "prune";
|
|
6688
|
+
throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
|
|
6689
|
+
}
|
|
6690
|
+
}
|
|
6691
|
+
for (const id of syncedIds) report.syncedIds.push(id);
|
|
6692
|
+
}
|
|
6693
|
+
ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
|
|
6694
|
+
try {
|
|
6695
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
6696
|
+
if (await this.sourceRefIndexPresent(tx)) {
|
|
6697
|
+
const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
|
|
6698
|
+
report.registrySweep = { skipped: false, deleted: r.changes };
|
|
6699
|
+
} else {
|
|
6700
|
+
report.registrySweep = { skipped: true, deleted: 0 };
|
|
6701
|
+
}
|
|
6702
|
+
});
|
|
6703
|
+
} catch (err) {
|
|
6704
|
+
report.failedStep = "registry_sweep";
|
|
6705
|
+
throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
|
|
6706
|
+
}
|
|
6707
|
+
if (report.registrySweep.skipped) {
|
|
6708
|
+
emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
|
|
6709
|
+
}
|
|
6710
|
+
ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
|
|
6711
|
+
await this._eraseDrainPassages(report);
|
|
6712
|
+
ok("passage_drain");
|
|
6713
|
+
await this._eraseReclaimRetired(report);
|
|
6714
|
+
ok("retired_reclaim");
|
|
6715
|
+
try {
|
|
6716
|
+
await this._wrappedVacuum();
|
|
6717
|
+
} catch (err) {
|
|
6718
|
+
if (err instanceof CheckpointIncompleteError) {
|
|
6719
|
+
report.failedStep = "checkpoint";
|
|
6720
|
+
throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
|
|
6721
|
+
}
|
|
6722
|
+
report.failedStep = "vacuum";
|
|
6723
|
+
throw new EraseStepError("erase_vacuum_failed", "erase stopped at step 5: VACUUM failed (commonly an unfenced writer holding the database \u2014 quiesce and retry; also any other VACUUM failure, e.g. disk-full or I/O errors)", report, err);
|
|
6724
|
+
}
|
|
6725
|
+
ok("vacuum");
|
|
6726
|
+
const byEntity = /* @__PURE__ */ new Map();
|
|
6727
|
+
for (const e of report.entities) byEntity.set(e, []);
|
|
6728
|
+
for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
|
|
6729
|
+
for (const [entityId, ids] of byEntity) {
|
|
6730
|
+
if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
|
|
6731
|
+
}
|
|
6732
|
+
ok("index_sync");
|
|
6733
|
+
if (rebuild) {
|
|
6734
|
+
try {
|
|
6735
|
+
await this.searchService.rebuildSurfaced();
|
|
6736
|
+
} catch (err) {
|
|
6737
|
+
report.failedStep = "rebuild";
|
|
6738
|
+
throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
|
|
6739
|
+
}
|
|
6740
|
+
ok("rebuild");
|
|
6741
|
+
}
|
|
6742
|
+
await this._eraseReclaimRetired(report);
|
|
6743
|
+
let present;
|
|
6744
|
+
try {
|
|
6745
|
+
present = await this.db.getAllAsync(
|
|
6746
|
+
`SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
|
|
6747
|
+
);
|
|
6748
|
+
} catch (err) {
|
|
6749
|
+
report.failedStep = "retired_reclaim";
|
|
6750
|
+
emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
|
|
6751
|
+
throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
|
|
6752
|
+
}
|
|
6753
|
+
const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
|
|
6754
|
+
if (left.length > 0) {
|
|
6755
|
+
report.failedStep = "retired_reclaim";
|
|
6756
|
+
emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
|
|
6757
|
+
throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
|
|
6758
|
+
}
|
|
6759
|
+
ok("retired_reclaim_rerun");
|
|
6760
|
+
await this._eraseOptimize(report);
|
|
6761
|
+
ok("optimize");
|
|
6762
|
+
try {
|
|
6763
|
+
await this.metadataRepo.checkpointTruncateVerified();
|
|
6764
|
+
} catch (err) {
|
|
6765
|
+
report.failedStep = "checkpoint";
|
|
6766
|
+
throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
|
|
6767
|
+
}
|
|
6768
|
+
ok("checkpoint");
|
|
6769
|
+
if (report.skipped.length === 0 && report.holds.length === 0) {
|
|
6770
|
+
let remainingTombstones;
|
|
6771
|
+
try {
|
|
6772
|
+
const row = await this.db.getFirstAsync(
|
|
6773
|
+
`SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
|
|
6774
|
+
+ (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
|
|
6775
|
+
);
|
|
6776
|
+
remainingTombstones = row?.n ?? 0;
|
|
6777
|
+
} catch (err) {
|
|
6778
|
+
report.failedStep = "tombstone_gate";
|
|
6779
|
+
throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
|
|
6780
|
+
}
|
|
6781
|
+
if (remainingTombstones > 0) {
|
|
6782
|
+
emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
|
|
6783
|
+
report.failedStep = "tombstone_gate";
|
|
6784
|
+
throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
|
|
6785
|
+
}
|
|
6786
|
+
ok("tombstone_gate");
|
|
6787
|
+
} else {
|
|
6788
|
+
report.steps.push({ step: "tombstone_gate", outcome: "partial" });
|
|
6789
|
+
}
|
|
6790
|
+
report.verified = report.skipped.length === 0 && report.holds.length === 0;
|
|
6791
|
+
return report;
|
|
6792
|
+
} catch (err) {
|
|
6793
|
+
if (err instanceof EraseStepError && err.report === report && report.failedStep) {
|
|
6794
|
+
report.steps.push({ step: report.failedStep, outcome: "failed" });
|
|
6795
|
+
report.verified = false;
|
|
6796
|
+
}
|
|
6797
|
+
throw err;
|
|
6798
|
+
} finally {
|
|
6799
|
+
this.jobManager.releaseLock("erase", "*");
|
|
6800
|
+
}
|
|
6801
|
+
}
|
|
6802
|
+
// ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
|
|
6803
|
+
/**
|
|
6804
|
+
* Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
|
|
6805
|
+
* the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
|
|
6806
|
+
* N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
|
|
6807
|
+
* drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
|
|
6808
|
+
* mean text was never drained -> the step fails and erasure is unverified.
|
|
6809
|
+
* Absent or empty ledgers proceed.
|
|
6810
|
+
*/
|
|
6811
|
+
async _eraseDrainPassages(report) {
|
|
6812
|
+
if (!this.searchService.hasStrictDrain()) {
|
|
6813
|
+
for (const [table, failedStep, code] of [
|
|
6814
|
+
[`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
|
|
6815
|
+
[`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
|
|
6816
|
+
]) {
|
|
6817
|
+
let rows = false;
|
|
6818
|
+
try {
|
|
6819
|
+
rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
|
|
6820
|
+
} catch (err) {
|
|
6821
|
+
report.failedStep = failedStep;
|
|
6822
|
+
throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
|
|
6823
|
+
}
|
|
6824
|
+
if (rows) {
|
|
6825
|
+
report.failedStep = failedStep;
|
|
6826
|
+
throw new EraseStepError(code, `erase stopped at step 3: ${table} holds undrained rows and the FTS index strategy cannot drain them; erasure is unverified`, report);
|
|
6827
|
+
}
|
|
6828
|
+
}
|
|
6829
|
+
for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
|
|
6830
|
+
let orphaned = false;
|
|
6831
|
+
try {
|
|
6832
|
+
orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
|
|
6833
|
+
} catch (err) {
|
|
6834
|
+
report.failedStep = "index_sync";
|
|
6835
|
+
throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
|
|
6836
|
+
}
|
|
6837
|
+
if (orphaned) {
|
|
6838
|
+
report.failedStep = "index_sync";
|
|
6839
|
+
throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
|
|
6840
|
+
}
|
|
6841
|
+
}
|
|
6842
|
+
}
|
|
6843
|
+
try {
|
|
6844
|
+
await this.searchService.drainEntriesLedgerSurfaced();
|
|
6845
|
+
} catch (err) {
|
|
6846
|
+
report.failedStep = "index_sync";
|
|
6847
|
+
throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
|
|
6848
|
+
}
|
|
6849
|
+
try {
|
|
6850
|
+
await this.searchService.drainPassagesSurfaced();
|
|
6851
|
+
} catch (err) {
|
|
6852
|
+
report.failedStep = "passage_drain";
|
|
6853
|
+
throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
|
|
6854
|
+
}
|
|
6855
|
+
}
|
|
6856
|
+
/**
|
|
6857
|
+
* Step 4 (and its re-run after step 6): reclaim retired FTS tables to
|
|
6858
|
+
* completion. A module-less runtime cannot DROP a virtual table, so each
|
|
6859
|
+
* retired table's shadow tables are emptied under the pragma and the name
|
|
6860
|
+
* stays listed; a later FTS5-capable open's step 4 completes the DROP.
|
|
6861
|
+
*/
|
|
6862
|
+
async _eraseReclaimRetired(report) {
|
|
6863
|
+
if (this.searchService.canReclaimRetired()) {
|
|
6864
|
+
try {
|
|
6865
|
+
await this.searchService.reclaimRetiredSurfaced();
|
|
6866
|
+
return;
|
|
6867
|
+
} catch (err) {
|
|
6868
|
+
if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
|
|
6869
|
+
report.failedStep = "retired_reclaim";
|
|
6870
|
+
throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
|
|
6871
|
+
}
|
|
6872
|
+
}
|
|
6873
|
+
}
|
|
6874
|
+
try {
|
|
6875
|
+
for (const name of await this._retiredList()) {
|
|
6876
|
+
for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
|
|
6877
|
+
if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
|
|
6878
|
+
}
|
|
6879
|
+
if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
|
|
6880
|
+
emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
|
|
6881
|
+
}
|
|
6882
|
+
} catch (err) {
|
|
6883
|
+
report.failedStep = "retired_reclaim";
|
|
6884
|
+
throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
|
|
6885
|
+
}
|
|
6886
|
+
}
|
|
6887
|
+
/** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
|
|
6888
|
+
async _retiredList() {
|
|
6889
|
+
let raw;
|
|
6890
|
+
try {
|
|
6891
|
+
raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
|
|
6892
|
+
} catch {
|
|
6893
|
+
return [];
|
|
6894
|
+
}
|
|
6895
|
+
return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
|
|
6896
|
+
}
|
|
6897
|
+
sourceTableExists(name) {
|
|
6898
|
+
return this.metadataRepo.tableExists(name);
|
|
6899
|
+
}
|
|
6900
|
+
/** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
|
|
6901
|
+
async _eraseSyncEntries(entityId, ids, report) {
|
|
6902
|
+
let ok = false;
|
|
6903
|
+
try {
|
|
6904
|
+
ok = await this.searchService.syncEntries(entityId, ids);
|
|
6905
|
+
} catch (err) {
|
|
6906
|
+
report.failedStep = "index_sync";
|
|
6907
|
+
throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
|
|
6908
|
+
}
|
|
6909
|
+
if (!ok) {
|
|
6910
|
+
report.failedStep = "index_sync";
|
|
6911
|
+
throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
|
|
6912
|
+
}
|
|
6913
|
+
}
|
|
6914
|
+
/** Step 7: FTS optimize on both FTS tables, after syncEntries. */
|
|
6915
|
+
async _eraseOptimize(report) {
|
|
6916
|
+
try {
|
|
6917
|
+
await this.searchService.optimizeSurfaced();
|
|
6918
|
+
} catch (err) {
|
|
6919
|
+
report.failedStep = "optimize";
|
|
6920
|
+
throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
|
|
6921
|
+
}
|
|
6922
|
+
}
|
|
6421
6923
|
async runLibrarian(entityId, options) {
|
|
6422
6924
|
this.jobManager.acquireLock("librarian", entityId);
|
|
6423
6925
|
try {
|
|
@@ -6538,6 +7040,9 @@ var MaintenanceService = class {
|
|
|
6538
7040
|
if (params.includeEvents && !params.clearAll) {
|
|
6539
7041
|
throw new Error("forget() includeEvents requires clearAll: true");
|
|
6540
7042
|
}
|
|
7043
|
+
if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
|
|
7044
|
+
throw new Error("forget() includeChain composes only with entryId");
|
|
7045
|
+
}
|
|
6541
7046
|
if (opts?.dryRun === true) {
|
|
6542
7047
|
return this.forgetDryRun(entityId, params);
|
|
6543
7048
|
}
|
|
@@ -6547,6 +7052,8 @@ var MaintenanceService = class {
|
|
|
6547
7052
|
let deletedEntries = 0;
|
|
6548
7053
|
let deletedTasks = 0;
|
|
6549
7054
|
let deletedEvents = 0;
|
|
7055
|
+
let chainIds = [];
|
|
7056
|
+
let chainTruncated = false;
|
|
6550
7057
|
const deletedEntryIds = [];
|
|
6551
7058
|
const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
|
|
6552
7059
|
await this.db.withTransactionAsync(async (tx) => {
|
|
@@ -6583,6 +7090,12 @@ var MaintenanceService = class {
|
|
|
6583
7090
|
if (params.entryId) {
|
|
6584
7091
|
const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
|
|
6585
7092
|
if (entryId) deletedEntryIds.push(entryId);
|
|
7093
|
+
if (entryId && params.includeChain) {
|
|
7094
|
+
const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
|
|
7095
|
+
chainIds = walk.ids.filter((id) => id !== entryId);
|
|
7096
|
+
chainTruncated = walk.truncated;
|
|
7097
|
+
for (const id of chainIds) deletedEntryIds.push(id);
|
|
7098
|
+
}
|
|
6586
7099
|
}
|
|
6587
7100
|
if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
|
|
6588
7101
|
const docs = `${this.prefix}source_documents`;
|
|
@@ -6608,6 +7121,9 @@ var MaintenanceService = class {
|
|
|
6608
7121
|
sourceRefIndexPromise ?? Promise.resolve(void 0)
|
|
6609
7122
|
]);
|
|
6610
7123
|
if (entryResult) deletedEntries++;
|
|
7124
|
+
for (const id of chainIds) {
|
|
7125
|
+
if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
|
|
7126
|
+
}
|
|
6611
7127
|
if (taskResult) deletedTasks++;
|
|
6612
7128
|
deletedEntries += refResult;
|
|
6613
7129
|
}
|
|
@@ -6661,7 +7177,17 @@ var MaintenanceService = class {
|
|
|
6661
7177
|
});
|
|
6662
7178
|
}
|
|
6663
7179
|
}
|
|
6664
|
-
if (!params.clearAll)
|
|
7180
|
+
if (!params.clearAll) {
|
|
7181
|
+
const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
|
|
7182
|
+
if (params.includeChain) {
|
|
7183
|
+
base.chainEntryIds = chainIds;
|
|
7184
|
+
if (chainTruncated) {
|
|
7185
|
+
base.truncated = true;
|
|
7186
|
+
base.notice = CHAIN_TRUNCATED_NOTICE;
|
|
7187
|
+
}
|
|
7188
|
+
}
|
|
7189
|
+
return base;
|
|
7190
|
+
}
|
|
6665
7191
|
return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
|
|
6666
7192
|
} finally {
|
|
6667
7193
|
this.jobManager.releaseLock("forget", entityId);
|
|
@@ -6727,8 +7253,25 @@ var MaintenanceService = class {
|
|
|
6727
7253
|
* (the spec keeps dry-run narrow).
|
|
6728
7254
|
*/
|
|
6729
7255
|
async forgetDryRun(entityId, params) {
|
|
7256
|
+
if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
|
|
7257
|
+
const id = await this.entryRepo.findIdById(params.entryId, entityId);
|
|
7258
|
+
if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
|
|
7259
|
+
const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
|
|
7260
|
+
const chainEntryIds = walk.ids.filter((c) => c !== id);
|
|
7261
|
+
const all = [id, ...chainEntryIds];
|
|
7262
|
+
const live = await this.db.getFirstAsync(
|
|
7263
|
+
`SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
|
|
7264
|
+
[entityId, ...all]
|
|
7265
|
+
);
|
|
7266
|
+
const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
|
|
7267
|
+
if (walk.truncated) {
|
|
7268
|
+
out.truncated = true;
|
|
7269
|
+
out.notice = CHAIN_TRUNCATED_NOTICE;
|
|
7270
|
+
}
|
|
7271
|
+
return out;
|
|
7272
|
+
}
|
|
6730
7273
|
if (params.entryId !== void 0 || params.taskId !== void 0) {
|
|
6731
|
-
throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
|
|
7274
|
+
throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
|
|
6732
7275
|
}
|
|
6733
7276
|
if (params.clearAll) {
|
|
6734
7277
|
const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
|
|
@@ -7931,7 +8474,8 @@ var ImportExportService = class {
|
|
|
7931
8474
|
this.vectorRemoval = vectorRemoval;
|
|
7932
8475
|
this.prefix = prefix;
|
|
7933
8476
|
}
|
|
7934
|
-
async exportDump(entityIds) {
|
|
8477
|
+
async exportDump(entityIds, opts) {
|
|
8478
|
+
const includeForgotten = opts?.includeForgotten === true;
|
|
7935
8479
|
let ids;
|
|
7936
8480
|
if (entityIds && entityIds.length > 0) {
|
|
7937
8481
|
ids = Array.from(new Set(entityIds));
|
|
@@ -7952,7 +8496,7 @@ var ImportExportService = class {
|
|
|
7952
8496
|
const batchResults = await Promise.all(
|
|
7953
8497
|
batch.map(
|
|
7954
8498
|
async (id) => {
|
|
7955
|
-
const bundle = await this.getFullBundle(id, { includeBlobs: true });
|
|
8499
|
+
const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
|
|
7956
8500
|
const storedSources = await this.exportStoredSources(id);
|
|
7957
8501
|
return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
|
|
7958
8502
|
}
|
|
@@ -8058,10 +8602,11 @@ var ImportExportService = class {
|
|
|
8058
8602
|
}
|
|
8059
8603
|
}
|
|
8060
8604
|
async getFullBundle(entityId, opts) {
|
|
8605
|
+
const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
|
|
8061
8606
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
8062
8607
|
const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
|
|
8063
|
-
opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
|
|
8064
|
-
this.taskRepo.findAllByEntityId(entityId),
|
|
8608
|
+
opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
|
|
8609
|
+
this.taskRepo.findAllByEntityId(entityId, void 0, incl),
|
|
8065
8610
|
this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
|
|
8066
8611
|
this.edgeRepo.getByEntityId(entityId),
|
|
8067
8612
|
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
|
|
@@ -8097,12 +8642,15 @@ var ImportExportService = class {
|
|
|
8097
8642
|
const skippedSources = [];
|
|
8098
8643
|
const refusalDiagnostics = [];
|
|
8099
8644
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
8645
|
+
const liveEmbedFactIds = /* @__PURE__ */ new Set();
|
|
8100
8646
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
8101
8647
|
const factsWithPreservedBlob = /* @__PURE__ */ new Map();
|
|
8102
8648
|
const preservedBlobDims = /* @__PURE__ */ new Set();
|
|
8103
8649
|
const softDeletedFactIds = [];
|
|
8650
|
+
const softDeletedTaskIds = [];
|
|
8104
8651
|
const clippedTextByFactId = /* @__PURE__ */ new Map();
|
|
8105
8652
|
let clampedEvents = 0;
|
|
8653
|
+
let tombstoneSkipped = 0;
|
|
8106
8654
|
const restamped = { behind_watermark: 0, invalid: 0 };
|
|
8107
8655
|
await this.db.withTransactionAsync(async (tx) => {
|
|
8108
8656
|
if (!merge) {
|
|
@@ -8113,8 +8661,9 @@ var ImportExportService = class {
|
|
|
8113
8661
|
tx,
|
|
8114
8662
|
false
|
|
8115
8663
|
);
|
|
8116
|
-
softDeletedFactIds.push(
|
|
8664
|
+
for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
|
|
8117
8665
|
await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
8666
|
+
for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
|
|
8118
8667
|
await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
8119
8668
|
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
8120
8669
|
await this.metadataRepo.deleteCheckpoint(entityId, tx);
|
|
@@ -8124,6 +8673,8 @@ var ImportExportService = class {
|
|
|
8124
8673
|
} else if (!merge) {
|
|
8125
8674
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
8126
8675
|
}
|
|
8676
|
+
const wipedByThisImport = new Set(softDeletedFactIds);
|
|
8677
|
+
const wipedTasksByThisImport = new Set(softDeletedTaskIds);
|
|
8127
8678
|
const factIds = bundle.facts.map((fact) => fact.id);
|
|
8128
8679
|
const existingFactsById = /* @__PURE__ */ new Map();
|
|
8129
8680
|
const existingFacts = await this.entryRepo.findExistingMetadataByIds(
|
|
@@ -8199,11 +8750,16 @@ var ImportExportService = class {
|
|
|
8199
8750
|
);
|
|
8200
8751
|
continue;
|
|
8201
8752
|
}
|
|
8202
|
-
if (
|
|
8753
|
+
if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
|
|
8754
|
+
tombstoneSkipped++;
|
|
8755
|
+
continue;
|
|
8756
|
+
}
|
|
8757
|
+
if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
|
|
8203
8758
|
}
|
|
8204
8759
|
const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
|
|
8205
8760
|
const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
|
|
8206
|
-
|
|
8761
|
+
const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
|
|
8762
|
+
clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
|
|
8207
8763
|
let normalizedSourceRef = null;
|
|
8208
8764
|
if (fact.source_ref !== null && fact.source_ref !== void 0) {
|
|
8209
8765
|
normalizedSourceRef = normalizeSourceRef(fact.source_ref);
|
|
@@ -8270,15 +8826,22 @@ var ImportExportService = class {
|
|
|
8270
8826
|
}, tx, { outbox: false });
|
|
8271
8827
|
if (blobData != null) {
|
|
8272
8828
|
factsWithPreservedBlob.set(fact.id, blobData);
|
|
8273
|
-
if (
|
|
8829
|
+
if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
|
|
8274
8830
|
}
|
|
8275
8831
|
existingFactsById.set(fact.id, {
|
|
8276
8832
|
id: fact.id,
|
|
8277
8833
|
entity_id: entityId,
|
|
8278
|
-
updated_at: safeUpdatedAt
|
|
8834
|
+
updated_at: safeUpdatedAt,
|
|
8835
|
+
deleted_at: fact.deleted_at ?? null
|
|
8279
8836
|
});
|
|
8837
|
+
wipedByThisImport.delete(fact.id);
|
|
8280
8838
|
upsertedFactIds.add(fact.id);
|
|
8281
|
-
if (fact.deleted_at)
|
|
8839
|
+
if (fact.deleted_at != null) {
|
|
8840
|
+
upsertedDeletedFactIds.add(fact.id);
|
|
8841
|
+
liveEmbedFactIds.delete(fact.id);
|
|
8842
|
+
} else {
|
|
8843
|
+
liveEmbedFactIds.add(fact.id);
|
|
8844
|
+
}
|
|
8282
8845
|
}
|
|
8283
8846
|
const taskIds = bundle.tasks.map((task) => task.id);
|
|
8284
8847
|
const existingTasksById = /* @__PURE__ */ new Map();
|
|
@@ -8302,7 +8865,11 @@ var ImportExportService = class {
|
|
|
8302
8865
|
);
|
|
8303
8866
|
continue;
|
|
8304
8867
|
}
|
|
8305
|
-
if (
|
|
8868
|
+
if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
|
|
8869
|
+
tombstoneSkipped++;
|
|
8870
|
+
continue;
|
|
8871
|
+
}
|
|
8872
|
+
if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
|
|
8306
8873
|
}
|
|
8307
8874
|
await this.taskRepo.upsertForImport(
|
|
8308
8875
|
{
|
|
@@ -8335,8 +8902,10 @@ var ImportExportService = class {
|
|
|
8335
8902
|
existingTasksById.set(task.id, {
|
|
8336
8903
|
id: task.id,
|
|
8337
8904
|
entity_id: entityId,
|
|
8338
|
-
updated_at: safeUpdatedAt
|
|
8905
|
+
updated_at: safeUpdatedAt,
|
|
8906
|
+
deleted_at: task.deleted_at ?? null
|
|
8339
8907
|
});
|
|
8908
|
+
wipedTasksByThisImport.delete(task.id);
|
|
8340
8909
|
}
|
|
8341
8910
|
const now = Date.now();
|
|
8342
8911
|
const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
|
|
@@ -8376,6 +8945,15 @@ var ImportExportService = class {
|
|
|
8376
8945
|
await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
|
|
8377
8946
|
});
|
|
8378
8947
|
for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
|
|
8948
|
+
if (tombstoneSkipped > 0) {
|
|
8949
|
+
emitDiagnostic(this.options, {
|
|
8950
|
+
code: "import_tombstone_skipped",
|
|
8951
|
+
operation: "importDump",
|
|
8952
|
+
trigger: "call",
|
|
8953
|
+
entityId,
|
|
8954
|
+
detail: { count: tombstoneSkipped }
|
|
8955
|
+
});
|
|
8956
|
+
}
|
|
8379
8957
|
if (clampedEvents > 0) {
|
|
8380
8958
|
emitDiagnostic(this.options, {
|
|
8381
8959
|
code: "event_created_at_clamped",
|
|
@@ -8401,28 +8979,28 @@ var ImportExportService = class {
|
|
|
8401
8979
|
} else {
|
|
8402
8980
|
await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
|
|
8403
8981
|
}
|
|
8404
|
-
for (const
|
|
8405
|
-
if (!
|
|
8406
|
-
const clipped = clippedTextByFactId.get(
|
|
8982
|
+
for (const id of liveEmbedFactIds) {
|
|
8983
|
+
if (!factsWithPreservedBlob.has(id)) {
|
|
8984
|
+
const clipped = clippedTextByFactId.get(id);
|
|
8407
8985
|
const embedded = await this.embeddingService.embedFact({
|
|
8408
|
-
id
|
|
8986
|
+
id,
|
|
8409
8987
|
entity_id: entityId,
|
|
8410
|
-
title: clipped?.title ??
|
|
8411
|
-
body: clipped?.body ??
|
|
8412
|
-
tags:
|
|
8988
|
+
title: clipped?.title ?? "",
|
|
8989
|
+
body: clipped?.body ?? "",
|
|
8990
|
+
tags: clipped?.tags ?? []
|
|
8413
8991
|
}, { operation: "importDump", trigger: "call" });
|
|
8414
8992
|
if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
8415
8993
|
try {
|
|
8416
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId,
|
|
8994
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
|
|
8417
8995
|
} catch (hookErr) {
|
|
8418
8996
|
console.warn(
|
|
8419
|
-
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${
|
|
8997
|
+
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
|
|
8420
8998
|
hookErr
|
|
8421
8999
|
);
|
|
8422
9000
|
this.embeddingService.reportHookFailed(
|
|
8423
9001
|
{ operation: "importDump", trigger: "call" },
|
|
8424
9002
|
entityId,
|
|
8425
|
-
|
|
9003
|
+
id
|
|
8426
9004
|
);
|
|
8427
9005
|
}
|
|
8428
9006
|
}
|
|
@@ -8430,7 +9008,7 @@ var ImportExportService = class {
|
|
|
8430
9008
|
}
|
|
8431
9009
|
for (const fact of bundle.facts) {
|
|
8432
9010
|
const blobData = factsWithPreservedBlob.get(fact.id);
|
|
8433
|
-
if (blobData &&
|
|
9011
|
+
if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
|
|
8434
9012
|
try {
|
|
8435
9013
|
const float32Vector = new Float32Array(
|
|
8436
9014
|
blobData.buffer,
|
|
@@ -9990,6 +10568,6 @@ var WriteService = class {
|
|
|
9990
10568
|
}
|
|
9991
10569
|
};
|
|
9992
10570
|
|
|
9993
|
-
export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
9994
|
-
//# sourceMappingURL=chunk-
|
|
9995
|
-
//# sourceMappingURL=chunk-
|
|
10571
|
+
export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
10572
|
+
//# sourceMappingURL=chunk-H436I7OM.mjs.map
|
|
10573
|
+
//# sourceMappingURL=chunk-H436I7OM.mjs.map
|