@equationalapplications/core-llm-wiki 9.1.0 → 9.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SIJD5GEF.mjs → chunk-H436I7OM.mjs} +1832 -496
- package/dist/chunk-H436I7OM.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2161 -404
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +655 -236
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-CmcCGx0_.d.mts → testing-DsD-idCv.d.mts} +401 -29
- package/dist/{testing-CmcCGx0_.d.ts → testing-DsD-idCv.d.ts} +401 -29
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1298 -173
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-SIJD5GEF.mjs.map +0 -1
|
@@ -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) {
|
|
@@ -1014,6 +1281,10 @@ var UnavailableIndexStrategy = class {
|
|
|
1014
1281
|
}
|
|
1015
1282
|
async drain(_opts) {
|
|
1016
1283
|
}
|
|
1284
|
+
/** Degraded like everything else: no passages, no throw (spec source-store section 7). */
|
|
1285
|
+
async searchPassages() {
|
|
1286
|
+
return [];
|
|
1287
|
+
}
|
|
1017
1288
|
};
|
|
1018
1289
|
|
|
1019
1290
|
// src/services/SearchService.ts
|
|
@@ -1236,25 +1507,110 @@ var _SearchService = class _SearchService {
|
|
|
1236
1507
|
return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
|
|
1237
1508
|
}
|
|
1238
1509
|
/**
|
|
1239
|
-
*
|
|
1510
|
+
* Post-commit passage index sync (spec source-store section 6). FTS5: drains the
|
|
1511
|
+
* passage ledger (per document, entity-scoped when given). MiniSearch: reloads
|
|
1512
|
+
* the entity's stored passages (all stored entities when omitted: the open-time
|
|
1513
|
+
* pass). Serialized on the sync chain; never rejects, like sync().
|
|
1240
1514
|
*/
|
|
1241
|
-
async
|
|
1242
|
-
const
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1515
|
+
async syncPassages(db, prefix, entityId, deadline) {
|
|
1516
|
+
const s = this.indexStrategy;
|
|
1517
|
+
if (!s.drainPassages && !s.reindexSourcePassages) return;
|
|
1518
|
+
const work = this.syncChain.then(async () => {
|
|
1519
|
+
try {
|
|
1520
|
+
if (s.drainPassages) await s.drainPassages({ entityId, deadline });
|
|
1521
|
+
else await s.reindexSourcePassages(db, prefix, entityId);
|
|
1522
|
+
} catch (err) {
|
|
1523
|
+
console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
|
|
1524
|
+
}
|
|
1525
|
+
});
|
|
1526
|
+
this.syncChain = work;
|
|
1527
|
+
return work;
|
|
1247
1528
|
}
|
|
1248
|
-
/**
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
const
|
|
1257
|
-
|
|
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
|
+
}
|
|
1584
|
+
/**
|
|
1585
|
+
* Stored-source passage search for ONE entity (spec source-store section 7:
|
|
1586
|
+
* ranking and caps are per entity). Rides the active strategy; a strategy
|
|
1587
|
+
* without passage search yields none.
|
|
1588
|
+
*/
|
|
1589
|
+
async searchPassages(query, entityId, limit) {
|
|
1590
|
+
if (!this.indexStrategy.searchPassages) return [];
|
|
1591
|
+
const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
|
|
1592
|
+
return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
|
|
1593
|
+
}
|
|
1594
|
+
/**
|
|
1595
|
+
* Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
|
|
1596
|
+
*/
|
|
1597
|
+
async getKeywordScores(query, entityIds, preFilterLimit) {
|
|
1598
|
+
const opts = preFilterLimit !== void 0 ? { entityIds, limit: preFilterLimit, preFilterLimit } : { entityIds, limit: Number.MAX_SAFE_INTEGER };
|
|
1599
|
+
const results = finiteResults(await this.indexStrategy.search(query, opts));
|
|
1600
|
+
if (results.length === 0) return /* @__PURE__ */ new Map();
|
|
1601
|
+
const maxScore = Math.max(1, results[0]?.score ?? 1);
|
|
1602
|
+
return new Map(results.map((r) => [r.id, r.score / maxScore]));
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* Score candidate rows using in-process JS cosine similarity.
|
|
1606
|
+
* Applies hybrid blending (if weight set) and tie-break sorting before returning.
|
|
1607
|
+
*/
|
|
1608
|
+
async rankSemantic(args) {
|
|
1609
|
+
const queryVec = args.queryVec instanceof Float32Array ? args.queryVec.slice() : Array.from(args.queryVec);
|
|
1610
|
+
const { entityId, candidateRows, weight, miniSearchScores, populateCache, limit, skipSort } = args;
|
|
1611
|
+
let entityCache = this.vectorCache.get(entityId);
|
|
1612
|
+
const tooLarge = populateCache && candidateRows.length > _SearchService.MAX_VECTOR_CACHE_FACTS_PER_ENTITY;
|
|
1613
|
+
if (tooLarge && entityCache) {
|
|
1258
1614
|
this.vectorCache.delete(entityId);
|
|
1259
1615
|
entityCache = void 0;
|
|
1260
1616
|
}
|
|
@@ -1380,7 +1736,7 @@ var JobManager = class {
|
|
|
1380
1736
|
this.statusSubscribers = /* @__PURE__ */ new Map();
|
|
1381
1737
|
/**
|
|
1382
1738
|
* Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
|
|
1383
|
-
* Excludes 'ingest' | 'global_reembed' | 'global_import', which those
|
|
1739
|
+
* Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
|
|
1384
1740
|
* methods already handle via explicit if/else branches before reaching
|
|
1385
1741
|
* this table.
|
|
1386
1742
|
*/
|
|
@@ -1391,7 +1747,8 @@ var JobManager = class {
|
|
|
1391
1747
|
reembed: (id) => this._reembedKey(id),
|
|
1392
1748
|
import: (id) => this._importKey(id),
|
|
1393
1749
|
forget: (id) => this._forgetKey(id),
|
|
1394
|
-
ontologyBackfill: (id) => this._ontologyBackfillKey(id)
|
|
1750
|
+
ontologyBackfill: (id) => this._ontologyBackfillKey(id),
|
|
1751
|
+
store: (id) => this._storeKey(id)
|
|
1395
1752
|
};
|
|
1396
1753
|
}
|
|
1397
1754
|
_hashLockKey(entityId, sourceHash) {
|
|
@@ -1448,6 +1805,9 @@ var JobManager = class {
|
|
|
1448
1805
|
_globalReembedKey() {
|
|
1449
1806
|
return `${this.prefix}:reembed`;
|
|
1450
1807
|
}
|
|
1808
|
+
_eraseKey() {
|
|
1809
|
+
return `${this.prefix}:erase`;
|
|
1810
|
+
}
|
|
1451
1811
|
_importKey(entityId) {
|
|
1452
1812
|
return `${this.prefix}:${entityId}:import`;
|
|
1453
1813
|
}
|
|
@@ -1460,6 +1820,9 @@ var JobManager = class {
|
|
|
1460
1820
|
_librarianKey(entityId) {
|
|
1461
1821
|
return `${this.prefix}:${entityId}:librarian`;
|
|
1462
1822
|
}
|
|
1823
|
+
_storeKey(entityId) {
|
|
1824
|
+
return `${this.prefix}:${entityId}:store`;
|
|
1825
|
+
}
|
|
1463
1826
|
_healKey(entityId) {
|
|
1464
1827
|
return `${this.prefix}:${entityId}:heal`;
|
|
1465
1828
|
}
|
|
@@ -1488,6 +1851,9 @@ var JobManager = class {
|
|
|
1488
1851
|
_isImportActiveFor(entityId) {
|
|
1489
1852
|
return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
|
|
1490
1853
|
}
|
|
1854
|
+
_isStoreActiveFor(entityId) {
|
|
1855
|
+
return this.activeMaintenanceJobs.has(this._storeKey(entityId));
|
|
1856
|
+
}
|
|
1491
1857
|
_isForgetActiveFor(entityId) {
|
|
1492
1858
|
return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
|
|
1493
1859
|
}
|
|
@@ -1522,11 +1888,19 @@ var JobManager = class {
|
|
|
1522
1888
|
_isIngestActiveFor(entityId) {
|
|
1523
1889
|
return this.activeIngestJobs.has(entityId);
|
|
1524
1890
|
}
|
|
1525
|
-
|
|
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") {
|
|
1526
1897
|
let blockingOperation = null;
|
|
1527
1898
|
if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
|
|
1528
1899
|
throw new WikiBusyError("import", "*");
|
|
1529
1900
|
}
|
|
1901
|
+
if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
|
|
1902
|
+
throw new WikiBusyError("erase", "*");
|
|
1903
|
+
}
|
|
1530
1904
|
switch (operation) {
|
|
1531
1905
|
case "prune":
|
|
1532
1906
|
if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
|
|
@@ -1537,6 +1911,7 @@ var JobManager = class {
|
|
|
1537
1911
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
1538
1912
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1539
1913
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
1914
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1540
1915
|
break;
|
|
1541
1916
|
case "librarian":
|
|
1542
1917
|
case "heal":
|
|
@@ -1547,6 +1922,7 @@ var JobManager = class {
|
|
|
1547
1922
|
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
1548
1923
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1549
1924
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
1925
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1550
1926
|
break;
|
|
1551
1927
|
}
|
|
1552
1928
|
case "reembed":
|
|
@@ -1559,6 +1935,7 @@ var JobManager = class {
|
|
|
1559
1935
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
1560
1936
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1561
1937
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
1938
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1562
1939
|
break;
|
|
1563
1940
|
case "global_reembed":
|
|
1564
1941
|
if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
|
|
@@ -1570,6 +1947,19 @@ var JobManager = class {
|
|
|
1570
1947
|
else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
|
|
1571
1948
|
else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
|
|
1572
1949
|
else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
|
|
1950
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
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";
|
|
1573
1963
|
break;
|
|
1574
1964
|
case "import":
|
|
1575
1965
|
case "forget": {
|
|
@@ -1583,10 +1973,23 @@ var JobManager = class {
|
|
|
1583
1973
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
1584
1974
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1585
1975
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
1976
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1586
1977
|
break;
|
|
1587
1978
|
}
|
|
1979
|
+
case "store":
|
|
1980
|
+
if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1981
|
+
else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
|
|
1982
|
+
else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
|
|
1983
|
+
else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
|
|
1984
|
+
else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
|
|
1985
|
+
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
1986
|
+
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
1987
|
+
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1988
|
+
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
1989
|
+
break;
|
|
1588
1990
|
case "global_import":
|
|
1589
1991
|
if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
|
|
1992
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
1590
1993
|
break;
|
|
1591
1994
|
case "ingest": {
|
|
1592
1995
|
const sourceKey = sourceRef ?? "";
|
|
@@ -1595,13 +1998,14 @@ var JobManager = class {
|
|
|
1595
1998
|
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
1596
1999
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
1597
2000
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
2001
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
1598
2002
|
break;
|
|
1599
2003
|
}
|
|
1600
2004
|
}
|
|
1601
2005
|
if (blockingOperation) {
|
|
1602
2006
|
throw new WikiBusyError(
|
|
1603
2007
|
blockingOperation,
|
|
1604
|
-
operation === "global_reembed" || operation === "global_import" ? "*" : entityId
|
|
2008
|
+
operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
|
|
1605
2009
|
);
|
|
1606
2010
|
}
|
|
1607
2011
|
if (operation === "ingest") {
|
|
@@ -1610,6 +2014,8 @@ var JobManager = class {
|
|
|
1610
2014
|
this.activeMaintenanceJobs.add(this._globalReembedKey());
|
|
1611
2015
|
} else if (operation === "global_import") {
|
|
1612
2016
|
this.activeMaintenanceJobs.add(this._globalImportKey());
|
|
2017
|
+
} else if (operation === "erase") {
|
|
2018
|
+
this.activeMaintenanceJobs.add(this._eraseKey());
|
|
1613
2019
|
} else {
|
|
1614
2020
|
this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
|
|
1615
2021
|
}
|
|
@@ -1622,6 +2028,8 @@ var JobManager = class {
|
|
|
1622
2028
|
this.activeMaintenanceJobs.delete(this._globalReembedKey());
|
|
1623
2029
|
} else if (operation === "global_import") {
|
|
1624
2030
|
this.activeMaintenanceJobs.delete(this._globalImportKey());
|
|
2031
|
+
} else if (operation === "erase") {
|
|
2032
|
+
this.activeMaintenanceJobs.delete(this._eraseKey());
|
|
1625
2033
|
} else {
|
|
1626
2034
|
this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
|
|
1627
2035
|
}
|
|
@@ -1633,26 +2041,31 @@ var JobManager = class {
|
|
|
1633
2041
|
*/
|
|
1634
2042
|
isBlocked(operation, entityId) {
|
|
1635
2043
|
if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
|
|
2044
|
+
if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
|
|
1636
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");
|
|
1637
2048
|
case "librarian":
|
|
1638
2049
|
case "heal":
|
|
1639
2050
|
case "ontologyBackfill":
|
|
1640
|
-
return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
2051
|
+
return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
1641
2052
|
case "prune":
|
|
1642
|
-
return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
2053
|
+
return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
1643
2054
|
case "reembed":
|
|
1644
|
-
return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
2055
|
+
return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
1645
2056
|
case "global_reembed":
|
|
1646
|
-
return this.activeMaintenanceJobs.has(this._globalReembedKey()) || 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");
|
|
2057
|
+
return this.activeMaintenanceJobs.has(this._globalReembedKey()) || 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");
|
|
1647
2058
|
case "import":
|
|
1648
2059
|
case "forget": {
|
|
1649
2060
|
const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
|
|
1650
|
-
return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
2061
|
+
return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
1651
2062
|
}
|
|
2063
|
+
case "store":
|
|
2064
|
+
return this._isStoreActiveFor(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
1652
2065
|
case "global_import":
|
|
1653
|
-
return this.activeMaintenanceJobs.has(this._globalImportKey());
|
|
2066
|
+
return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
|
|
1654
2067
|
case "ingest":
|
|
1655
|
-
return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
2068
|
+
return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
1656
2069
|
default:
|
|
1657
2070
|
return false;
|
|
1658
2071
|
}
|
|
@@ -1665,6 +2078,7 @@ var JobManager = class {
|
|
|
1665
2078
|
*/
|
|
1666
2079
|
tryAcquireAutoHealLock(entityId) {
|
|
1667
2080
|
if (this.isAnyReembedActive()) return false;
|
|
2081
|
+
if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
|
|
1668
2082
|
const healKey = this._healKey(entityId);
|
|
1669
2083
|
if (this.activeMaintenanceJobs.has(healKey)) return false;
|
|
1670
2084
|
this.activeMaintenanceJobs.add(healKey);
|
|
@@ -1708,6 +2122,7 @@ var JobManager = class {
|
|
|
1708
2122
|
* Validates all entities before acquiring any lock (same as current importDump semantics).
|
|
1709
2123
|
*/
|
|
1710
2124
|
acquireImportLocks(entityIds) {
|
|
2125
|
+
if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
|
|
1711
2126
|
for (const entityId of entityIds) {
|
|
1712
2127
|
if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
|
|
1713
2128
|
if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
|
|
@@ -1717,6 +2132,7 @@ var JobManager = class {
|
|
|
1717
2132
|
if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
|
|
1718
2133
|
if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
|
|
1719
2134
|
if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
|
|
2135
|
+
if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
|
|
1720
2136
|
}
|
|
1721
2137
|
if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
|
|
1722
2138
|
this.activeMaintenanceJobs.add(this._globalImportKey());
|
|
@@ -2275,6 +2691,15 @@ var SEVERITY = {
|
|
|
2275
2691
|
resolve_failed: "warn",
|
|
2276
2692
|
read_budget: "info",
|
|
2277
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",
|
|
2278
2703
|
event_created_at_clamped: "warn",
|
|
2279
2704
|
event_created_at_restamped: "info",
|
|
2280
2705
|
external_deletion_pending: "warn",
|
|
@@ -2282,7 +2707,12 @@ var SEVERITY = {
|
|
|
2282
2707
|
guidance_too_long: "warn",
|
|
2283
2708
|
guidance_resolver_failed: "warn",
|
|
2284
2709
|
source_pointer_unresolved: "warn",
|
|
2285
|
-
source_pointer_invalid: "warn"
|
|
2710
|
+
source_pointer_invalid: "warn",
|
|
2711
|
+
source_store_source_too_large: "warn",
|
|
2712
|
+
source_store_budget_exceeded: "warn",
|
|
2713
|
+
source_store_hash_mismatch: "warn",
|
|
2714
|
+
source_store_duplicate_hash: "warn",
|
|
2715
|
+
source_store_text_not_storable: "warn"
|
|
2286
2716
|
};
|
|
2287
2717
|
var MESSAGE = {
|
|
2288
2718
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -2305,6 +2735,15 @@ var MESSAGE = {
|
|
|
2305
2735
|
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
2306
2736
|
read_budget: "A read was packed to a token budget.",
|
|
2307
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.",
|
|
2308
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.",
|
|
2309
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.",
|
|
2310
2749
|
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
@@ -2312,7 +2751,12 @@ var MESSAGE = {
|
|
|
2312
2751
|
guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
|
|
2313
2752
|
guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
|
|
2314
2753
|
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
|
|
2315
|
-
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
|
|
2754
|
+
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
|
|
2755
|
+
source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
|
|
2756
|
+
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
2757
|
+
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
2758
|
+
source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
|
|
2759
|
+
source_store_text_not_storable: "A source document text could not be stored as given."
|
|
2316
2760
|
};
|
|
2317
2761
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
2318
2762
|
function copyDetail(detail) {
|
|
@@ -3178,6 +3622,112 @@ function classifierStateForFact(fact) {
|
|
|
3178
3622
|
return parts.join("\n\n");
|
|
3179
3623
|
}
|
|
3180
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
|
+
};
|
|
3730
|
+
|
|
3181
3731
|
// src/utils/engineDefaults.ts
|
|
3182
3732
|
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
3183
3733
|
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
@@ -3216,21 +3766,6 @@ function warnChangedDefaultsOnce(config) {
|
|
|
3216
3766
|
}
|
|
3217
3767
|
}
|
|
3218
3768
|
|
|
3219
|
-
// src/repositories/BaseRepository.ts
|
|
3220
|
-
var BaseRepository = class {
|
|
3221
|
-
constructor(db, prefix) {
|
|
3222
|
-
this.db = db;
|
|
3223
|
-
this.prefix = prefix;
|
|
3224
|
-
}
|
|
3225
|
-
/**
|
|
3226
|
-
* Return the DB executor for a given transaction handle.
|
|
3227
|
-
* If tx is provided, use it; otherwise fall back to this.db.
|
|
3228
|
-
*/
|
|
3229
|
-
getExecutor(tx) {
|
|
3230
|
-
return tx ?? this.db;
|
|
3231
|
-
}
|
|
3232
|
-
};
|
|
3233
|
-
|
|
3234
3769
|
// src/repositories/VectorRemovalRepository.ts
|
|
3235
3770
|
var CHUNK = 500;
|
|
3236
3771
|
function removalBackoffMs(attempts) {
|
|
@@ -3768,24 +4303,6 @@ function withBudget(p, ms) {
|
|
|
3768
4303
|
});
|
|
3769
4304
|
}
|
|
3770
4305
|
|
|
3771
|
-
// src/utils/temporal.ts
|
|
3772
|
-
function liveAtSql(mode, alias = "") {
|
|
3773
|
-
const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
|
|
3774
|
-
return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
|
|
3775
|
-
}
|
|
3776
|
-
function isLiveAt(f, mode, t) {
|
|
3777
|
-
if (f.deleted_at != null) return false;
|
|
3778
|
-
const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
|
|
3779
|
-
if (from != null && from > t) return false;
|
|
3780
|
-
return f.valid_to == null || f.valid_to > t;
|
|
3781
|
-
}
|
|
3782
|
-
function assertEpochMs(name, v) {
|
|
3783
|
-
if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
|
|
3784
|
-
throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
|
|
3785
|
-
}
|
|
3786
|
-
return Math.trunc(v);
|
|
3787
|
-
}
|
|
3788
|
-
|
|
3789
4306
|
// src/repositories/EdgeRepository.ts
|
|
3790
4307
|
var CONFIDENCE_RANK = {
|
|
3791
4308
|
tentative: 0,
|
|
@@ -3862,309 +4379,106 @@ var EdgeRepository = class extends BaseRepository {
|
|
|
3862
4379
|
/**
|
|
3863
4380
|
* Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
|
|
3864
4381
|
* dead-ending, cycle-guarding, capping, and ordering happens in this one query.
|
|
3865
|
-
* The anchor is validated (exists, right entity, not soft-deleted) but never gated
|
|
3866
|
-
* by confidence/source_type — only nodes discovered beyond it are.
|
|
3867
|
-
*/
|
|
3868
|
-
async getNeighborhood(entityId, sourceId, opts, tx) {
|
|
3869
|
-
const executor = this.getExecutor(tx);
|
|
3870
|
-
if (opts.edgeTypes && opts.edgeTypes.length === 0) {
|
|
3871
|
-
const anchor = await executor.getFirstAsync(
|
|
3872
|
-
`SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
|
|
3873
|
-
[sourceId, entityId]
|
|
3874
|
-
);
|
|
3875
|
-
return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
|
|
3876
|
-
}
|
|
3877
|
-
const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
|
|
3878
|
-
const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
|
|
3879
|
-
const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
|
|
3880
|
-
const sql = `
|
|
3881
|
-
WITH RECURSIVE walk(node_id, depth, visited) AS (
|
|
3882
|
-
SELECT id, 0, ',' || id || ','
|
|
3883
|
-
FROM ${this.prefix}entries
|
|
3884
|
-
WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
|
|
3885
|
-
|
|
3886
|
-
UNION
|
|
3887
|
-
|
|
3888
|
-
SELECT
|
|
3889
|
-
CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
|
|
3890
|
-
w.depth + 1,
|
|
3891
|
-
w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
|
|
3892
|
-
FROM walk w
|
|
3893
|
-
JOIN ${this.prefix}edges e
|
|
3894
|
-
ON e.entity_id = ?
|
|
3895
|
-
AND (
|
|
3896
|
-
(? != 'inbound' AND e.source_id = w.node_id) OR
|
|
3897
|
-
(? != 'outbound' AND e.target_id = w.node_id)
|
|
3898
|
-
)
|
|
3899
|
-
AND (${edgeTypesClause})
|
|
3900
|
-
JOIN ${this.prefix}entries n
|
|
3901
|
-
ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
|
|
3902
|
-
AND n.entity_id = ?
|
|
3903
|
-
AND n.deleted_at IS NULL
|
|
3904
|
-
AND (
|
|
3905
|
-
CASE n.confidence
|
|
3906
|
-
WHEN 'tentative' THEN 0
|
|
3907
|
-
WHEN 'inferred' THEN 1
|
|
3908
|
-
WHEN 'certain' THEN 2
|
|
3909
|
-
ELSE -1
|
|
3910
|
-
END
|
|
3911
|
-
) >= ?
|
|
3912
|
-
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
3913
|
-
AND (? = 0 OR n.lifecycle_status != 'draft')
|
|
3914
|
-
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
3915
|
-
WHERE w.depth < ?
|
|
3916
|
-
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
3917
|
-
)
|
|
3918
|
-
SELECT node_id, MIN(depth) AS depth
|
|
3919
|
-
FROM walk
|
|
3920
|
-
GROUP BY node_id
|
|
3921
|
-
ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
|
|
3922
|
-
LIMIT ?
|
|
3923
|
-
`;
|
|
3924
|
-
const params = [
|
|
3925
|
-
sourceId,
|
|
3926
|
-
entityId,
|
|
3927
|
-
entityId,
|
|
3928
|
-
opts.direction,
|
|
3929
|
-
opts.direction,
|
|
3930
|
-
...opts.edgeTypes ?? [],
|
|
3931
|
-
entityId,
|
|
3932
|
-
minConfidenceRank,
|
|
3933
|
-
...opts.excludeSourceTypes,
|
|
3934
|
-
opts.excludeDrafts === true ? 1 : 0,
|
|
3935
|
-
opts.live.t,
|
|
3936
|
-
opts.live.t,
|
|
3937
|
-
opts.maxDepth,
|
|
3938
|
-
opts.maxNodes
|
|
3939
|
-
];
|
|
3940
|
-
const rows = await executor.getAllAsync(sql, params);
|
|
3941
|
-
const nodeIds = rows.map((r) => r.node_id);
|
|
3942
|
-
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
3943
|
-
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
3944
|
-
const edgeRows = await executor.getAllAsync(
|
|
3945
|
-
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
3946
|
-
SELECT e.* FROM ${this.prefix}edges e
|
|
3947
|
-
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
3948
|
-
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
3949
|
-
WHERE e.entity_id = ?`,
|
|
3950
|
-
[...nodeIds, entityId]
|
|
3951
|
-
);
|
|
3952
|
-
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
3953
|
-
}
|
|
3954
|
-
};
|
|
3955
|
-
function mapRowToEdge(row) {
|
|
3956
|
-
return {
|
|
3957
|
-
id: String(row.id),
|
|
3958
|
-
entity_id: String(row.entity_id),
|
|
3959
|
-
source_id: String(row.source_id),
|
|
3960
|
-
target_id: String(row.target_id),
|
|
3961
|
-
edge_type: String(row.edge_type),
|
|
3962
|
-
created_at: Number(row.created_at)
|
|
3963
|
-
};
|
|
3964
|
-
}
|
|
3965
|
-
|
|
3966
|
-
// src/repositories/MetadataRepository.ts
|
|
3967
|
-
function entitySummaryMetaKey(entityId) {
|
|
3968
|
-
return `entity_summary:${entityId}`;
|
|
3969
|
-
}
|
|
3970
|
-
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
3971
|
-
var MetadataRepository = class extends BaseRepository {
|
|
3972
|
-
// CHECKPOINTS TABLE METHODS
|
|
3973
|
-
async getCheckpoint(entityId, tx) {
|
|
3974
|
-
const executor = this.getExecutor(tx);
|
|
3975
|
-
const row = await executor.getFirstAsync(
|
|
3976
|
-
`SELECT memory_checkpoint, heal_checkpoint FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
3977
|
-
[entityId]
|
|
3978
|
-
);
|
|
3979
|
-
if (!row) return {};
|
|
3980
|
-
return {
|
|
3981
|
-
memory: row.memory_checkpoint ?? void 0,
|
|
3982
|
-
heal: row.heal_checkpoint ?? void 0
|
|
3983
|
-
};
|
|
3984
|
-
}
|
|
3985
|
-
async updateCheckpoint(entityId, updates, tx) {
|
|
3986
|
-
const fields = [];
|
|
3987
|
-
const values = [];
|
|
3988
|
-
if (updates.memory !== void 0) {
|
|
3989
|
-
fields.push("memory_checkpoint = ?");
|
|
3990
|
-
values.push(updates.memory);
|
|
3991
|
-
}
|
|
3992
|
-
if (updates.heal !== void 0) {
|
|
3993
|
-
fields.push("heal_checkpoint = ?");
|
|
3994
|
-
values.push(updates.heal);
|
|
3995
|
-
}
|
|
3996
|
-
if (fields.length === 0) return;
|
|
3997
|
-
const executor = this.getExecutor(tx);
|
|
3998
|
-
await executor.runAsync(
|
|
3999
|
-
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint)
|
|
4000
|
-
VALUES (?, ?, ?)
|
|
4001
|
-
ON CONFLICT(entity_id) DO UPDATE SET ${fields.join(", ")}`,
|
|
4002
|
-
[entityId, updates.memory ?? 0, updates.heal ?? 0, ...values]
|
|
4003
|
-
);
|
|
4004
|
-
}
|
|
4005
|
-
async deleteCheckpoint(entityId, tx) {
|
|
4006
|
-
const executor = this.getExecutor(tx);
|
|
4007
|
-
await executor.runAsync(
|
|
4008
|
-
`DELETE FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
4009
|
-
[entityId]
|
|
4010
|
-
);
|
|
4011
|
-
}
|
|
4012
|
-
/**
|
|
4013
|
-
* Read the op-based librarian's high-water mark. Returns `null` when the
|
|
4014
|
-
* entity has never had its watermark set.
|
|
4015
|
-
*/
|
|
4016
|
-
async getLibrarianWatermark(entityId, tx) {
|
|
4017
|
-
const executor = this.getExecutor(tx);
|
|
4018
|
-
const row = await executor.getFirstAsync(
|
|
4019
|
-
`SELECT librarian_watermark_at, librarian_watermark_id FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
|
|
4020
|
-
[entityId]
|
|
4021
|
-
);
|
|
4022
|
-
if (!row || row.librarian_watermark_at == null || row.librarian_watermark_id == null) {
|
|
4023
|
-
return null;
|
|
4024
|
-
}
|
|
4025
|
-
return { at: row.librarian_watermark_at, id: row.librarian_watermark_id };
|
|
4026
|
-
}
|
|
4027
|
-
/**
|
|
4028
|
-
* Write the op-based librarian's high-water mark. Uses `ON CONFLICT`
|
|
4029
|
-
* `DO UPDATE` so existing `memory_checkpoint` / `heal_checkpoint` rows
|
|
4030
|
-
* are preserved verbatim.
|
|
4031
|
-
*/
|
|
4032
|
-
async setLibrarianWatermark(entityId, wm, tx) {
|
|
4033
|
-
const executor = this.getExecutor(tx);
|
|
4034
|
-
await executor.runAsync(
|
|
4035
|
-
`INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint, librarian_watermark_at, librarian_watermark_id)
|
|
4036
|
-
VALUES (?, 0, 0, ?, ?)
|
|
4037
|
-
ON CONFLICT(entity_id) DO UPDATE SET
|
|
4038
|
-
librarian_watermark_at = excluded.librarian_watermark_at,
|
|
4039
|
-
librarian_watermark_id = excluded.librarian_watermark_id`,
|
|
4040
|
-
[entityId, wm.at, wm.id]
|
|
4041
|
-
);
|
|
4042
|
-
}
|
|
4043
|
-
// META TABLE METHODS
|
|
4044
|
-
async getMeta(key, tx) {
|
|
4045
|
-
const executor = this.getExecutor(tx);
|
|
4046
|
-
const row = await executor.getFirstAsync(
|
|
4047
|
-
`SELECT value FROM ${this.prefix}meta WHERE key = ?`,
|
|
4048
|
-
[key]
|
|
4049
|
-
);
|
|
4050
|
-
return row ? row.value : null;
|
|
4051
|
-
}
|
|
4052
|
-
async setMeta(key, value, tx) {
|
|
4053
|
-
const executor = this.getExecutor(tx);
|
|
4054
|
-
await executor.runAsync(
|
|
4055
|
-
`INSERT INTO ${this.prefix}meta (key, value) VALUES (?, ?)
|
|
4056
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
|
|
4057
|
-
[key, value]
|
|
4058
|
-
);
|
|
4059
|
-
}
|
|
4060
|
-
async deleteMeta(key, tx) {
|
|
4061
|
-
const executor = this.getExecutor(tx);
|
|
4062
|
-
await executor.runAsync(
|
|
4063
|
-
`DELETE FROM ${this.prefix}meta WHERE key = ?`,
|
|
4064
|
-
[key]
|
|
4065
|
-
);
|
|
4066
|
-
}
|
|
4067
|
-
async clearDimensionMismatch(tx) {
|
|
4068
|
-
const executor = this.getExecutor(tx);
|
|
4069
|
-
await executor.runAsync(
|
|
4070
|
-
`DELETE FROM ${this.prefix}meta WHERE key = 'embedding_dimension_mismatch'`
|
|
4071
|
-
);
|
|
4072
|
-
}
|
|
4073
|
-
async tableExists(tableName, tx) {
|
|
4074
|
-
const executor = this.getExecutor(tx);
|
|
4075
|
-
const row = await executor.getFirstAsync(
|
|
4076
|
-
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
|
|
4077
|
-
[tableName]
|
|
4078
|
-
);
|
|
4079
|
-
return row != null;
|
|
4080
|
-
}
|
|
4081
|
-
async getTableDdl(tableName, tx) {
|
|
4082
|
-
const executor = this.getExecutor(tx);
|
|
4083
|
-
const row = await executor.getFirstAsync(
|
|
4084
|
-
`SELECT sql FROM sqlite_master WHERE type='table' AND name=?`,
|
|
4085
|
-
[tableName]
|
|
4086
|
-
);
|
|
4087
|
-
return row?.sql ?? null;
|
|
4088
|
-
}
|
|
4089
|
-
async vacuum() {
|
|
4090
|
-
await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
|
|
4091
|
-
await this.db.execAsync(`VACUUM`);
|
|
4092
|
-
}
|
|
4093
|
-
/**
|
|
4094
|
-
* Returns the set of distinct `entity_id` values across entries/tasks/events.
|
|
4095
|
-
*
|
|
4096
|
-
* Deliberately widened from a prior `WHERE deleted_at IS NULL` form: the
|
|
4097
|
-
* returned set intentionally includes entities whose only rows are
|
|
4098
|
-
* soft-deleted, so the host's maintenance sweep can visit such
|
|
4099
|
-
* "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
|
|
4100
|
-
* is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
|
|
4101
|
-
*/
|
|
4102
|
-
async getDistinctEntityIds(tx) {
|
|
4103
|
-
const executor = this.getExecutor(tx);
|
|
4104
|
-
const rows = await executor.getAllAsync(
|
|
4105
|
-
`SELECT DISTINCT entity_id FROM (
|
|
4106
|
-
SELECT entity_id FROM ${this.prefix}entries
|
|
4107
|
-
UNION
|
|
4108
|
-
SELECT entity_id FROM ${this.prefix}tasks
|
|
4109
|
-
UNION
|
|
4110
|
-
SELECT entity_id FROM ${this.prefix}events
|
|
4111
|
-
) ORDER BY entity_id COLLATE BINARY`
|
|
4112
|
-
);
|
|
4113
|
-
return rows.map((r) => r.entity_id);
|
|
4114
|
-
}
|
|
4115
|
-
async getManifest(entityId, tx) {
|
|
4116
|
-
const executor = this.getExecutor(tx);
|
|
4117
|
-
const row = await executor.getFirstAsync(`SELECT mode, manifest_json FROM ${this.prefix}entity_manifests WHERE entity_id = ?`, [entityId]);
|
|
4118
|
-
if (!row) return null;
|
|
4119
|
-
if (row.mode !== "off" && row.mode !== "strict" && row.mode !== "emergent") {
|
|
4120
|
-
throw new Error(`Invalid ontology mode for entity ${entityId}: ${JSON.stringify(row.mode)}`);
|
|
4121
|
-
}
|
|
4122
|
-
let manifest;
|
|
4123
|
-
try {
|
|
4124
|
-
manifest = JSON.parse(row.manifest_json);
|
|
4125
|
-
} catch (error) {
|
|
4126
|
-
throw new Error(`Invalid manifest_json for entity ${entityId}: ${error.message}`);
|
|
4127
|
-
}
|
|
4128
|
-
validateManifest(manifest);
|
|
4129
|
-
return {
|
|
4130
|
-
mode: row.mode,
|
|
4131
|
-
manifest
|
|
4132
|
-
};
|
|
4133
|
-
}
|
|
4134
|
-
/**
|
|
4135
|
-
* Write an entity's manifest.
|
|
4136
|
-
*
|
|
4137
|
-
* `opts.ifAbsent` selects the conflict behaviour:
|
|
4138
|
-
* - omitted / `false` — upsert. An existing row is replaced.
|
|
4139
|
-
* - `true` — create-if-absent. An existing row is left exactly as it is.
|
|
4140
|
-
*
|
|
4141
|
-
* Returns whether this call actually wrote a row. Under `ifAbsent` a `false`
|
|
4142
|
-
* result means another writer got there first; the check and the write are one
|
|
4143
|
-
* statement, so there is no window between them.
|
|
4382
|
+
* The anchor is validated (exists, right entity, not soft-deleted) but never gated
|
|
4383
|
+
* by confidence/source_type — only nodes discovered beyond it are.
|
|
4144
4384
|
*/
|
|
4145
|
-
async
|
|
4146
|
-
validateManifest(data.manifest);
|
|
4385
|
+
async getNeighborhood(entityId, sourceId, opts, tx) {
|
|
4147
4386
|
const executor = this.getExecutor(tx);
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
|
|
4152
|
-
|
|
4153
|
-
|
|
4154
|
-
|
|
4387
|
+
if (opts.edgeTypes && opts.edgeTypes.length === 0) {
|
|
4388
|
+
const anchor = await executor.getFirstAsync(
|
|
4389
|
+
`SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
|
|
4390
|
+
[sourceId, entityId]
|
|
4391
|
+
);
|
|
4392
|
+
return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
|
|
4393
|
+
}
|
|
4394
|
+
const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
|
|
4395
|
+
const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
|
|
4396
|
+
const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
|
|
4397
|
+
const sql = `
|
|
4398
|
+
WITH RECURSIVE walk(node_id, depth, visited) AS (
|
|
4399
|
+
SELECT id, 0, ',' || id || ','
|
|
4400
|
+
FROM ${this.prefix}entries
|
|
4401
|
+
WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
|
|
4402
|
+
|
|
4403
|
+
UNION
|
|
4404
|
+
|
|
4405
|
+
SELECT
|
|
4406
|
+
CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
|
|
4407
|
+
w.depth + 1,
|
|
4408
|
+
w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
|
|
4409
|
+
FROM walk w
|
|
4410
|
+
JOIN ${this.prefix}edges e
|
|
4411
|
+
ON e.entity_id = ?
|
|
4412
|
+
AND (
|
|
4413
|
+
(? != 'inbound' AND e.source_id = w.node_id) OR
|
|
4414
|
+
(? != 'outbound' AND e.target_id = w.node_id)
|
|
4415
|
+
)
|
|
4416
|
+
AND (${edgeTypesClause})
|
|
4417
|
+
JOIN ${this.prefix}entries n
|
|
4418
|
+
ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
|
|
4419
|
+
AND n.entity_id = ?
|
|
4420
|
+
AND n.deleted_at IS NULL
|
|
4421
|
+
AND (
|
|
4422
|
+
CASE n.confidence
|
|
4423
|
+
WHEN 'tentative' THEN 0
|
|
4424
|
+
WHEN 'inferred' THEN 1
|
|
4425
|
+
WHEN 'certain' THEN 2
|
|
4426
|
+
ELSE -1
|
|
4427
|
+
END
|
|
4428
|
+
) >= ?
|
|
4429
|
+
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
4430
|
+
AND (? = 0 OR n.lifecycle_status != 'draft')
|
|
4431
|
+
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
4432
|
+
WHERE w.depth < ?
|
|
4433
|
+
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
4434
|
+
)
|
|
4435
|
+
SELECT node_id, MIN(depth) AS depth
|
|
4436
|
+
FROM walk
|
|
4437
|
+
GROUP BY node_id
|
|
4438
|
+
ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
|
|
4439
|
+
LIMIT ?
|
|
4440
|
+
`;
|
|
4441
|
+
const params = [
|
|
4442
|
+
sourceId,
|
|
4443
|
+
entityId,
|
|
4444
|
+
entityId,
|
|
4445
|
+
opts.direction,
|
|
4446
|
+
opts.direction,
|
|
4447
|
+
...opts.edgeTypes ?? [],
|
|
4448
|
+
entityId,
|
|
4449
|
+
minConfidenceRank,
|
|
4450
|
+
...opts.excludeSourceTypes,
|
|
4451
|
+
opts.excludeDrafts === true ? 1 : 0,
|
|
4452
|
+
opts.live.t,
|
|
4453
|
+
opts.live.t,
|
|
4454
|
+
opts.maxDepth,
|
|
4455
|
+
opts.maxNodes
|
|
4456
|
+
];
|
|
4457
|
+
const rows = await executor.getAllAsync(sql, params);
|
|
4458
|
+
const nodeIds = rows.map((r) => r.node_id);
|
|
4459
|
+
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
4460
|
+
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
4461
|
+
const edgeRows = await executor.getAllAsync(
|
|
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]
|
|
4155
4468
|
);
|
|
4156
|
-
return
|
|
4157
|
-
}
|
|
4158
|
-
async mergeManifestUpdates(entityId, updates, tx) {
|
|
4159
|
-
const current = await this.getManifest(entityId, tx) ?? {
|
|
4160
|
-
mode: "emergent",
|
|
4161
|
-
manifest: emptyManifest()
|
|
4162
|
-
};
|
|
4163
|
-
const merged = mergeOntologyUpdates(current.manifest, updates);
|
|
4164
|
-
await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
|
|
4165
|
-
return merged;
|
|
4469
|
+
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
4166
4470
|
}
|
|
4167
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
|
+
}
|
|
4168
4482
|
|
|
4169
4483
|
// src/services/legacyWatermark.ts
|
|
4170
4484
|
async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
|
|
@@ -4409,6 +4723,29 @@ async function setupDatabase(db, prefix) {
|
|
|
4409
4723
|
ON ${prefix}source_ref_index (entity_id, source_hash)
|
|
4410
4724
|
WHERE deleted_at IS NULL;
|
|
4411
4725
|
|
|
4726
|
+
-- source_documents / source_passages: the source store (specs/source-store \xA73).
|
|
4727
|
+
-- New tables only; hard delete, so no deleted_at and both UNIQUE indexes are plain.
|
|
4728
|
+
-- Passage text is not stored: offsets (UTF-16 code units) slice source_documents.text.
|
|
4729
|
+
CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
|
|
4730
|
+
id TEXT PRIMARY KEY,
|
|
4731
|
+
entity_id TEXT NOT NULL,
|
|
4732
|
+
source_ref TEXT NOT NULL,
|
|
4733
|
+
source_hash TEXT NOT NULL,
|
|
4734
|
+
text TEXT NOT NULL,
|
|
4735
|
+
text_hash TEXT NOT NULL,
|
|
4736
|
+
char_count INTEGER NOT NULL,
|
|
4737
|
+
created_at INTEGER NOT NULL
|
|
4738
|
+
);
|
|
4739
|
+
|
|
4740
|
+
CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
|
|
4741
|
+
id TEXT PRIMARY KEY,
|
|
4742
|
+
entity_id TEXT NOT NULL,
|
|
4743
|
+
document_id TEXT NOT NULL,
|
|
4744
|
+
seq INTEGER NOT NULL,
|
|
4745
|
+
start_offset INTEGER NOT NULL,
|
|
4746
|
+
end_offset INTEGER NOT NULL
|
|
4747
|
+
);
|
|
4748
|
+
|
|
4412
4749
|
CREATE TABLE IF NOT EXISTS ${prefix}tasks (
|
|
4413
4750
|
id TEXT PRIMARY KEY,
|
|
4414
4751
|
entity_id TEXT NOT NULL,
|
|
@@ -4535,6 +4872,8 @@ async function setupDatabase(db, prefix) {
|
|
|
4535
4872
|
`);
|
|
4536
4873
|
await createOkfV02IndexesIfColumnsExist(db, prefix);
|
|
4537
4874
|
await createTemporalIndexesIfColumnsExist(db, prefix);
|
|
4875
|
+
await createSourcePassageIndexesIfColumnsExist(db, prefix);
|
|
4876
|
+
await createSourceDocumentIndexesIfColumnsExist(db, prefix);
|
|
4538
4877
|
await createResurrectTrigger(db, prefix);
|
|
4539
4878
|
}
|
|
4540
4879
|
var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
|
|
@@ -4601,6 +4940,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
|
|
|
4601
4940
|
);
|
|
4602
4941
|
}
|
|
4603
4942
|
}
|
|
4943
|
+
async function createSourcePassageIndexesIfColumnsExist(db, prefix) {
|
|
4944
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_passages)`);
|
|
4945
|
+
const names = new Set(cols.map((c) => c.name));
|
|
4946
|
+
if (!names.has("document_id") || !names.has("entity_id")) return;
|
|
4947
|
+
await db.execAsync(`
|
|
4948
|
+
CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_doc ON ${prefix}source_passages (document_id, seq);
|
|
4949
|
+
CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_entity ON ${prefix}source_passages (entity_id);`);
|
|
4950
|
+
}
|
|
4951
|
+
async function createSourceDocumentIndexesIfColumnsExist(db, prefix) {
|
|
4952
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_documents)`);
|
|
4953
|
+
const names = new Set(cols.map((c) => c.name));
|
|
4954
|
+
if (!names.has("entity_id") || !names.has("source_ref") || !names.has("source_hash")) return;
|
|
4955
|
+
await db.execAsync(`
|
|
4956
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref ON ${prefix}source_documents (entity_id, source_ref);
|
|
4957
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash ON ${prefix}source_documents (entity_id, source_hash);`);
|
|
4958
|
+
}
|
|
4604
4959
|
|
|
4605
4960
|
// src/services/search/fts5Sql.ts
|
|
4606
4961
|
var FTS5_STATE_KEY = "fts5_index_state";
|
|
@@ -4738,6 +5093,38 @@ function sweepChunkSql(p) {
|
|
|
4738
5093
|
`DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
|
|
4739
5094
|
];
|
|
4740
5095
|
}
|
|
5096
|
+
function passageFtsTriggerNames(p) {
|
|
5097
|
+
return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
|
|
5098
|
+
}
|
|
5099
|
+
function passageFtsTablesDdl(p) {
|
|
5100
|
+
return `
|
|
5101
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS ${p}source_passages_fts USING fts5(
|
|
5102
|
+
passage_id UNINDEXED, entity_id UNINDEXED, doc_id UNINDEXED, text,
|
|
5103
|
+
tokenize = 'porter unicode61'
|
|
5104
|
+
);
|
|
5105
|
+
CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_map (
|
|
5106
|
+
fts_rowid INTEGER PRIMARY KEY,
|
|
5107
|
+
passage_id TEXT NOT NULL UNIQUE,
|
|
5108
|
+
doc_id TEXT NOT NULL
|
|
5109
|
+
);
|
|
5110
|
+
CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_map_doc ON ${p}source_passages_fts_map(doc_id);
|
|
5111
|
+
CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_pending (
|
|
5112
|
+
seq INTEGER PRIMARY KEY,
|
|
5113
|
+
entity_id TEXT NOT NULL,
|
|
5114
|
+
doc_id TEXT NOT NULL
|
|
5115
|
+
);
|
|
5116
|
+
CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_pending_doc ON ${p}source_passages_fts_pending(doc_id);`;
|
|
5117
|
+
}
|
|
5118
|
+
function passageFtsTriggersDdl(p) {
|
|
5119
|
+
const [ai, ad] = passageFtsTriggerNames(p);
|
|
5120
|
+
return `
|
|
5121
|
+
CREATE TRIGGER IF NOT EXISTS ${ai} AFTER INSERT ON ${p}source_passages BEGIN
|
|
5122
|
+
INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (NEW.entity_id, NEW.document_id);
|
|
5123
|
+
END;
|
|
5124
|
+
CREATE TRIGGER IF NOT EXISTS ${ad} AFTER DELETE ON ${p}source_passages BEGIN
|
|
5125
|
+
INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (OLD.entity_id, OLD.document_id);
|
|
5126
|
+
END;`;
|
|
5127
|
+
}
|
|
4741
5128
|
|
|
4742
5129
|
// src/db/migrations.ts
|
|
4743
5130
|
var MIGRATIONS = [
|
|
@@ -5043,6 +5430,57 @@ var MIGRATIONS = [
|
|
|
5043
5430
|
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
|
|
5044
5431
|
}
|
|
5045
5432
|
}
|
|
5433
|
+
},
|
|
5434
|
+
{
|
|
5435
|
+
version: 17,
|
|
5436
|
+
description: "add_source_store",
|
|
5437
|
+
run: async (db, prefix) => {
|
|
5438
|
+
const expected = {
|
|
5439
|
+
source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
|
|
5440
|
+
source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
|
|
5441
|
+
};
|
|
5442
|
+
for (const [table, want] of Object.entries(expected)) {
|
|
5443
|
+
const full = `${prefix}${table}`;
|
|
5444
|
+
const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
|
|
5445
|
+
if (cols.length === 0) continue;
|
|
5446
|
+
const same = cols.length === want.length && want.every((c) => cols.includes(c));
|
|
5447
|
+
if (!same) {
|
|
5448
|
+
throw new Error(
|
|
5449
|
+
`Migration v17 (add_source_store) failed: table ${full} exists with columns [${cols.join(", ")}], expected [${want.join(", ")}]. Drop the stray table (it predates the source store) and re-run setup().`
|
|
5450
|
+
);
|
|
5451
|
+
}
|
|
5452
|
+
const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
|
|
5453
|
+
if (row && row.n > 0) {
|
|
5454
|
+
throw new Error(
|
|
5455
|
+
`Migration v17 (add_source_store) failed: table ${full} already holds ${row.n} row(s), but no source text exists before v17. Back up and drop the table, then re-run setup().`
|
|
5456
|
+
);
|
|
5457
|
+
}
|
|
5458
|
+
}
|
|
5459
|
+
await db.execAsync(
|
|
5460
|
+
`CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
|
|
5461
|
+
id TEXT PRIMARY KEY,
|
|
5462
|
+
entity_id TEXT NOT NULL,
|
|
5463
|
+
source_ref TEXT NOT NULL,
|
|
5464
|
+
source_hash TEXT NOT NULL,
|
|
5465
|
+
text TEXT NOT NULL,
|
|
5466
|
+
text_hash TEXT NOT NULL,
|
|
5467
|
+
char_count INTEGER NOT NULL,
|
|
5468
|
+
created_at INTEGER NOT NULL
|
|
5469
|
+
);
|
|
5470
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
|
|
5471
|
+
ON ${prefix}source_documents (entity_id, source_ref);
|
|
5472
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
|
|
5473
|
+
ON ${prefix}source_documents (entity_id, source_hash);
|
|
5474
|
+
CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
|
|
5475
|
+
id TEXT PRIMARY KEY,
|
|
5476
|
+
entity_id TEXT NOT NULL,
|
|
5477
|
+
document_id TEXT NOT NULL,
|
|
5478
|
+
seq INTEGER NOT NULL,
|
|
5479
|
+
start_offset INTEGER NOT NULL,
|
|
5480
|
+
end_offset INTEGER NOT NULL
|
|
5481
|
+
);`
|
|
5482
|
+
);
|
|
5483
|
+
}
|
|
5046
5484
|
}
|
|
5047
5485
|
];
|
|
5048
5486
|
async function createLegacySourceTypeIndex(db, prefix) {
|
|
@@ -5635,100 +6073,12 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
5635
6073
|
else out.rejected.push(g);
|
|
5636
6074
|
});
|
|
5637
6075
|
}
|
|
5638
|
-
if (outcome.skipped.some((s) => s.reason === "call_error")) {
|
|
5639
|
-
throw new Error("resolve: transient provider error; retry the pass");
|
|
5640
|
-
}
|
|
5641
|
-
for (const s of outcome.skipped) out.failed.push(s.item);
|
|
5642
|
-
return out;
|
|
5643
|
-
}
|
|
5644
|
-
|
|
5645
|
-
// src/services/TemporalService.ts
|
|
5646
|
-
var HISTORY_MAX_DEPTH = 100;
|
|
5647
|
-
var TemporalService = class {
|
|
5648
|
-
constructor(db, options, entryRepo, searchService, embeddingService) {
|
|
5649
|
-
this.db = db;
|
|
5650
|
-
this.options = options;
|
|
5651
|
-
this.entryRepo = entryRepo;
|
|
5652
|
-
this.searchService = searchService;
|
|
5653
|
-
this.embeddingService = embeddingService;
|
|
5654
|
-
}
|
|
5655
|
-
/**
|
|
5656
|
-
* Link `oldId` → `newId` inside the caller's transaction. `newId` must
|
|
5657
|
-
* already exist. Throws WikiSupersedeError on any rule violation; the
|
|
5658
|
-
* caller's transaction then rolls back.
|
|
5659
|
-
*/
|
|
5660
|
-
async supersedeInTx(tx, entityId, oldId, newId, t, now) {
|
|
5661
|
-
const old = await this.entryRepo.findTemporalRow(oldId, tx);
|
|
5662
|
-
if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
5663
|
-
if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
5664
|
-
if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
5665
|
-
if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
|
|
5666
|
-
if (newId === oldId) throw new WikiSupersedeError("cycle");
|
|
5667
|
-
const repl = await this.entryRepo.findTemporalRow(newId, tx);
|
|
5668
|
-
if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
|
|
5669
|
-
if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
|
|
5670
|
-
if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
|
|
5671
|
-
const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
|
|
5672
|
-
if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
|
|
5673
|
-
await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
|
|
5674
|
-
if (repl.valid_from == null) {
|
|
5675
|
-
await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
|
|
5676
|
-
}
|
|
5677
|
-
}
|
|
5678
|
-
async supersede(entityId, oldId, replacement, options) {
|
|
5679
|
-
const now = Date.now();
|
|
5680
|
-
const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
|
|
5681
|
-
let created = null;
|
|
5682
|
-
if (typeof replacement !== "string") {
|
|
5683
|
-
if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
|
|
5684
|
-
throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
|
|
5685
|
-
}
|
|
5686
|
-
created = {
|
|
5687
|
-
id: generateId("fact_"),
|
|
5688
|
-
entity_id: entityId,
|
|
5689
|
-
title: replacement.title,
|
|
5690
|
-
body: replacement.body,
|
|
5691
|
-
tags: Array.isArray(replacement.tags) ? replacement.tags : [],
|
|
5692
|
-
confidence: replacement.confidence ?? "certain",
|
|
5693
|
-
source_type: replacement.source_type ?? "user_stated",
|
|
5694
|
-
source_hash: null,
|
|
5695
|
-
source_ref: null,
|
|
5696
|
-
created_at: now,
|
|
5697
|
-
updated_at: now,
|
|
5698
|
-
last_accessed_at: null,
|
|
5699
|
-
access_count: 0,
|
|
5700
|
-
deleted_at: null
|
|
5701
|
-
};
|
|
5702
|
-
}
|
|
5703
|
-
const newId = typeof replacement === "string" ? replacement : created.id;
|
|
5704
|
-
const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
|
|
5705
|
-
await this.db.withTransactionAsync(async (tx) => {
|
|
5706
|
-
if (created) {
|
|
5707
|
-
await this.entryRepo.upsert(created, tx);
|
|
5708
|
-
if (newValidFrom !== void 0) {
|
|
5709
|
-
await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
|
|
5710
|
-
}
|
|
5711
|
-
}
|
|
5712
|
-
await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
|
|
5713
|
-
});
|
|
5714
|
-
await this.searchService.syncEntries(entityId, [oldId, newId]);
|
|
5715
|
-
if (created) {
|
|
5716
|
-
await this.embeddingService.embedFact(
|
|
5717
|
-
{ id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
|
|
5718
|
-
{ operation: "supersede", trigger: "call" }
|
|
5719
|
-
);
|
|
5720
|
-
}
|
|
5721
|
-
this.searchService.evictCache(entityId);
|
|
5722
|
-
return { newId };
|
|
5723
|
-
}
|
|
5724
|
-
async history(entityId, factId) {
|
|
5725
|
-
const start = await this.entryRepo.findTemporalRow(factId);
|
|
5726
|
-
if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
|
|
5727
|
-
const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
|
|
5728
|
-
const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
|
|
5729
|
-
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));
|
|
5730
|
-
}
|
|
5731
|
-
};
|
|
6076
|
+
if (outcome.skipped.some((s) => s.reason === "call_error")) {
|
|
6077
|
+
throw new Error("resolve: transient provider error; retry the pass");
|
|
6078
|
+
}
|
|
6079
|
+
for (const s of outcome.skipped) out.failed.push(s.item);
|
|
6080
|
+
return out;
|
|
6081
|
+
}
|
|
5732
6082
|
|
|
5733
6083
|
// src/services/librarian/ops/apply.ts
|
|
5734
6084
|
function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
|
|
@@ -5995,6 +6345,7 @@ async function runLibrarianStrategy(deps, ctx) {
|
|
|
5995
6345
|
}
|
|
5996
6346
|
|
|
5997
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.`;
|
|
5998
6349
|
var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
|
|
5999
6350
|
var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
6000
6351
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -6043,6 +6394,20 @@ var formatSkipError = (err) => {
|
|
|
6043
6394
|
}
|
|
6044
6395
|
return base;
|
|
6045
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
|
+
};
|
|
6046
6411
|
var MaintenanceService = class {
|
|
6047
6412
|
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
|
|
6048
6413
|
this.db = db;
|
|
@@ -6063,7 +6428,15 @@ var MaintenanceService = class {
|
|
|
6063
6428
|
this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
|
|
6064
6429
|
}
|
|
6065
6430
|
async runPrune(entityId, options) {
|
|
6066
|
-
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);
|
|
6067
6440
|
try {
|
|
6068
6441
|
const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
|
|
6069
6442
|
const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
|
|
@@ -6094,8 +6467,9 @@ var MaintenanceService = class {
|
|
|
6094
6467
|
}
|
|
6095
6468
|
}
|
|
6096
6469
|
if (retainSoftDeletedFor !== null) {
|
|
6097
|
-
const
|
|
6098
|
-
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 });
|
|
6099
6473
|
const prunableIds = entriesToDelete.map((r) => r.id);
|
|
6100
6474
|
const vr = this.vectorRemoval;
|
|
6101
6475
|
const vrRepo = this.vectorRemovalRepo;
|
|
@@ -6141,7 +6515,7 @@ var MaintenanceService = class {
|
|
|
6141
6515
|
}
|
|
6142
6516
|
if (deletable.length > 0) {
|
|
6143
6517
|
const deletedIds = [];
|
|
6144
|
-
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 });
|
|
6145
6519
|
if (hookLedger) {
|
|
6146
6520
|
const gone = new Set(deletedIds);
|
|
6147
6521
|
const skipped = deletable.filter((id) => !gone.has(id));
|
|
@@ -6156,7 +6530,7 @@ var MaintenanceService = class {
|
|
|
6156
6530
|
else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
|
|
6157
6531
|
}
|
|
6158
6532
|
}
|
|
6159
|
-
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
|
|
6533
|
+
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
|
|
6160
6534
|
});
|
|
6161
6535
|
if (hookLedger) {
|
|
6162
6536
|
const keptSet = new Set(kept);
|
|
@@ -6201,12 +6575,20 @@ var MaintenanceService = class {
|
|
|
6201
6575
|
}
|
|
6202
6576
|
}
|
|
6203
6577
|
}
|
|
6578
|
+
let vacuumCheckpointErr;
|
|
6204
6579
|
if (vacuum) {
|
|
6205
|
-
|
|
6206
|
-
|
|
6207
|
-
|
|
6580
|
+
try {
|
|
6581
|
+
await this._wrappedVacuum();
|
|
6582
|
+
} catch (err) {
|
|
6583
|
+
if (!(err instanceof CheckpointIncompleteError)) throw err;
|
|
6584
|
+
vacuumCheckpointErr = err;
|
|
6585
|
+
}
|
|
6208
6586
|
}
|
|
6587
|
+
if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
|
|
6209
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
|
+
}
|
|
6210
6592
|
if (prunePartial) {
|
|
6211
6593
|
throw new PrunePartialFailureError(
|
|
6212
6594
|
deletedEntries,
|
|
@@ -6217,11 +6599,327 @@ var MaintenanceService = class {
|
|
|
6217
6599
|
deletedEvents
|
|
6218
6600
|
);
|
|
6219
6601
|
}
|
|
6602
|
+
if (vacuumCheckpointErr) throw vacuumCheckpointErr;
|
|
6220
6603
|
return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
|
|
6221
6604
|
} finally {
|
|
6222
6605
|
this.jobManager.releaseLock("prune", entityId);
|
|
6223
6606
|
}
|
|
6224
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
|
+
}
|
|
6225
6923
|
async runLibrarian(entityId, options) {
|
|
6226
6924
|
this.jobManager.acquireLock("librarian", entityId);
|
|
6227
6925
|
try {
|
|
@@ -6342,6 +7040,9 @@ var MaintenanceService = class {
|
|
|
6342
7040
|
if (params.includeEvents && !params.clearAll) {
|
|
6343
7041
|
throw new Error("forget() includeEvents requires clearAll: true");
|
|
6344
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
|
+
}
|
|
6345
7046
|
if (opts?.dryRun === true) {
|
|
6346
7047
|
return this.forgetDryRun(entityId, params);
|
|
6347
7048
|
}
|
|
@@ -6351,6 +7052,8 @@ var MaintenanceService = class {
|
|
|
6351
7052
|
let deletedEntries = 0;
|
|
6352
7053
|
let deletedTasks = 0;
|
|
6353
7054
|
let deletedEvents = 0;
|
|
7055
|
+
let chainIds = [];
|
|
7056
|
+
let chainTruncated = false;
|
|
6354
7057
|
const deletedEntryIds = [];
|
|
6355
7058
|
const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
|
|
6356
7059
|
await this.db.withTransactionAsync(async (tx) => {
|
|
@@ -6361,6 +7064,10 @@ var MaintenanceService = class {
|
|
|
6361
7064
|
if (await this.sourceRefIndexPresent(tx)) {
|
|
6362
7065
|
await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
|
|
6363
7066
|
}
|
|
7067
|
+
if (await this.sourceStorePresent(tx)) {
|
|
7068
|
+
await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
|
|
7069
|
+
await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
|
|
7070
|
+
}
|
|
6364
7071
|
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
6365
7072
|
if (params.includeEvents) {
|
|
6366
7073
|
deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
|
|
@@ -6383,6 +7090,22 @@ var MaintenanceService = class {
|
|
|
6383
7090
|
if (params.entryId) {
|
|
6384
7091
|
const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
|
|
6385
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
|
+
}
|
|
7099
|
+
}
|
|
7100
|
+
if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
|
|
7101
|
+
const docs = `${this.prefix}source_documents`;
|
|
7102
|
+
const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
|
|
7103
|
+
const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
|
|
7104
|
+
await tx.runAsync(
|
|
7105
|
+
`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
|
|
7106
|
+
[entityId, ...selArgs]
|
|
7107
|
+
);
|
|
7108
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
|
|
6386
7109
|
}
|
|
6387
7110
|
if (sourceRef || sourceHash) {
|
|
6388
7111
|
for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
|
|
@@ -6398,6 +7121,9 @@ var MaintenanceService = class {
|
|
|
6398
7121
|
sourceRefIndexPromise ?? Promise.resolve(void 0)
|
|
6399
7122
|
]);
|
|
6400
7123
|
if (entryResult) deletedEntries++;
|
|
7124
|
+
for (const id of chainIds) {
|
|
7125
|
+
if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
|
|
7126
|
+
}
|
|
6401
7127
|
if (taskResult) deletedTasks++;
|
|
6402
7128
|
deletedEntries += refResult;
|
|
6403
7129
|
}
|
|
@@ -6451,7 +7177,17 @@ var MaintenanceService = class {
|
|
|
6451
7177
|
});
|
|
6452
7178
|
}
|
|
6453
7179
|
}
|
|
6454
|
-
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
|
+
}
|
|
6455
7191
|
return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
|
|
6456
7192
|
} finally {
|
|
6457
7193
|
this.jobManager.releaseLock("forget", entityId);
|
|
@@ -6500,6 +7236,10 @@ var MaintenanceService = class {
|
|
|
6500
7236
|
if (version < 9) return false;
|
|
6501
7237
|
throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
|
|
6502
7238
|
}
|
|
7239
|
+
/** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
|
|
7240
|
+
async sourceStorePresent(tx) {
|
|
7241
|
+
return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
|
|
7242
|
+
}
|
|
6503
7243
|
/**
|
|
6504
7244
|
* Read-only dry-run preview of {@link forget}. Returns the same shape as a
|
|
6505
7245
|
* real call would, without acquiring the lock, opening a transaction, staging
|
|
@@ -6513,8 +7253,25 @@ var MaintenanceService = class {
|
|
|
6513
7253
|
* (the spec keeps dry-run narrow).
|
|
6514
7254
|
*/
|
|
6515
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
|
+
}
|
|
6516
7273
|
if (params.entryId !== void 0 || params.taskId !== void 0) {
|
|
6517
|
-
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");
|
|
6518
7275
|
}
|
|
6519
7276
|
if (params.clearAll) {
|
|
6520
7277
|
const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
|
|
@@ -7234,6 +7991,360 @@ var MaintenanceService = class {
|
|
|
7234
7991
|
}
|
|
7235
7992
|
};
|
|
7236
7993
|
|
|
7994
|
+
// src/utils/passageCutter.ts
|
|
7995
|
+
var MAX_PASSAGE_UNITS = 12e3;
|
|
7996
|
+
var WHITESPACE = /\s/;
|
|
7997
|
+
function isHigh(code) {
|
|
7998
|
+
return code >= 55296 && code <= 56319;
|
|
7999
|
+
}
|
|
8000
|
+
function isLow(code) {
|
|
8001
|
+
return code >= 56320 && code <= 57343;
|
|
8002
|
+
}
|
|
8003
|
+
function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
|
|
8004
|
+
const limit = Math.max(2, Math.floor(maxUnits));
|
|
8005
|
+
const spans = [];
|
|
8006
|
+
let start = 0;
|
|
8007
|
+
while (start < text.length) {
|
|
8008
|
+
if (text.length - start <= limit) {
|
|
8009
|
+
spans.push({ start, end: text.length });
|
|
8010
|
+
break;
|
|
8011
|
+
}
|
|
8012
|
+
let end = start + limit;
|
|
8013
|
+
let cut = -1;
|
|
8014
|
+
for (let i = end - 1; i > start; i--) {
|
|
8015
|
+
if (WHITESPACE.test(text[i])) {
|
|
8016
|
+
cut = i + 1;
|
|
8017
|
+
break;
|
|
8018
|
+
}
|
|
8019
|
+
}
|
|
8020
|
+
if (cut > start) {
|
|
8021
|
+
end = cut;
|
|
8022
|
+
} else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
|
|
8023
|
+
end -= 1;
|
|
8024
|
+
}
|
|
8025
|
+
spans.push({ start, end });
|
|
8026
|
+
start = end;
|
|
8027
|
+
}
|
|
8028
|
+
return spans;
|
|
8029
|
+
}
|
|
8030
|
+
|
|
8031
|
+
// src/utils/sha256.ts
|
|
8032
|
+
var K = new Uint32Array([
|
|
8033
|
+
1116352408,
|
|
8034
|
+
1899447441,
|
|
8035
|
+
3049323471,
|
|
8036
|
+
3921009573,
|
|
8037
|
+
961987163,
|
|
8038
|
+
1508970993,
|
|
8039
|
+
2453635748,
|
|
8040
|
+
2870763221,
|
|
8041
|
+
3624381080,
|
|
8042
|
+
310598401,
|
|
8043
|
+
607225278,
|
|
8044
|
+
1426881987,
|
|
8045
|
+
1925078388,
|
|
8046
|
+
2162078206,
|
|
8047
|
+
2614888103,
|
|
8048
|
+
3248222580,
|
|
8049
|
+
3835390401,
|
|
8050
|
+
4022224774,
|
|
8051
|
+
264347078,
|
|
8052
|
+
604807628,
|
|
8053
|
+
770255983,
|
|
8054
|
+
1249150122,
|
|
8055
|
+
1555081692,
|
|
8056
|
+
1996064986,
|
|
8057
|
+
2554220882,
|
|
8058
|
+
2821834349,
|
|
8059
|
+
2952996808,
|
|
8060
|
+
3210313671,
|
|
8061
|
+
3336571891,
|
|
8062
|
+
3584528711,
|
|
8063
|
+
113926993,
|
|
8064
|
+
338241895,
|
|
8065
|
+
666307205,
|
|
8066
|
+
773529912,
|
|
8067
|
+
1294757372,
|
|
8068
|
+
1396182291,
|
|
8069
|
+
1695183700,
|
|
8070
|
+
1986661051,
|
|
8071
|
+
2177026350,
|
|
8072
|
+
2456956037,
|
|
8073
|
+
2730485921,
|
|
8074
|
+
2820302411,
|
|
8075
|
+
3259730800,
|
|
8076
|
+
3345764771,
|
|
8077
|
+
3516065817,
|
|
8078
|
+
3600352804,
|
|
8079
|
+
4094571909,
|
|
8080
|
+
275423344,
|
|
8081
|
+
430227734,
|
|
8082
|
+
506948616,
|
|
8083
|
+
659060556,
|
|
8084
|
+
883997877,
|
|
8085
|
+
958139571,
|
|
8086
|
+
1322822218,
|
|
8087
|
+
1537002063,
|
|
8088
|
+
1747873779,
|
|
8089
|
+
1955562222,
|
|
8090
|
+
2024104815,
|
|
8091
|
+
2227730452,
|
|
8092
|
+
2361852424,
|
|
8093
|
+
2428436474,
|
|
8094
|
+
2756734187,
|
|
8095
|
+
3204031479,
|
|
8096
|
+
3329325298
|
|
8097
|
+
]);
|
|
8098
|
+
var rotr = (x, n) => x >>> n | x << 32 - n;
|
|
8099
|
+
var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
|
|
8100
|
+
function compress(H, W, view, off) {
|
|
8101
|
+
for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
|
|
8102
|
+
for (let t = 16; t < 64; t++) {
|
|
8103
|
+
const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
|
|
8104
|
+
const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
|
|
8105
|
+
W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
|
|
8106
|
+
}
|
|
8107
|
+
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
|
|
8108
|
+
for (let t = 0; t < 64; t++) {
|
|
8109
|
+
const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
8110
|
+
const ch = e & f ^ ~e & g;
|
|
8111
|
+
const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
|
|
8112
|
+
const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
8113
|
+
const maj = a & b ^ a & c ^ b & c;
|
|
8114
|
+
const t2 = S0 + maj >>> 0;
|
|
8115
|
+
h = g;
|
|
8116
|
+
g = f;
|
|
8117
|
+
f = e;
|
|
8118
|
+
e = d + t1 >>> 0;
|
|
8119
|
+
d = c;
|
|
8120
|
+
c = b;
|
|
8121
|
+
b = a;
|
|
8122
|
+
a = t1 + t2 >>> 0;
|
|
8123
|
+
}
|
|
8124
|
+
H[0] = H[0] + a >>> 0;
|
|
8125
|
+
H[1] = H[1] + b >>> 0;
|
|
8126
|
+
H[2] = H[2] + c >>> 0;
|
|
8127
|
+
H[3] = H[3] + d >>> 0;
|
|
8128
|
+
H[4] = H[4] + e >>> 0;
|
|
8129
|
+
H[5] = H[5] + f >>> 0;
|
|
8130
|
+
H[6] = H[6] + g >>> 0;
|
|
8131
|
+
H[7] = H[7] + h >>> 0;
|
|
8132
|
+
}
|
|
8133
|
+
function sha256(bytes) {
|
|
8134
|
+
const H = new Uint32Array(IV);
|
|
8135
|
+
const W = new Uint32Array(64);
|
|
8136
|
+
const whole = bytes.length - bytes.length % 64;
|
|
8137
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
8138
|
+
for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
|
|
8139
|
+
const rest = bytes.subarray(whole);
|
|
8140
|
+
const bitLen = bytes.length * 8;
|
|
8141
|
+
const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
|
|
8142
|
+
padded.set(rest);
|
|
8143
|
+
padded[rest.length] = 128;
|
|
8144
|
+
const pv = new DataView(padded.buffer);
|
|
8145
|
+
pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
|
|
8146
|
+
pv.setUint32(padded.length - 4, bitLen >>> 0);
|
|
8147
|
+
for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
|
|
8148
|
+
const out = new Uint8Array(32);
|
|
8149
|
+
const outView = new DataView(out.buffer);
|
|
8150
|
+
for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
|
|
8151
|
+
return out;
|
|
8152
|
+
}
|
|
8153
|
+
function utf8Encode(s) {
|
|
8154
|
+
const out = [];
|
|
8155
|
+
for (let i = 0; i < s.length; i++) {
|
|
8156
|
+
let cp = s.charCodeAt(i);
|
|
8157
|
+
if (cp >= 55296 && cp <= 56319) {
|
|
8158
|
+
const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
8159
|
+
if (next >= 56320 && next <= 57343) {
|
|
8160
|
+
cp = 65536 + (cp - 55296 << 10) + (next - 56320);
|
|
8161
|
+
i++;
|
|
8162
|
+
} else {
|
|
8163
|
+
cp = 65533;
|
|
8164
|
+
}
|
|
8165
|
+
} else if (cp >= 56320 && cp <= 57343) {
|
|
8166
|
+
cp = 65533;
|
|
8167
|
+
}
|
|
8168
|
+
if (cp < 128) out.push(cp);
|
|
8169
|
+
else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
|
|
8170
|
+
else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
|
|
8171
|
+
else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
|
|
8172
|
+
}
|
|
8173
|
+
return Uint8Array.from(out);
|
|
8174
|
+
}
|
|
8175
|
+
function sha256Hex(text) {
|
|
8176
|
+
let hex = "";
|
|
8177
|
+
for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
|
|
8178
|
+
return hex;
|
|
8179
|
+
}
|
|
8180
|
+
|
|
8181
|
+
// src/services/sourceStoreUpsert.ts
|
|
8182
|
+
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
8183
|
+
async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
|
|
8184
|
+
const { sourceRef, sourceHash, text } = src;
|
|
8185
|
+
const refuse = (code) => {
|
|
8186
|
+
onRefusal(code);
|
|
8187
|
+
return { status: "refused" };
|
|
8188
|
+
};
|
|
8189
|
+
if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
|
|
8190
|
+
if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
|
|
8191
|
+
const textHash = sha256Hex(text);
|
|
8192
|
+
const charCount = text.length;
|
|
8193
|
+
const docs = `${prefix}source_documents`;
|
|
8194
|
+
const passages = `${prefix}source_passages`;
|
|
8195
|
+
const registry = `${prefix}source_ref_index`;
|
|
8196
|
+
const existing = await tx.getFirstAsync(
|
|
8197
|
+
`SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
|
|
8198
|
+
WHERE entity_id = ? AND source_ref = ?`,
|
|
8199
|
+
[entityId, sourceRef]
|
|
8200
|
+
);
|
|
8201
|
+
if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
|
|
8202
|
+
if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
|
|
8203
|
+
const row = await tx.getFirstAsync(
|
|
8204
|
+
`SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
|
|
8205
|
+
[entityId, existing.id]
|
|
8206
|
+
);
|
|
8207
|
+
return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
|
|
8208
|
+
}
|
|
8209
|
+
const heldByStore = await tx.getFirstAsync(
|
|
8210
|
+
`SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
|
|
8211
|
+
[entityId, sourceHash, sourceRef]
|
|
8212
|
+
);
|
|
8213
|
+
const heldByFacts = await tx.getFirstAsync(
|
|
8214
|
+
`SELECT source_ref FROM ${registry}
|
|
8215
|
+
WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
|
|
8216
|
+
[entityId, sourceHash, sourceRef]
|
|
8217
|
+
);
|
|
8218
|
+
if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
|
|
8219
|
+
const total = await tx.getFirstAsync(
|
|
8220
|
+
`SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
|
|
8221
|
+
[entityId, sourceRef]
|
|
8222
|
+
);
|
|
8223
|
+
if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
|
|
8224
|
+
if (existing) {
|
|
8225
|
+
await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
|
|
8226
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
|
|
8227
|
+
}
|
|
8228
|
+
const id = generateId("sdoc_");
|
|
8229
|
+
const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
|
|
8230
|
+
await tx.runAsync(
|
|
8231
|
+
`INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
|
|
8232
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
8233
|
+
[id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
|
|
8234
|
+
);
|
|
8235
|
+
const spans = cutPassages(text);
|
|
8236
|
+
for (let seq = 0; seq < spans.length; seq++) {
|
|
8237
|
+
await tx.runAsync(
|
|
8238
|
+
`INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
|
|
8239
|
+
[generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
|
|
8240
|
+
);
|
|
8241
|
+
}
|
|
8242
|
+
return { status: "stored", charCount, passageCount: spans.length, storedAt };
|
|
8243
|
+
}
|
|
8244
|
+
|
|
8245
|
+
// src/services/SourceStoreService.ts
|
|
8246
|
+
var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
|
|
8247
|
+
var DEFAULT_MAX_TOTAL_CHARS = 5e6;
|
|
8248
|
+
function limitOr(value, fallback) {
|
|
8249
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
8250
|
+
}
|
|
8251
|
+
var SourceStoreService = class {
|
|
8252
|
+
constructor(db, prefix, options, jobManager) {
|
|
8253
|
+
this.db = db;
|
|
8254
|
+
this.prefix = prefix;
|
|
8255
|
+
this.options = options;
|
|
8256
|
+
this.jobManager = jobManager;
|
|
8257
|
+
}
|
|
8258
|
+
limits() {
|
|
8259
|
+
const cfg = this.options.config?.sourceStore;
|
|
8260
|
+
return {
|
|
8261
|
+
maxCharsPerSource: limitOr(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
|
|
8262
|
+
maxTotalChars: limitOr(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
|
|
8263
|
+
};
|
|
8264
|
+
}
|
|
8265
|
+
refuse(entityId, code, sourceRef) {
|
|
8266
|
+
const captured = [];
|
|
8267
|
+
const input = { code, operation: "sourceStore", trigger: "call", entityId, detail: { sourceRef } };
|
|
8268
|
+
emitDiagnostic({ onDiagnostic: (d) => {
|
|
8269
|
+
captured.push(d);
|
|
8270
|
+
} }, input);
|
|
8271
|
+
emitDiagnostic(this.options, input);
|
|
8272
|
+
return { stored: false, diagnostics: captured };
|
|
8273
|
+
}
|
|
8274
|
+
async storeSource(entityId, params) {
|
|
8275
|
+
const sourceRef = normalizeSourceRef(params.sourceRef);
|
|
8276
|
+
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
8277
|
+
const sourceHash = normalizeSourceHash(params.sourceHash);
|
|
8278
|
+
if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
|
|
8279
|
+
if (typeof params.text !== "string") throw new Error(`text must be a string, received ${typeof params.text}`);
|
|
8280
|
+
const text = params.text;
|
|
8281
|
+
this.jobManager.acquireLock("store", entityId);
|
|
8282
|
+
try {
|
|
8283
|
+
const limits = this.limits();
|
|
8284
|
+
let refused;
|
|
8285
|
+
const outcome = await this.db.withTransactionAsync((tx) => upsertStoredSource(
|
|
8286
|
+
tx,
|
|
8287
|
+
this.prefix,
|
|
8288
|
+
entityId,
|
|
8289
|
+
{ sourceRef, sourceHash, text },
|
|
8290
|
+
limits,
|
|
8291
|
+
(code) => {
|
|
8292
|
+
refused = code;
|
|
8293
|
+
},
|
|
8294
|
+
{ idempotentSamePair: true }
|
|
8295
|
+
));
|
|
8296
|
+
if (outcome.status === "refused") return this.refuse(entityId, refused, sourceRef);
|
|
8297
|
+
return {
|
|
8298
|
+
stored: true,
|
|
8299
|
+
sourceRef,
|
|
8300
|
+
sourceHash,
|
|
8301
|
+
charCount: outcome.charCount,
|
|
8302
|
+
passageCount: outcome.passageCount,
|
|
8303
|
+
storedAt: outcome.storedAt
|
|
8304
|
+
};
|
|
8305
|
+
} finally {
|
|
8306
|
+
this.jobManager.releaseLock("store", entityId);
|
|
8307
|
+
}
|
|
8308
|
+
}
|
|
8309
|
+
/** Spec §7: the text exactly as handed, or null. Plain read, no write lock. */
|
|
8310
|
+
async getStoredSource(entityId, sourceRef) {
|
|
8311
|
+
const ref = normalizeSourceRef(sourceRef);
|
|
8312
|
+
if (!ref) return null;
|
|
8313
|
+
const row = await this.db.getFirstAsync(
|
|
8314
|
+
`SELECT source_ref, source_hash, text, char_count, created_at FROM ${this.prefix}source_documents
|
|
8315
|
+
WHERE entity_id = ? AND source_ref = ?`,
|
|
8316
|
+
[entityId, ref]
|
|
8317
|
+
);
|
|
8318
|
+
if (!row) return null;
|
|
8319
|
+
return {
|
|
8320
|
+
sourceRef: row.source_ref,
|
|
8321
|
+
sourceHash: row.source_hash,
|
|
8322
|
+
text: row.text,
|
|
8323
|
+
charCount: Number(row.char_count),
|
|
8324
|
+
storedAt: Number(row.created_at)
|
|
8325
|
+
};
|
|
8326
|
+
}
|
|
8327
|
+
/** Spec §4/§7: full store listing, including sources stored with no ingest. */
|
|
8328
|
+
async listStoredSources(entityId) {
|
|
8329
|
+
const rows = await this.db.getAllAsync(
|
|
8330
|
+
`SELECT d.source_ref, d.source_hash, d.char_count, d.created_at,
|
|
8331
|
+
(SELECT COUNT(*) FROM ${this.prefix}source_passages p
|
|
8332
|
+
WHERE p.entity_id = d.entity_id AND p.document_id = d.id) AS passage_count
|
|
8333
|
+
FROM ${this.prefix}source_documents d
|
|
8334
|
+
WHERE d.entity_id = ?
|
|
8335
|
+
ORDER BY d.source_ref COLLATE BINARY`,
|
|
8336
|
+
[entityId]
|
|
8337
|
+
);
|
|
8338
|
+
return rows.map((r) => ({
|
|
8339
|
+
sourceRef: r.source_ref,
|
|
8340
|
+
sourceHash: r.source_hash,
|
|
8341
|
+
charCount: Number(r.char_count),
|
|
8342
|
+
passageCount: Number(r.passage_count),
|
|
8343
|
+
storedAt: Number(r.created_at)
|
|
8344
|
+
}));
|
|
8345
|
+
}
|
|
8346
|
+
};
|
|
8347
|
+
|
|
7237
8348
|
// src/utils/sourcePointer.ts
|
|
7238
8349
|
var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
|
|
7239
8350
|
function isStringOrNull(v) {
|
|
@@ -7349,7 +8460,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
7349
8460
|
var IMPORT_TITLE_MAX = 500;
|
|
7350
8461
|
var IMPORT_BODY_MAX = 8e3;
|
|
7351
8462
|
var ImportExportService = class {
|
|
7352
|
-
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
|
|
8463
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
|
|
7353
8464
|
this.db = db;
|
|
7354
8465
|
this.entryRepo = entryRepo;
|
|
7355
8466
|
this.taskRepo = taskRepo;
|
|
@@ -7361,13 +8472,22 @@ var ImportExportService = class {
|
|
|
7361
8472
|
this.embeddingService = embeddingService;
|
|
7362
8473
|
this.options = options;
|
|
7363
8474
|
this.vectorRemoval = vectorRemoval;
|
|
8475
|
+
this.prefix = prefix;
|
|
7364
8476
|
}
|
|
7365
|
-
async exportDump(entityIds) {
|
|
8477
|
+
async exportDump(entityIds, opts) {
|
|
8478
|
+
const includeForgotten = opts?.includeForgotten === true;
|
|
7366
8479
|
let ids;
|
|
7367
8480
|
if (entityIds && entityIds.length > 0) {
|
|
7368
8481
|
ids = Array.from(new Set(entityIds));
|
|
7369
8482
|
} else {
|
|
7370
8483
|
ids = await this.metadataRepo.getDistinctEntityIds();
|
|
8484
|
+
const prefix = this.storePrefix();
|
|
8485
|
+
if (prefix !== void 0 && await this.storePresent(prefix)) {
|
|
8486
|
+
const rows = await this.db.getAllAsync(
|
|
8487
|
+
`SELECT DISTINCT entity_id FROM ${prefix}source_documents`
|
|
8488
|
+
);
|
|
8489
|
+
ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
|
|
8490
|
+
}
|
|
7371
8491
|
}
|
|
7372
8492
|
const entities = {};
|
|
7373
8493
|
const BATCH = 3;
|
|
@@ -7375,10 +8495,11 @@ var ImportExportService = class {
|
|
|
7375
8495
|
const batch = ids.slice(i, i + BATCH);
|
|
7376
8496
|
const batchResults = await Promise.all(
|
|
7377
8497
|
batch.map(
|
|
7378
|
-
async (id) =>
|
|
7379
|
-
id,
|
|
7380
|
-
await this.
|
|
7381
|
-
|
|
8498
|
+
async (id) => {
|
|
8499
|
+
const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
|
|
8500
|
+
const storedSources = await this.exportStoredSources(id);
|
|
8501
|
+
return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
|
|
8502
|
+
}
|
|
7382
8503
|
)
|
|
7383
8504
|
);
|
|
7384
8505
|
for (const [id, bundle] of batchResults) {
|
|
@@ -7389,22 +8510,103 @@ var ImportExportService = class {
|
|
|
7389
8510
|
}
|
|
7390
8511
|
async importDump(dump, opts) {
|
|
7391
8512
|
const merge = opts?.merge ?? false;
|
|
8513
|
+
const skippedSources = [];
|
|
7392
8514
|
const entityIds = Object.keys(dump.entities);
|
|
7393
8515
|
this.jobManager.acquireImportLocks(entityIds);
|
|
7394
8516
|
try {
|
|
7395
8517
|
await this.assertNoLegacySourceTypes();
|
|
7396
8518
|
for (const [entityId, bundle] of Object.entries(dump.entities)) {
|
|
7397
|
-
await this.doImportEntity(entityId, bundle, merge);
|
|
8519
|
+
skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
|
|
7398
8520
|
}
|
|
7399
8521
|
} finally {
|
|
7400
8522
|
this.jobManager.releaseImportLocks(entityIds);
|
|
7401
8523
|
}
|
|
8524
|
+
return { skippedSources };
|
|
8525
|
+
}
|
|
8526
|
+
storePrefix() {
|
|
8527
|
+
return typeof this.prefix === "string" ? this.prefix : void 0;
|
|
8528
|
+
}
|
|
8529
|
+
// `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
|
|
8530
|
+
// store tables come from v17, which only runs after v9 — so it exists whenever they do.
|
|
8531
|
+
async storePresent(prefix, tx) {
|
|
8532
|
+
return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
|
|
8533
|
+
}
|
|
8534
|
+
/** Spec source-store §8: stored sources for one exported entity; [] when none. */
|
|
8535
|
+
async exportStoredSources(entityId) {
|
|
8536
|
+
const prefix = this.storePrefix();
|
|
8537
|
+
if (prefix === void 0 || !await this.storePresent(prefix)) return [];
|
|
8538
|
+
const docs = await this.db.getAllAsync(
|
|
8539
|
+
`SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
|
|
8540
|
+
WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
|
|
8541
|
+
[entityId]
|
|
8542
|
+
);
|
|
8543
|
+
const out = [];
|
|
8544
|
+
for (const d of docs) {
|
|
8545
|
+
const ps = await this.db.getAllAsync(
|
|
8546
|
+
`SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
|
|
8547
|
+
WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
|
|
8548
|
+
[entityId, d.id]
|
|
8549
|
+
);
|
|
8550
|
+
out.push({
|
|
8551
|
+
sourceRef: d.source_ref,
|
|
8552
|
+
sourceHash: d.source_hash,
|
|
8553
|
+
text: d.text,
|
|
8554
|
+
textHash: d.text_hash,
|
|
8555
|
+
charCount: Number(d.char_count),
|
|
8556
|
+
storedAt: Number(d.created_at),
|
|
8557
|
+
passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
|
|
8558
|
+
});
|
|
8559
|
+
}
|
|
8560
|
+
return out;
|
|
8561
|
+
}
|
|
8562
|
+
/**
|
|
8563
|
+
* Spec source-store §8/§9 import step, inside the import transaction. One
|
|
8564
|
+
* source at a time; a refusal skips that source only. Uses the
|
|
8565
|
+
* same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
|
|
8566
|
+
* truth for that ref (so no hash_mismatch refusal on import).
|
|
8567
|
+
*/
|
|
8568
|
+
async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
|
|
8569
|
+
const prefix = this.storePrefix();
|
|
8570
|
+
if (prefix === void 0) return;
|
|
8571
|
+
if (merge && !sources?.length) return;
|
|
8572
|
+
if (!await this.storePresent(prefix, tx)) return;
|
|
8573
|
+
const docs = `${prefix}source_documents`;
|
|
8574
|
+
const passages = `${prefix}source_passages`;
|
|
8575
|
+
if (!merge) {
|
|
8576
|
+
await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
|
|
8577
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
|
|
8578
|
+
}
|
|
8579
|
+
const cfg = this.options.config?.sourceStore;
|
|
8580
|
+
const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
|
|
8581
|
+
const limits = {
|
|
8582
|
+
maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
|
|
8583
|
+
maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
|
|
8584
|
+
};
|
|
8585
|
+
for (const src of sources ?? []) {
|
|
8586
|
+
const sourceRef = normalizeSourceRef(src?.sourceRef);
|
|
8587
|
+
const sourceHash = normalizeSourceHash(src?.sourceHash);
|
|
8588
|
+
if (!sourceRef || !sourceHash || typeof src.text !== "string") {
|
|
8589
|
+
throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
|
|
8590
|
+
}
|
|
8591
|
+
await upsertStoredSource(
|
|
8592
|
+
tx,
|
|
8593
|
+
prefix,
|
|
8594
|
+
entityId,
|
|
8595
|
+
{ sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
|
|
8596
|
+
limits,
|
|
8597
|
+
(code) => {
|
|
8598
|
+
skipped.push({ sourceRef, code });
|
|
8599
|
+
deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
|
|
8600
|
+
}
|
|
8601
|
+
);
|
|
8602
|
+
}
|
|
7402
8603
|
}
|
|
7403
8604
|
async getFullBundle(entityId, opts) {
|
|
8605
|
+
const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
|
|
7404
8606
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
7405
8607
|
const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
|
|
7406
|
-
opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
|
|
7407
|
-
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),
|
|
7408
8610
|
this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
|
|
7409
8611
|
this.edgeRepo.getByEntityId(entityId),
|
|
7410
8612
|
this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
|
|
@@ -7437,13 +8639,18 @@ var ImportExportService = class {
|
|
|
7437
8639
|
}
|
|
7438
8640
|
/** Single-entity import transaction + post-processing; package-internal hook for tests. */
|
|
7439
8641
|
async doImportEntity(entityId, bundle, merge) {
|
|
8642
|
+
const skippedSources = [];
|
|
8643
|
+
const refusalDiagnostics = [];
|
|
7440
8644
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
8645
|
+
const liveEmbedFactIds = /* @__PURE__ */ new Set();
|
|
7441
8646
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
7442
8647
|
const factsWithPreservedBlob = /* @__PURE__ */ new Map();
|
|
7443
8648
|
const preservedBlobDims = /* @__PURE__ */ new Set();
|
|
7444
8649
|
const softDeletedFactIds = [];
|
|
8650
|
+
const softDeletedTaskIds = [];
|
|
7445
8651
|
const clippedTextByFactId = /* @__PURE__ */ new Map();
|
|
7446
8652
|
let clampedEvents = 0;
|
|
8653
|
+
let tombstoneSkipped = 0;
|
|
7447
8654
|
const restamped = { behind_watermark: 0, invalid: 0 };
|
|
7448
8655
|
await this.db.withTransactionAsync(async (tx) => {
|
|
7449
8656
|
if (!merge) {
|
|
@@ -7454,8 +8661,9 @@ var ImportExportService = class {
|
|
|
7454
8661
|
tx,
|
|
7455
8662
|
false
|
|
7456
8663
|
);
|
|
7457
|
-
softDeletedFactIds.push(
|
|
8664
|
+
for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
|
|
7458
8665
|
await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
8666
|
+
for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
|
|
7459
8667
|
await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
7460
8668
|
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
7461
8669
|
await this.metadataRepo.deleteCheckpoint(entityId, tx);
|
|
@@ -7465,6 +8673,8 @@ var ImportExportService = class {
|
|
|
7465
8673
|
} else if (!merge) {
|
|
7466
8674
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
7467
8675
|
}
|
|
8676
|
+
const wipedByThisImport = new Set(softDeletedFactIds);
|
|
8677
|
+
const wipedTasksByThisImport = new Set(softDeletedTaskIds);
|
|
7468
8678
|
const factIds = bundle.facts.map((fact) => fact.id);
|
|
7469
8679
|
const existingFactsById = /* @__PURE__ */ new Map();
|
|
7470
8680
|
const existingFacts = await this.entryRepo.findExistingMetadataByIds(
|
|
@@ -7540,11 +8750,16 @@ var ImportExportService = class {
|
|
|
7540
8750
|
);
|
|
7541
8751
|
continue;
|
|
7542
8752
|
}
|
|
7543
|
-
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;
|
|
7544
8758
|
}
|
|
7545
8759
|
const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
|
|
7546
8760
|
const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
|
|
7547
|
-
|
|
8761
|
+
const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
|
|
8762
|
+
clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
|
|
7548
8763
|
let normalizedSourceRef = null;
|
|
7549
8764
|
if (fact.source_ref !== null && fact.source_ref !== void 0) {
|
|
7550
8765
|
normalizedSourceRef = normalizeSourceRef(fact.source_ref);
|
|
@@ -7611,15 +8826,22 @@ var ImportExportService = class {
|
|
|
7611
8826
|
}, tx, { outbox: false });
|
|
7612
8827
|
if (blobData != null) {
|
|
7613
8828
|
factsWithPreservedBlob.set(fact.id, blobData);
|
|
7614
|
-
if (
|
|
8829
|
+
if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
|
|
7615
8830
|
}
|
|
7616
8831
|
existingFactsById.set(fact.id, {
|
|
7617
8832
|
id: fact.id,
|
|
7618
8833
|
entity_id: entityId,
|
|
7619
|
-
updated_at: safeUpdatedAt
|
|
8834
|
+
updated_at: safeUpdatedAt,
|
|
8835
|
+
deleted_at: fact.deleted_at ?? null
|
|
7620
8836
|
});
|
|
8837
|
+
wipedByThisImport.delete(fact.id);
|
|
7621
8838
|
upsertedFactIds.add(fact.id);
|
|
7622
|
-
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
|
+
}
|
|
7623
8845
|
}
|
|
7624
8846
|
const taskIds = bundle.tasks.map((task) => task.id);
|
|
7625
8847
|
const existingTasksById = /* @__PURE__ */ new Map();
|
|
@@ -7643,7 +8865,11 @@ var ImportExportService = class {
|
|
|
7643
8865
|
);
|
|
7644
8866
|
continue;
|
|
7645
8867
|
}
|
|
7646
|
-
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;
|
|
7647
8873
|
}
|
|
7648
8874
|
await this.taskRepo.upsertForImport(
|
|
7649
8875
|
{
|
|
@@ -7676,8 +8902,10 @@ var ImportExportService = class {
|
|
|
7676
8902
|
existingTasksById.set(task.id, {
|
|
7677
8903
|
id: task.id,
|
|
7678
8904
|
entity_id: entityId,
|
|
7679
|
-
updated_at: safeUpdatedAt
|
|
8905
|
+
updated_at: safeUpdatedAt,
|
|
8906
|
+
deleted_at: task.deleted_at ?? null
|
|
7680
8907
|
});
|
|
8908
|
+
wipedTasksByThisImport.delete(task.id);
|
|
7681
8909
|
}
|
|
7682
8910
|
const now = Date.now();
|
|
7683
8911
|
const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
|
|
@@ -7714,7 +8942,18 @@ var ImportExportService = class {
|
|
|
7714
8942
|
tx
|
|
7715
8943
|
);
|
|
7716
8944
|
}
|
|
8945
|
+
await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
|
|
7717
8946
|
});
|
|
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
|
+
}
|
|
7718
8957
|
if (clampedEvents > 0) {
|
|
7719
8958
|
emitDiagnostic(this.options, {
|
|
7720
8959
|
code: "event_created_at_clamped",
|
|
@@ -7740,28 +8979,28 @@ var ImportExportService = class {
|
|
|
7740
8979
|
} else {
|
|
7741
8980
|
await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
|
|
7742
8981
|
}
|
|
7743
|
-
for (const
|
|
7744
|
-
if (!
|
|
7745
|
-
const clipped = clippedTextByFactId.get(
|
|
8982
|
+
for (const id of liveEmbedFactIds) {
|
|
8983
|
+
if (!factsWithPreservedBlob.has(id)) {
|
|
8984
|
+
const clipped = clippedTextByFactId.get(id);
|
|
7746
8985
|
const embedded = await this.embeddingService.embedFact({
|
|
7747
|
-
id
|
|
8986
|
+
id,
|
|
7748
8987
|
entity_id: entityId,
|
|
7749
|
-
title: clipped?.title ??
|
|
7750
|
-
body: clipped?.body ??
|
|
7751
|
-
tags:
|
|
8988
|
+
title: clipped?.title ?? "",
|
|
8989
|
+
body: clipped?.body ?? "",
|
|
8990
|
+
tags: clipped?.tags ?? []
|
|
7752
8991
|
}, { operation: "importDump", trigger: "call" });
|
|
7753
8992
|
if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
7754
8993
|
try {
|
|
7755
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId,
|
|
8994
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
|
|
7756
8995
|
} catch (hookErr) {
|
|
7757
8996
|
console.warn(
|
|
7758
|
-
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${
|
|
8997
|
+
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
|
|
7759
8998
|
hookErr
|
|
7760
8999
|
);
|
|
7761
9000
|
this.embeddingService.reportHookFailed(
|
|
7762
9001
|
{ operation: "importDump", trigger: "call" },
|
|
7763
9002
|
entityId,
|
|
7764
|
-
|
|
9003
|
+
id
|
|
7765
9004
|
);
|
|
7766
9005
|
}
|
|
7767
9006
|
}
|
|
@@ -7769,7 +9008,7 @@ var ImportExportService = class {
|
|
|
7769
9008
|
}
|
|
7770
9009
|
for (const fact of bundle.facts) {
|
|
7771
9010
|
const blobData = factsWithPreservedBlob.get(fact.id);
|
|
7772
|
-
if (blobData &&
|
|
9011
|
+
if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
|
|
7773
9012
|
try {
|
|
7774
9013
|
const float32Vector = new Float32Array(
|
|
7775
9014
|
blobData.buffer,
|
|
@@ -7882,6 +9121,7 @@ var ImportExportService = class {
|
|
|
7882
9121
|
} finally {
|
|
7883
9122
|
this.searchService.evictCache(entityId);
|
|
7884
9123
|
}
|
|
9124
|
+
return skippedSources;
|
|
7885
9125
|
}
|
|
7886
9126
|
_warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
|
|
7887
9127
|
console.warn(
|
|
@@ -8406,6 +9646,63 @@ function packFactsByBudget(items, budget, scores) {
|
|
|
8406
9646
|
|
|
8407
9647
|
// src/services/RetrievalService.ts
|
|
8408
9648
|
var EMPTY_ID_SET = /* @__PURE__ */ new Set();
|
|
9649
|
+
var DEFAULT_SOURCE_PASSAGES = 8;
|
|
9650
|
+
var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
|
|
9651
|
+
var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
9652
|
+
var isHigh2 = (c) => c >= 55296 && c <= 56319;
|
|
9653
|
+
var isLow2 = (c) => c >= 56320 && c <= 57343;
|
|
9654
|
+
function queryTerms(query) {
|
|
9655
|
+
return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
|
|
9656
|
+
}
|
|
9657
|
+
function assertSourcesQuery(opt) {
|
|
9658
|
+
const query = opt?.query;
|
|
9659
|
+
if (typeof query !== "string" || query.trim() === "") {
|
|
9660
|
+
throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
|
|
9661
|
+
}
|
|
9662
|
+
if (queryTerms(query).length === 0) {
|
|
9663
|
+
throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
|
|
9664
|
+
}
|
|
9665
|
+
}
|
|
9666
|
+
function windowPassage(text, terms, budget) {
|
|
9667
|
+
if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
|
|
9668
|
+
const lower = asciiLower(text);
|
|
9669
|
+
let a = -1;
|
|
9670
|
+
let len = 0;
|
|
9671
|
+
for (const t of terms) {
|
|
9672
|
+
const i = lower.indexOf(t);
|
|
9673
|
+
if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
|
|
9674
|
+
a = i;
|
|
9675
|
+
len = t.length;
|
|
9676
|
+
}
|
|
9677
|
+
}
|
|
9678
|
+
const hardCut = (from) => {
|
|
9679
|
+
let end = Math.min(text.length, from + budget);
|
|
9680
|
+
if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
|
|
9681
|
+
if (end - 1 > from) end -= 1;
|
|
9682
|
+
else return { start: from, end: from, truncated: true };
|
|
9683
|
+
}
|
|
9684
|
+
return { start: from, end, truncated: from > 0 || end < text.length };
|
|
9685
|
+
};
|
|
9686
|
+
if (a < 0) return hardCut(0);
|
|
9687
|
+
if (len > budget) return hardCut(a);
|
|
9688
|
+
const toks = [];
|
|
9689
|
+
for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
|
|
9690
|
+
const mEnd = a + len;
|
|
9691
|
+
const ti = toks.findIndex(([, e]) => e > a);
|
|
9692
|
+
if (ti < 0) return hardCut(a);
|
|
9693
|
+
let tj = ti;
|
|
9694
|
+
while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
|
|
9695
|
+
if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
|
|
9696
|
+
let r = toks.length - 1;
|
|
9697
|
+
let best = { start: toks[ti][0], end: toks[tj][1] };
|
|
9698
|
+
for (let l = ti; l >= 0; l--) {
|
|
9699
|
+
const s = toks[l][0];
|
|
9700
|
+
while (r > tj && toks[r][1] - s > budget) r--;
|
|
9701
|
+
if (toks[r][1] - s > budget) break;
|
|
9702
|
+
if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
|
|
9703
|
+
}
|
|
9704
|
+
return { ...best, truncated: true };
|
|
9705
|
+
}
|
|
8409
9706
|
var RetrievalService = class {
|
|
8410
9707
|
constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
|
|
8411
9708
|
this.options = options;
|
|
@@ -8420,8 +9717,10 @@ var RetrievalService = class {
|
|
|
8420
9717
|
const entityIds = normalizeEntityIds(entityId);
|
|
8421
9718
|
const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
|
|
8422
9719
|
const exposeMetadata = shouldExposeReadMetadata(entityId);
|
|
9720
|
+
if (options?.sources) assertSourcesQuery(options.sources);
|
|
8423
9721
|
if (entityIds.length === 0) {
|
|
8424
9722
|
const empty = { facts: [], tasks: [], events: [], edges: [] };
|
|
9723
|
+
if (options?.sources) empty.sources = [];
|
|
8425
9724
|
if (exposeMetadata) {
|
|
8426
9725
|
empty.metadata = { query, entityIds: [] };
|
|
8427
9726
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -8936,6 +10235,7 @@ var RetrievalService = class {
|
|
|
8936
10235
|
factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
|
|
8937
10236
|
}
|
|
8938
10237
|
const bundle = { facts, tasks, events: events.reverse(), edges: [] };
|
|
10238
|
+
if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
|
|
8939
10239
|
if (exposeMetadata) {
|
|
8940
10240
|
bundle.metadata = { query, entityIds };
|
|
8941
10241
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -8944,6 +10244,42 @@ var RetrievalService = class {
|
|
|
8944
10244
|
}
|
|
8945
10245
|
return bundle;
|
|
8946
10246
|
}
|
|
10247
|
+
/**
|
|
10248
|
+
* The `sources` group (spec source-store section 7). One search per entity,
|
|
10249
|
+
* so ranking and caps never cross entities. No model call anywhere.
|
|
10250
|
+
* `charBudget` is per entity: windows are cut in rank order against the
|
|
10251
|
+
* entity's remaining budget, and once it is spent lower-ranked hits are not returned.
|
|
10252
|
+
*/
|
|
10253
|
+
async _readSources(entityIds, opt) {
|
|
10254
|
+
const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
|
|
10255
|
+
const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
|
|
10256
|
+
const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
|
|
10257
|
+
assertSourcesQuery(opt);
|
|
10258
|
+
const query = opt.query;
|
|
10259
|
+
const terms = queryTerms(query);
|
|
10260
|
+
const out = [];
|
|
10261
|
+
for (const entityId of entityIds) {
|
|
10262
|
+
const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
|
|
10263
|
+
let remaining = charBudget;
|
|
10264
|
+
for (const h of hits) {
|
|
10265
|
+
if (remaining <= 0) break;
|
|
10266
|
+
const w = windowPassage(h.text, terms, remaining);
|
|
10267
|
+
if (w.end === w.start) continue;
|
|
10268
|
+
remaining -= w.end - w.start;
|
|
10269
|
+
out.push({
|
|
10270
|
+
entityId,
|
|
10271
|
+
sourceRef: h.source_ref,
|
|
10272
|
+
sourceHash: h.source_hash,
|
|
10273
|
+
seq: h.seq,
|
|
10274
|
+
startOffset: h.start_offset + w.start,
|
|
10275
|
+
endOffset: h.start_offset + w.end,
|
|
10276
|
+
truncated: w.truncated,
|
|
10277
|
+
text: h.text.slice(w.start, w.end)
|
|
10278
|
+
});
|
|
10279
|
+
}
|
|
10280
|
+
}
|
|
10281
|
+
return out;
|
|
10282
|
+
}
|
|
8947
10283
|
/**
|
|
8948
10284
|
* Returns entity IDs that will participate in scored retrieval.
|
|
8949
10285
|
* Excludes zero-weight entities unless includeZeroWeightEntities is true.
|
|
@@ -9232,6 +10568,6 @@ var WriteService = class {
|
|
|
9232
10568
|
}
|
|
9233
10569
|
};
|
|
9234
10570
|
|
|
9235
|
-
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, 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, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
9236
|
-
//# sourceMappingURL=chunk-
|
|
9237
|
-
//# 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
|