@equationalapplications/core-llm-wiki 9.14.1 → 9.16.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-JX7VMQ55.mjs → chunk-DD5G4VRF.mjs} +3624 -3223
- package/dist/chunk-DD5G4VRF.mjs.map +1 -0
- package/dist/index.d.mts +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.js +1484 -942
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +174 -34
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BclOvn3q.d.mts → testing-C8sYdo2S.d.mts} +169 -41
- package/dist/{testing-BclOvn3q.d.ts → testing-C8sYdo2S.d.ts} +169 -41
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +465 -71
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-JX7VMQ55.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -15,6 +15,299 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
|
|
|
15
15
|
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
16
16
|
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
17
17
|
|
|
18
|
+
// src/utils/chunkingDefaults.ts
|
|
19
|
+
var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
|
|
20
|
+
var DEFAULT_CHUNK_OVERLAP = 400;
|
|
21
|
+
|
|
22
|
+
// src/utils/contextCaps.ts
|
|
23
|
+
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
24
|
+
var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
25
|
+
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
26
|
+
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
27
|
+
|
|
28
|
+
// src/config/context.ts
|
|
29
|
+
var DEFAULT_CHARS_PER_TOKEN = 4;
|
|
30
|
+
var DEFAULT_SAFETY_FRACTION = 0.9;
|
|
31
|
+
var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
|
|
32
|
+
var OP_FLOOR = {
|
|
33
|
+
resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
34
|
+
heal: HEAL_MAX_PROMPT_CHARS,
|
|
35
|
+
extract: OPS_MAX_EXTRACT_CHARS,
|
|
36
|
+
backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
|
|
37
|
+
};
|
|
38
|
+
function bad(key, value, why) {
|
|
39
|
+
return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
|
|
40
|
+
}
|
|
41
|
+
function resolveContextBudget(config) {
|
|
42
|
+
const context = config?.context;
|
|
43
|
+
if (!context || context.budget === void 0) {
|
|
44
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
45
|
+
}
|
|
46
|
+
if (context.budget !== "legacy" && context.budget !== "declared") {
|
|
47
|
+
throw bad("budget", context.budget, "'legacy' or 'declared'");
|
|
48
|
+
}
|
|
49
|
+
if (context.budget === "legacy") {
|
|
50
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
51
|
+
}
|
|
52
|
+
const window = context.contextWindowTokens;
|
|
53
|
+
if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
|
|
54
|
+
throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
|
|
55
|
+
}
|
|
56
|
+
const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
57
|
+
if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
|
|
58
|
+
throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
|
|
59
|
+
}
|
|
60
|
+
const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
|
|
61
|
+
if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
|
|
62
|
+
throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
|
|
63
|
+
}
|
|
64
|
+
const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
|
|
65
|
+
if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
|
|
66
|
+
throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
|
|
67
|
+
}
|
|
68
|
+
return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
|
|
69
|
+
}
|
|
70
|
+
function declaredPromptCap(budget, op) {
|
|
71
|
+
const derived = Math.floor(
|
|
72
|
+
(budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
|
|
73
|
+
);
|
|
74
|
+
return Math.max(OP_FLOOR[op], derived);
|
|
75
|
+
}
|
|
76
|
+
function resolveMaxPromptChars(budget, op) {
|
|
77
|
+
if (budget.mode !== "declared") {
|
|
78
|
+
return OP_FLOOR[op];
|
|
79
|
+
}
|
|
80
|
+
if (op === "extract") {
|
|
81
|
+
const resolveDerived = declaredPromptCap(budget, "resolve");
|
|
82
|
+
const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
|
|
83
|
+
return Math.max(OP_FLOOR.extract, extractDerived);
|
|
84
|
+
}
|
|
85
|
+
return declaredPromptCap(budget, op);
|
|
86
|
+
}
|
|
87
|
+
function resolveDefaultChunkLength(budget) {
|
|
88
|
+
return DEFAULT_MAX_CHUNK_LENGTH;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/utils/engineDefaults.ts
|
|
92
|
+
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
93
|
+
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
94
|
+
function resolveLibrarianStrategy(config) {
|
|
95
|
+
return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
|
|
96
|
+
}
|
|
97
|
+
function resolveMaintenanceMode(config) {
|
|
98
|
+
return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
|
|
99
|
+
}
|
|
100
|
+
function resolveContextBudgetOrThrow(config) {
|
|
101
|
+
return resolveContextBudget(config);
|
|
102
|
+
}
|
|
103
|
+
function changedDefaultWarnings(config) {
|
|
104
|
+
const warnings = [];
|
|
105
|
+
const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
|
|
106
|
+
if (hasThreshold && config?.maintenance === void 0) {
|
|
107
|
+
warnings.push(
|
|
108
|
+
"[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
if (config?.prompts?.librarianSystemPrompt !== void 0) {
|
|
112
|
+
warnings.push(
|
|
113
|
+
"[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
|
|
117
|
+
warnings.push(
|
|
118
|
+
"[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
return warnings;
|
|
122
|
+
}
|
|
123
|
+
var warnedDefaults = /* @__PURE__ */ new Set();
|
|
124
|
+
function warnChangedDefaultsOnce(config) {
|
|
125
|
+
for (const message of changedDefaultWarnings(config)) {
|
|
126
|
+
if (warnedDefaults.has(message)) continue;
|
|
127
|
+
warnedDefaults.add(message);
|
|
128
|
+
console.warn(message);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function warnOnce(message) {
|
|
132
|
+
if (warnedDefaults.has(message)) return;
|
|
133
|
+
warnedDefaults.add(message);
|
|
134
|
+
console.warn(message);
|
|
135
|
+
}
|
|
136
|
+
function formatConfigValue(value) {
|
|
137
|
+
try {
|
|
138
|
+
const json = JSON.stringify(value);
|
|
139
|
+
return json ?? String(value);
|
|
140
|
+
} catch {
|
|
141
|
+
return `[unserializable: ${typeof value}]`;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
var isTypingMode = (v) => v === "auto" || v === "llm";
|
|
145
|
+
var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
146
|
+
function resolveSystemOneTyping(config, classifierCallOption) {
|
|
147
|
+
const systemOne = config?.systemOne;
|
|
148
|
+
const legacy = config?.ontology?.backfillClassifier;
|
|
149
|
+
const systemOneValid = isTypingMode(systemOne?.typing);
|
|
150
|
+
const legacyValid = isTypingMode(legacy);
|
|
151
|
+
if (systemOne?.typing !== void 0 && !systemOneValid) {
|
|
152
|
+
warnOnce(
|
|
153
|
+
`[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (legacy !== void 0 && !legacyValid) {
|
|
157
|
+
warnOnce(
|
|
158
|
+
`[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
|
|
162
|
+
warnOnce(
|
|
163
|
+
`[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
|
|
167
|
+
}
|
|
168
|
+
function resolveSystemOneEdges(config) {
|
|
169
|
+
const edges = config?.systemOne?.edges;
|
|
170
|
+
if (edges !== void 0 && !isTypingMode(edges)) {
|
|
171
|
+
warnOnce(
|
|
172
|
+
`[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
173
|
+
);
|
|
174
|
+
return "llm";
|
|
175
|
+
}
|
|
176
|
+
return edges ?? "llm";
|
|
177
|
+
}
|
|
178
|
+
function resolveSystemOneResolve(config) {
|
|
179
|
+
const resolve = config?.systemOne?.resolve;
|
|
180
|
+
if (resolve !== void 0 && !isTypingMode(resolve)) {
|
|
181
|
+
warnOnce(
|
|
182
|
+
`[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
183
|
+
);
|
|
184
|
+
return "llm";
|
|
185
|
+
}
|
|
186
|
+
return resolve ?? "llm";
|
|
187
|
+
}
|
|
188
|
+
var DEFAULT_SHORTLIST_K = 10;
|
|
189
|
+
function resolveShortlistK(config) {
|
|
190
|
+
const k = config?.ontology?.shortlistK;
|
|
191
|
+
if (k === void 0) return DEFAULT_SHORTLIST_K;
|
|
192
|
+
if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
|
|
193
|
+
throw new Error(
|
|
194
|
+
`[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
return k;
|
|
198
|
+
}
|
|
199
|
+
var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
|
|
200
|
+
function resolveTypingMinConfidence(config) {
|
|
201
|
+
const systemOneFloor = config?.systemOne?.minConfidence?.typing;
|
|
202
|
+
const legacyFloor = config?.ontology?.classifyMinConfidence;
|
|
203
|
+
const systemOneValid = isConfidenceFloor(systemOneFloor);
|
|
204
|
+
const legacyValid = isConfidenceFloor(legacyFloor);
|
|
205
|
+
if (systemOneFloor !== void 0 && !systemOneValid) {
|
|
206
|
+
warnOnce(
|
|
207
|
+
`[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
if (legacyFloor !== void 0 && !legacyValid) {
|
|
211
|
+
warnOnce(
|
|
212
|
+
`[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
|
|
216
|
+
}
|
|
217
|
+
var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
|
|
218
|
+
function resolveEdgesMinConfidence(config) {
|
|
219
|
+
if (resolveSystemOneEdges(config) !== "auto") return void 0;
|
|
220
|
+
const floor = config?.systemOne?.minConfidence?.edges;
|
|
221
|
+
if (isEdgesFloor(floor)) return floor;
|
|
222
|
+
warnOnce(
|
|
223
|
+
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
|
|
224
|
+
);
|
|
225
|
+
return void 0;
|
|
226
|
+
}
|
|
227
|
+
function resolveResolveMinConfidence(config) {
|
|
228
|
+
if (resolveSystemOneResolve(config) !== "auto") return void 0;
|
|
229
|
+
const floor = config?.systemOne?.minConfidence?.resolve;
|
|
230
|
+
if (isEdgesFloor(floor)) return floor;
|
|
231
|
+
warnOnce(
|
|
232
|
+
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
|
|
233
|
+
);
|
|
234
|
+
return void 0;
|
|
235
|
+
}
|
|
236
|
+
function resolveSystemOneHealScreen(config) {
|
|
237
|
+
const healScreen = config?.systemOne?.healScreen;
|
|
238
|
+
if (healScreen !== void 0 && !isTypingMode(healScreen)) {
|
|
239
|
+
warnOnce(
|
|
240
|
+
`[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
241
|
+
);
|
|
242
|
+
return "llm";
|
|
243
|
+
}
|
|
244
|
+
return healScreen ?? "llm";
|
|
245
|
+
}
|
|
246
|
+
function resolveSystemOneTypeOnWrite(config) {
|
|
247
|
+
const typeOnWrite = config?.systemOne?.typeOnWrite;
|
|
248
|
+
if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
|
|
249
|
+
warnOnce(
|
|
250
|
+
`[core-llm-wiki] systemOne: \`systemOne.typeOnWrite\` is ${formatConfigValue(typeOnWrite)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
251
|
+
);
|
|
252
|
+
return "llm";
|
|
253
|
+
}
|
|
254
|
+
return typeOnWrite ?? "llm";
|
|
255
|
+
}
|
|
256
|
+
function resolveHealScreenMinConfidence(config) {
|
|
257
|
+
if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
|
|
258
|
+
const floor = config?.systemOne?.minConfidence?.healScreen;
|
|
259
|
+
if (isEdgesFloor(floor)) return floor;
|
|
260
|
+
warnOnce(
|
|
261
|
+
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
|
|
262
|
+
);
|
|
263
|
+
return void 0;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// src/utils/classifier.ts
|
|
267
|
+
var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
268
|
+
function validateClassifierAnswer(response, key, question) {
|
|
269
|
+
try {
|
|
270
|
+
if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
|
|
271
|
+
const answers = response.answers;
|
|
272
|
+
if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
|
|
273
|
+
if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
|
|
274
|
+
const raw = answers[key];
|
|
275
|
+
if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
|
|
276
|
+
const a = raw;
|
|
277
|
+
if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
|
|
278
|
+
if (question.kind === "choice") {
|
|
279
|
+
if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
|
|
280
|
+
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
281
|
+
const probs = a.probabilities;
|
|
282
|
+
if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
|
|
283
|
+
const probabilities = {};
|
|
284
|
+
for (const [k, v] of Object.entries(probs)) {
|
|
285
|
+
if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
|
|
286
|
+
probabilities[k] = v;
|
|
287
|
+
}
|
|
288
|
+
return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
|
|
289
|
+
}
|
|
290
|
+
if (question.kind === "binary") {
|
|
291
|
+
if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
|
|
292
|
+
return { ok: true, answer: { kind: "binary", probability: a.probability } };
|
|
293
|
+
}
|
|
294
|
+
const maxScore = question.levels.length - 1;
|
|
295
|
+
if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
|
|
296
|
+
return { ok: false, reason: "score_out_of_range" };
|
|
297
|
+
}
|
|
298
|
+
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
299
|
+
if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
|
|
300
|
+
return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
|
|
301
|
+
} catch {
|
|
302
|
+
return { ok: false, reason: "malformed" };
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function classifierStateForFact(fact) {
|
|
306
|
+
const parts = [fact.title, fact.body];
|
|
307
|
+
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
308
|
+
return parts.join("\n\n");
|
|
309
|
+
}
|
|
310
|
+
|
|
18
311
|
// src/utils/diagnostics.ts
|
|
19
312
|
var SEVERITY = {
|
|
20
313
|
ingest_chunk_failed: "warn",
|
|
@@ -38,6 +331,8 @@ var SEVERITY = {
|
|
|
38
331
|
llm_usage: "info",
|
|
39
332
|
librarian_gate: "info",
|
|
40
333
|
librarian_op_rejected: "warn",
|
|
334
|
+
librarian_rewritten: "info",
|
|
335
|
+
librarian_superseded: "info",
|
|
41
336
|
contradicts_document: "warn",
|
|
42
337
|
resolve_failed: "warn",
|
|
43
338
|
read_budget: "info",
|
|
@@ -56,11 +351,14 @@ var SEVERITY = {
|
|
|
56
351
|
event_created_at_clamped: "warn",
|
|
57
352
|
event_created_at_restamped: "info",
|
|
58
353
|
external_deletion_pending: "warn",
|
|
354
|
+
supersede_scheduled_end_replaced: "info",
|
|
59
355
|
external_deletion_discarded: "warn",
|
|
60
356
|
guidance_too_long: "warn",
|
|
61
357
|
guidance_resolver_failed: "warn",
|
|
62
358
|
source_pointer_unresolved: "warn",
|
|
63
359
|
source_pointer_invalid: "warn",
|
|
360
|
+
source_event_gone: "warn",
|
|
361
|
+
derived_events_invalid: "warn",
|
|
64
362
|
source_store_source_too_large: "warn",
|
|
65
363
|
source_store_budget_exceeded: "warn",
|
|
66
364
|
source_store_hash_mismatch: "warn",
|
|
@@ -93,6 +391,8 @@ var MESSAGE = {
|
|
|
93
391
|
llm_usage: "An LLM call completed; token usage attached.",
|
|
94
392
|
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
95
393
|
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
394
|
+
librarian_rewritten: "The librarian rewrote an engine-inferred fact in place; the previous text was not kept.",
|
|
395
|
+
librarian_superseded: "The librarian ended a fact\u2019s validity with a replacement fact.",
|
|
96
396
|
contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
|
|
97
397
|
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
98
398
|
read_budget: "A read was packed to a token budget.",
|
|
@@ -110,12 +410,15 @@ var MESSAGE = {
|
|
|
110
410
|
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.",
|
|
111
411
|
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.",
|
|
112
412
|
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.",
|
|
413
|
+
supersede_scheduled_end_replaced: "A supersede replaced a scheduled end date on the old fact; the prior end is kept in prior_valid_to and reopen() can restore it.",
|
|
113
414
|
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
114
415
|
external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
|
|
115
416
|
guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
|
|
116
417
|
guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
|
|
117
|
-
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
|
|
418
|
+
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one, or the librarian merged such an unattributed candidate into this fact in place (its derived_events list was not extended).",
|
|
118
419
|
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
|
|
420
|
+
source_event_gone: "A librarian candidate was dropped at apply time because the event it came from no longer exists (deleted outside the engine while the pass ran).",
|
|
421
|
+
derived_events_invalid: "Import met a malformed derived_events value and stored null.",
|
|
119
422
|
source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
|
|
120
423
|
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
121
424
|
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
@@ -246,28 +549,102 @@ function edgeDropDiagnostic(drop, ctx) {
|
|
|
246
549
|
return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
|
|
247
550
|
}
|
|
248
551
|
|
|
249
|
-
// src/
|
|
250
|
-
function
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
552
|
+
// src/utils/usage.ts
|
|
553
|
+
function estimateTokens(text) {
|
|
554
|
+
return Math.ceil(text.length / 4);
|
|
555
|
+
}
|
|
556
|
+
var UsageMeter = class {
|
|
557
|
+
constructor(budget) {
|
|
558
|
+
this.used = 0;
|
|
559
|
+
this.estimated = false;
|
|
560
|
+
if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
|
|
561
|
+
throw new TypeError("tokenBudget must be a finite number >= 0");
|
|
562
|
+
}
|
|
563
|
+
this.budget = budget;
|
|
564
|
+
}
|
|
565
|
+
get remaining() {
|
|
566
|
+
return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
|
|
567
|
+
}
|
|
568
|
+
fits(estimate) {
|
|
569
|
+
return estimate <= this.remaining;
|
|
570
|
+
}
|
|
571
|
+
record(r) {
|
|
572
|
+
this.used += r.inputTokens + r.outputTokens;
|
|
573
|
+
if (r.estimated) this.estimated = true;
|
|
574
|
+
}
|
|
575
|
+
};
|
|
576
|
+
var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
|
|
577
|
+
constructor(requiredEstimate, remaining) {
|
|
578
|
+
super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
|
|
579
|
+
this.name = "WikiBudgetExhausted";
|
|
580
|
+
this.requiredEstimate = requiredEstimate;
|
|
581
|
+
this.remaining = remaining;
|
|
582
|
+
Object.setPrototypeOf(this, _WikiBudgetExhausted.prototype);
|
|
583
|
+
}
|
|
584
|
+
};
|
|
585
|
+
|
|
586
|
+
// src/utils/llmCall.ts
|
|
587
|
+
function validUsage(u) {
|
|
588
|
+
if (!u || typeof u !== "object") return false;
|
|
589
|
+
const { inputTokens, outputTokens } = u;
|
|
590
|
+
return [inputTokens, outputTokens].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0);
|
|
591
|
+
}
|
|
592
|
+
async function callLlm(options, ctx, prompts) {
|
|
593
|
+
const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
|
|
594
|
+
if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
|
|
595
|
+
throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
|
|
596
|
+
}
|
|
597
|
+
const provider = options.llmProvider;
|
|
598
|
+
const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
|
|
599
|
+
let text;
|
|
600
|
+
let reported;
|
|
601
|
+
if (typeof provider.generateTextWithUsage === "function") {
|
|
602
|
+
const result = await provider.generateTextWithUsage(params);
|
|
603
|
+
if (!result || typeof result.text !== "string") {
|
|
604
|
+
throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
|
|
257
605
|
}
|
|
606
|
+
text = result.text;
|
|
607
|
+
reported = validUsage(result.usage) ? result.usage : void 0;
|
|
608
|
+
} else {
|
|
609
|
+
text = await provider.generateText(params);
|
|
258
610
|
}
|
|
259
|
-
|
|
611
|
+
const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
|
|
612
|
+
ctx.meter?.record(record);
|
|
613
|
+
if (options.config?.reportLlmUsage === true) {
|
|
614
|
+
emitDiagnostic(options, {
|
|
615
|
+
code: "llm_usage",
|
|
616
|
+
operation: ctx.operation,
|
|
617
|
+
trigger: ctx.trigger,
|
|
618
|
+
entityId: ctx.entityId,
|
|
619
|
+
detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
return text;
|
|
260
623
|
}
|
|
261
|
-
function
|
|
262
|
-
|
|
263
|
-
if (
|
|
264
|
-
|
|
265
|
-
const p = JSON.parse(s);
|
|
266
|
-
if (p && typeof p === "object" && !Array.isArray(p)) return p;
|
|
267
|
-
} catch {
|
|
268
|
-
}
|
|
624
|
+
async function callClassify(options, ctx, request) {
|
|
625
|
+
const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
|
|
626
|
+
if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
|
|
627
|
+
throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
|
|
269
628
|
}
|
|
270
|
-
|
|
629
|
+
const provider = options.llmProvider;
|
|
630
|
+
if (typeof provider.classify !== "function") {
|
|
631
|
+
throw new TypeError("callClassify requires a provider with classify()");
|
|
632
|
+
}
|
|
633
|
+
const response = await provider.classify(request);
|
|
634
|
+
const reported = validUsage(response?.usage) ? response.usage : void 0;
|
|
635
|
+
const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
|
|
636
|
+
const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
|
|
637
|
+
ctx.meter?.record(record);
|
|
638
|
+
if (options.config?.reportLlmUsage === true) {
|
|
639
|
+
emitDiagnostic(options, {
|
|
640
|
+
code: "llm_usage",
|
|
641
|
+
operation: ctx.operation,
|
|
642
|
+
trigger: ctx.trigger,
|
|
643
|
+
entityId: ctx.entityId,
|
|
644
|
+
detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
return response;
|
|
271
648
|
}
|
|
272
649
|
|
|
273
650
|
// src/db/sqliteCodes.ts
|
|
@@ -477,19 +854,234 @@ var WikiMigrationRequiredError = class _WikiMigrationRequiredError extends Error
|
|
|
477
854
|
Error.captureStackTrace(this, _WikiMigrationRequiredError);
|
|
478
855
|
}
|
|
479
856
|
}
|
|
480
|
-
};
|
|
481
|
-
var WikiSearchUnavailableError = class extends Error {
|
|
482
|
-
constructor(message = "Keyword search is temporarily unavailable", cause) {
|
|
483
|
-
super(message, cause !== void 0 ? { cause } : void 0);
|
|
484
|
-
this.name = "WikiSearchUnavailableError";
|
|
857
|
+
};
|
|
858
|
+
var WikiSearchUnavailableError = class extends Error {
|
|
859
|
+
constructor(message = "Keyword search is temporarily unavailable", cause) {
|
|
860
|
+
super(message, cause !== void 0 ? { cause } : void 0);
|
|
861
|
+
this.name = "WikiSearchUnavailableError";
|
|
862
|
+
}
|
|
863
|
+
};
|
|
864
|
+
function isWikiSearchUnavailableError(err) {
|
|
865
|
+
try {
|
|
866
|
+
return err instanceof WikiSearchUnavailableError;
|
|
867
|
+
} catch {
|
|
868
|
+
return false;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/utils/ontology.ts
|
|
873
|
+
function emptyManifest() {
|
|
874
|
+
return { node_types: [], edge_types: [] };
|
|
875
|
+
}
|
|
876
|
+
function normalizeTitleKey(title) {
|
|
877
|
+
return title.trim().toLowerCase().replace(/\s+/g, " ");
|
|
878
|
+
}
|
|
879
|
+
function normalizeSlug(raw) {
|
|
880
|
+
return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
|
|
881
|
+
}
|
|
882
|
+
function resolveNodeTypeMatch(raw, manifest) {
|
|
883
|
+
const slug = typeof raw === "string" ? raw.trim() : "";
|
|
884
|
+
if (!slug) return null;
|
|
885
|
+
const lowered = slug.toLowerCase();
|
|
886
|
+
const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
|
|
887
|
+
if (exact) return { slug: exact.type, via: "exact" };
|
|
888
|
+
const normalized = normalizeSlug(slug);
|
|
889
|
+
if (!normalized) return null;
|
|
890
|
+
const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
|
|
891
|
+
return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
|
|
892
|
+
}
|
|
893
|
+
function resolveNodeType(raw, manifest) {
|
|
894
|
+
return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
|
|
895
|
+
}
|
|
896
|
+
var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
|
|
897
|
+
function isReservedAbstainSlug(raw) {
|
|
898
|
+
return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
|
|
899
|
+
}
|
|
900
|
+
function resolveEdgeDefinitions(rawEdgeType, manifest) {
|
|
901
|
+
const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
|
|
902
|
+
if (!slug) return [];
|
|
903
|
+
const lowered = slug.toLowerCase();
|
|
904
|
+
const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
|
|
905
|
+
if (exact.length > 0) return exact;
|
|
906
|
+
const normalized = normalizeSlug(slug);
|
|
907
|
+
if (!normalized) return [];
|
|
908
|
+
const names = new Set(
|
|
909
|
+
manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
|
|
910
|
+
);
|
|
911
|
+
if (names.size !== 1) return [];
|
|
912
|
+
return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
|
|
913
|
+
}
|
|
914
|
+
function edgeTripleKey(type, sourceType, targetType) {
|
|
915
|
+
return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
|
|
916
|
+
}
|
|
917
|
+
function typeSatisfies(declaredType, concreteType, manifest) {
|
|
918
|
+
const concrete = concreteType.trim().toLowerCase();
|
|
919
|
+
const declared = declaredType.trim().toLowerCase();
|
|
920
|
+
if (!concrete || !declared) return false;
|
|
921
|
+
if (declared === concrete) return true;
|
|
922
|
+
const def = (manifest.node_types ?? []).find(
|
|
923
|
+
(n) => typeof n?.type === "string" && n.type.trim().toLowerCase() === concrete
|
|
924
|
+
);
|
|
925
|
+
const parent = typeof def?.parent_type === "string" ? def.parent_type.trim().toLowerCase() : "";
|
|
926
|
+
return parent !== "" && parent === declared;
|
|
927
|
+
}
|
|
928
|
+
function edgeTripleAllowed(manifest, edgeType, sourceType, targetType) {
|
|
929
|
+
const wanted = edgeType.trim().toLowerCase();
|
|
930
|
+
return (manifest.edge_types ?? []).some((d) => typeof d?.type === "string" && d.type.trim().toLowerCase() === wanted && typeof d.source_type === "string" && typeSatisfies(d.source_type, sourceType, manifest) && typeof d.target_type === "string" && typeSatisfies(d.target_type, targetType, manifest));
|
|
931
|
+
}
|
|
932
|
+
function validateManifest(manifest) {
|
|
933
|
+
const nodeSlugs = /* @__PURE__ */ new Set();
|
|
934
|
+
for (const node of manifest.node_types ?? []) {
|
|
935
|
+
const type = node.type?.trim();
|
|
936
|
+
if (!type) throw new Error("Ontology node type slug must be non-empty");
|
|
937
|
+
const key = type.toLowerCase();
|
|
938
|
+
if (nodeSlugs.has(key)) throw new Error(`Duplicate node type: ${type}`);
|
|
939
|
+
nodeSlugs.add(key);
|
|
940
|
+
}
|
|
941
|
+
const parentOf = /* @__PURE__ */ new Map();
|
|
942
|
+
for (const node of manifest.node_types ?? []) {
|
|
943
|
+
const parent = typeof node.parent_type === "string" ? node.parent_type.trim().toLowerCase() : void 0;
|
|
944
|
+
parentOf.set(node.type.trim().toLowerCase(), parent);
|
|
945
|
+
}
|
|
946
|
+
for (const node of manifest.node_types ?? []) {
|
|
947
|
+
if (node.parent_type === void 0) continue;
|
|
948
|
+
if (typeof node.parent_type !== "string" || !node.parent_type.trim()) {
|
|
949
|
+
throw new Error(`Ontology parent_type must be a non-empty string when present: ${node.type}`);
|
|
950
|
+
}
|
|
951
|
+
const parentSlug = node.parent_type.trim().toLowerCase();
|
|
952
|
+
if (parentSlug === node.type.trim().toLowerCase()) {
|
|
953
|
+
throw new Error(`Self-parent: ${node.type}`);
|
|
954
|
+
}
|
|
955
|
+
if (!nodeSlugs.has(parentSlug)) {
|
|
956
|
+
throw new Error(`Parent type not found: ${node.parent_type}`);
|
|
957
|
+
}
|
|
958
|
+
const grandparent = parentOf.get(parentSlug);
|
|
959
|
+
if (grandparent) {
|
|
960
|
+
throw new Error(`Parent chain too deep: ${node.type} \u2192 ${node.parent_type} \u2192 ${grandparent}`);
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
const edgeKeys = /* @__PURE__ */ new Set();
|
|
964
|
+
const edgeNames = /* @__PURE__ */ new Map();
|
|
965
|
+
for (const edge of manifest.edge_types ?? []) {
|
|
966
|
+
const edgeType = edge.type?.trim();
|
|
967
|
+
const sourceType = edge.source_type?.trim();
|
|
968
|
+
const targetType = edge.target_type?.trim();
|
|
969
|
+
if (!edgeType) throw new Error("Ontology edge type slug must be non-empty");
|
|
970
|
+
if (!sourceType || !targetType || !nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
|
|
971
|
+
throw new Error(`Edge type ${edgeType} references unknown node type`);
|
|
972
|
+
}
|
|
973
|
+
const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
|
|
974
|
+
if (edgeKeys.has(edgeKey)) {
|
|
975
|
+
throw new Error(`Duplicate edge definition: ${edgeType} (${sourceType} \u2192 ${targetType})`);
|
|
976
|
+
}
|
|
977
|
+
edgeKeys.add(edgeKey);
|
|
978
|
+
const canonical = edgeNames.get(edgeType.toLowerCase());
|
|
979
|
+
if (canonical === void 0) {
|
|
980
|
+
edgeNames.set(edgeType.toLowerCase(), edgeType);
|
|
981
|
+
} else if (canonical !== edgeType) {
|
|
982
|
+
throw new Error(`Inconsistent casing for edge type: ${edgeType} conflicts with ${canonical}`);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
function buildDeclaresParentIndex(nodes) {
|
|
987
|
+
const declaresParent = /* @__PURE__ */ new Map();
|
|
988
|
+
for (const n of nodes) {
|
|
989
|
+
const slug = typeof n?.type === "string" ? n.type.trim().toLowerCase() : "";
|
|
990
|
+
if (!slug || declaresParent.has(slug)) continue;
|
|
991
|
+
declaresParent.set(slug, n?.parent_type !== void 0);
|
|
992
|
+
}
|
|
993
|
+
return declaresParent;
|
|
994
|
+
}
|
|
995
|
+
function mergeOntologyUpdates(current, updates) {
|
|
996
|
+
const node_types = [...current.node_types];
|
|
997
|
+
const edge_types = [...current.edge_types];
|
|
998
|
+
const rejected = [];
|
|
999
|
+
const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
|
|
1000
|
+
const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
|
|
1001
|
+
const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
|
|
1002
|
+
const declaresParent = buildDeclaresParentIndex([
|
|
1003
|
+
...current.node_types,
|
|
1004
|
+
...updates.node_types ?? []
|
|
1005
|
+
]);
|
|
1006
|
+
for (const node of updates.node_types ?? []) {
|
|
1007
|
+
const type = node?.type?.trim();
|
|
1008
|
+
if (!type) {
|
|
1009
|
+
rejected.push("invalid_shape");
|
|
1010
|
+
continue;
|
|
1011
|
+
}
|
|
1012
|
+
const key = type.toLowerCase();
|
|
1013
|
+
if (nodeSlugs.has(key)) {
|
|
1014
|
+
rejected.push("duplicate_node_type");
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
|
|
1018
|
+
const parentSlug = rawParent.toLowerCase();
|
|
1019
|
+
const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
|
|
1020
|
+
node_types.push({
|
|
1021
|
+
type,
|
|
1022
|
+
description: String(node.description ?? ""),
|
|
1023
|
+
...keepParent ? { parent_type: rawParent } : {}
|
|
1024
|
+
});
|
|
1025
|
+
nodeSlugs.add(key);
|
|
1026
|
+
}
|
|
1027
|
+
for (const edge of updates.edge_types ?? []) {
|
|
1028
|
+
const rawEdgeType = edge?.type?.trim();
|
|
1029
|
+
const sourceType = edge?.source_type?.trim();
|
|
1030
|
+
const targetType = edge?.target_type?.trim();
|
|
1031
|
+
if (!rawEdgeType || !sourceType || !targetType) {
|
|
1032
|
+
rejected.push("invalid_shape");
|
|
1033
|
+
continue;
|
|
1034
|
+
}
|
|
1035
|
+
const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
|
|
1036
|
+
const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
|
|
1037
|
+
if (edgeKeys.has(edgeKey)) {
|
|
1038
|
+
rejected.push("duplicate_edge");
|
|
1039
|
+
continue;
|
|
1040
|
+
}
|
|
1041
|
+
if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
|
|
1042
|
+
rejected.push("unknown_endpoint");
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
edgeNames.set(edgeType.toLowerCase(), edgeType);
|
|
1046
|
+
edge_types.push({
|
|
1047
|
+
type: edgeType,
|
|
1048
|
+
source_type: sourceType,
|
|
1049
|
+
target_type: targetType,
|
|
1050
|
+
description: String(edge.description ?? "")
|
|
1051
|
+
});
|
|
1052
|
+
edgeKeys.add(edgeKey);
|
|
1053
|
+
}
|
|
1054
|
+
return { manifest: { node_types, edge_types }, rejected };
|
|
1055
|
+
}
|
|
1056
|
+
function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
|
|
1057
|
+
const strict = opts?.strict === true;
|
|
1058
|
+
const entityId = opts?.entityId ?? "";
|
|
1059
|
+
const drops = opts?.drops;
|
|
1060
|
+
const drop = (reason, edgeType) => {
|
|
1061
|
+
drops?.push({ reason, sourceId: null, edgeType, sourceNodeType: sourceType, targetNodeType: null });
|
|
1062
|
+
};
|
|
1063
|
+
if (!Array.isArray(edges)) {
|
|
1064
|
+
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", "");
|
|
1065
|
+
drop("invalid_shape", null);
|
|
1066
|
+
return [];
|
|
485
1067
|
}
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
1068
|
+
const valid = [];
|
|
1069
|
+
for (const edge of edges) {
|
|
1070
|
+
if (typeof edge?.edge_type !== "string" || typeof edge?.target_title !== "string") {
|
|
1071
|
+
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", String(edge?.edge_type ?? ""));
|
|
1072
|
+
drop("invalid_shape", typeof edge?.edge_type === "string" ? edge.edge_type : null);
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
const defs = resolveEdgeDefinitions(edge.edge_type, manifest);
|
|
1076
|
+
const match = defs.find((d) => typeSatisfies(d.source_type, sourceType, manifest));
|
|
1077
|
+
if (!match) {
|
|
1078
|
+
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", edge.edge_type);
|
|
1079
|
+
drop("type_not_in_manifest", edge.edge_type);
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
valid.push({ edge_type: match.type, target_title: edge.target_title });
|
|
492
1083
|
}
|
|
1084
|
+
return valid;
|
|
493
1085
|
}
|
|
494
1086
|
|
|
495
1087
|
// src/utils/pure.ts
|
|
@@ -1006,6 +1598,336 @@ function jaccardScore(a, b) {
|
|
|
1006
1598
|
return intersection.size / union.size;
|
|
1007
1599
|
}
|
|
1008
1600
|
|
|
1601
|
+
// src/services/BoundedLlmCall.ts
|
|
1602
|
+
var DEFAULT_BATCH_SIZE = 10;
|
|
1603
|
+
var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
|
|
1604
|
+
var OUTPUT_BUDGET_FRACTION = 0.8;
|
|
1605
|
+
var TRUNCATION_PATTERNS = [
|
|
1606
|
+
/truncat/i,
|
|
1607
|
+
/token limit/i,
|
|
1608
|
+
/max(imum)?[ _-]?tokens?/i,
|
|
1609
|
+
/output limit/i,
|
|
1610
|
+
/length limit/i,
|
|
1611
|
+
/finish[_ ]?reason/i
|
|
1612
|
+
];
|
|
1613
|
+
var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
|
|
1614
|
+
var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
|
|
1615
|
+
var CONTEXT_OVERFLOW_PATTERNS = [
|
|
1616
|
+
/maximum context length/i,
|
|
1617
|
+
/context[_ ]?length[_ ]?exceeded/i,
|
|
1618
|
+
/prompt is too long/i,
|
|
1619
|
+
/input (token count|is too long)/i,
|
|
1620
|
+
/exceeds? the (available )?context( size)?/i,
|
|
1621
|
+
// Tail requires a context-window clause (context|maximum), NOT bare `token`:
|
|
1622
|
+
// a 429 body like "input exceeds the tokens-per-minute limit" must NOT
|
|
1623
|
+
// classify as input overflow (it would split the batch and stamp a cooldown).
|
|
1624
|
+
/(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
|
|
1625
|
+
/context limit/i,
|
|
1626
|
+
// llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
|
|
1627
|
+
/\bcontext is full\b/i,
|
|
1628
|
+
/too long for (the )?requested model/i,
|
|
1629
|
+
// vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
|
|
1630
|
+
// "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
|
|
1631
|
+
/max[_ ]?tokens?.{0,40}too large.{0,80}context/i
|
|
1632
|
+
];
|
|
1633
|
+
function isContextOverflowError(err) {
|
|
1634
|
+
const message = getErrorMessage(err);
|
|
1635
|
+
if (message === void 0) return false;
|
|
1636
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
1637
|
+
return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
|
|
1638
|
+
}
|
|
1639
|
+
function getErrorMessage(err) {
|
|
1640
|
+
try {
|
|
1641
|
+
return err instanceof Error ? err.message : String(err ?? "");
|
|
1642
|
+
} catch {
|
|
1643
|
+
return void 0;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
function isTruncationError(err) {
|
|
1647
|
+
const message = getErrorMessage(err);
|
|
1648
|
+
if (message === void 0) return false;
|
|
1649
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
1650
|
+
if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
|
|
1651
|
+
return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
|
|
1652
|
+
}
|
|
1653
|
+
function isConfigError(err) {
|
|
1654
|
+
const message = getErrorMessage(err);
|
|
1655
|
+
if (message === void 0) return false;
|
|
1656
|
+
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
1657
|
+
return EXCEEDS_LIMIT_PATTERN.test(message);
|
|
1658
|
+
}
|
|
1659
|
+
function initialBatchSize(maxOutputTokens) {
|
|
1660
|
+
if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
|
|
1661
|
+
return DEFAULT_BATCH_SIZE;
|
|
1662
|
+
}
|
|
1663
|
+
const estimate = Math.floor(
|
|
1664
|
+
maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
|
|
1665
|
+
);
|
|
1666
|
+
return Math.max(DEFAULT_BATCH_SIZE, estimate);
|
|
1667
|
+
}
|
|
1668
|
+
var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
|
|
1669
|
+
async function runBatched(args) {
|
|
1670
|
+
const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
|
|
1671
|
+
const results = [];
|
|
1672
|
+
const skipped = [];
|
|
1673
|
+
let batches = 0;
|
|
1674
|
+
const settled = /* @__PURE__ */ new Set();
|
|
1675
|
+
let budgetStop;
|
|
1676
|
+
let batchSize = initialBatchSize(maxOutputTokens);
|
|
1677
|
+
const trim = async (candidate) => {
|
|
1678
|
+
const whole = await buildPrompt(candidate);
|
|
1679
|
+
if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
|
|
1680
|
+
return { batch: candidate, prompts: whole };
|
|
1681
|
+
}
|
|
1682
|
+
let low = 2;
|
|
1683
|
+
let high = candidate.length - 1;
|
|
1684
|
+
let best;
|
|
1685
|
+
let bestPrompts;
|
|
1686
|
+
while (low <= high) {
|
|
1687
|
+
const mid = Math.floor((low + high) / 2);
|
|
1688
|
+
const batch = candidate.slice(0, mid);
|
|
1689
|
+
const prompts = await buildPrompt(batch);
|
|
1690
|
+
if (promptLength(prompts) <= maxPromptChars) {
|
|
1691
|
+
best = batch;
|
|
1692
|
+
bestPrompts = prompts;
|
|
1693
|
+
low = mid + 1;
|
|
1694
|
+
} else {
|
|
1695
|
+
high = mid - 1;
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
|
|
1699
|
+
const single = candidate.slice(0, 1);
|
|
1700
|
+
return { batch: single, prompts: await buildPrompt(single) };
|
|
1701
|
+
};
|
|
1702
|
+
const onFailure = async (batch, err, attemptLevel, fromCall) => {
|
|
1703
|
+
if (batch.length === 1) {
|
|
1704
|
+
if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
|
|
1705
|
+
await attempt(batch, void 0, attemptLevel + 1);
|
|
1706
|
+
} else {
|
|
1707
|
+
const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
|
|
1708
|
+
skipped.push({ item: batch[0], reason });
|
|
1709
|
+
settled.add(batch[0]);
|
|
1710
|
+
onSkip?.(batch[0], err);
|
|
1711
|
+
}
|
|
1712
|
+
return;
|
|
1713
|
+
}
|
|
1714
|
+
if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
|
|
1715
|
+
const mid = Math.ceil(batch.length / 2);
|
|
1716
|
+
if (mid < batchSize) batchSize = mid;
|
|
1717
|
+
let i = 0;
|
|
1718
|
+
while (i < batch.length && !budgetStop) {
|
|
1719
|
+
const size = Math.min(batchSize, batch.length - i);
|
|
1720
|
+
const trimmed = await trim(batch.slice(i, i + size));
|
|
1721
|
+
await attempt(trimmed.batch, trimmed.prompts);
|
|
1722
|
+
i += trimmed.batch.length;
|
|
1723
|
+
}
|
|
1724
|
+
};
|
|
1725
|
+
const attempt = async (batch, prebuilt, attemptLevel = 0) => {
|
|
1726
|
+
if (budgetStop) return;
|
|
1727
|
+
if (batch.length === 0) return;
|
|
1728
|
+
const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
|
|
1729
|
+
batches++;
|
|
1730
|
+
let responseText;
|
|
1731
|
+
try {
|
|
1732
|
+
responseText = await call(prompts);
|
|
1733
|
+
} catch (err) {
|
|
1734
|
+
if (err instanceof WikiBudgetExhausted) {
|
|
1735
|
+
budgetStop = { requiredEstimate: err.requiredEstimate };
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
await onFailure(batch, err, attemptLevel, true);
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
let result;
|
|
1742
|
+
try {
|
|
1743
|
+
result = parse(responseText, batch, prompts);
|
|
1744
|
+
} catch (err) {
|
|
1745
|
+
await onFailure(batch, err, attemptLevel, false);
|
|
1746
|
+
return;
|
|
1747
|
+
}
|
|
1748
|
+
results.push(result);
|
|
1749
|
+
for (const item of batch) settled.add(item);
|
|
1750
|
+
};
|
|
1751
|
+
let index = 0;
|
|
1752
|
+
while (index < items.length && !budgetStop) {
|
|
1753
|
+
const { batch, prompts } = await trim(items.slice(index, index + batchSize));
|
|
1754
|
+
index += batch.length;
|
|
1755
|
+
await attempt(batch, prompts, 0);
|
|
1756
|
+
}
|
|
1757
|
+
const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
|
|
1758
|
+
return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
|
|
1759
|
+
}
|
|
1760
|
+
|
|
1761
|
+
// src/services/typing/typeOnWrite.ts
|
|
1762
|
+
var CLASSIFIER_MAX_CHOICES = 255;
|
|
1763
|
+
function isManifestRepresentable(manifest) {
|
|
1764
|
+
const slugs = manifest.node_types.map((n) => n.type);
|
|
1765
|
+
return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
|
|
1766
|
+
}
|
|
1767
|
+
function canEngageWriteTyping(config, provider, mode, manifest) {
|
|
1768
|
+
return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
|
|
1769
|
+
}
|
|
1770
|
+
function buildTypingQuestion(manifest) {
|
|
1771
|
+
return {
|
|
1772
|
+
kind: "choice",
|
|
1773
|
+
options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
|
|
1774
|
+
instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
|
|
1775
|
+
` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
|
|
1776
|
+
};
|
|
1777
|
+
}
|
|
1778
|
+
function volunteeredTypeResolves(rawOkfType, manifest) {
|
|
1779
|
+
return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
|
|
1780
|
+
}
|
|
1781
|
+
async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
|
|
1782
|
+
const question = buildTypingQuestion(manifest);
|
|
1783
|
+
const rawConcurrency = options.config?.chunkConcurrency ?? 1;
|
|
1784
|
+
const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
|
|
1785
|
+
let stopped = false;
|
|
1786
|
+
return withConcurrency(
|
|
1787
|
+
facts.map((fact) => async () => {
|
|
1788
|
+
if (stopped) return { kind: "unattempted" };
|
|
1789
|
+
let response;
|
|
1790
|
+
try {
|
|
1791
|
+
response = await callClassify(
|
|
1792
|
+
options,
|
|
1793
|
+
{ operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
|
|
1794
|
+
{ state: classifierStateForFact(fact), questions: { okf_type: question } }
|
|
1795
|
+
);
|
|
1796
|
+
} catch (err) {
|
|
1797
|
+
if (err instanceof WikiBudgetExhausted) {
|
|
1798
|
+
stopped = true;
|
|
1799
|
+
return { kind: "unattempted" };
|
|
1800
|
+
}
|
|
1801
|
+
if (isContextOverflowError(err)) return { kind: "overflow_skip" };
|
|
1802
|
+
return { kind: "threw" };
|
|
1803
|
+
}
|
|
1804
|
+
const checked = validateClassifierAnswer(response, "okf_type", question);
|
|
1805
|
+
if (!checked.ok) return { kind: "invalid", reason: checked.reason };
|
|
1806
|
+
if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
|
|
1807
|
+
if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
|
|
1808
|
+
if (checked.answer.confidence < floor) return { kind: "low_confidence" };
|
|
1809
|
+
return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
|
|
1810
|
+
}),
|
|
1811
|
+
concurrency
|
|
1812
|
+
);
|
|
1813
|
+
}
|
|
1814
|
+
function emptyTypingCounters() {
|
|
1815
|
+
return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
|
|
1816
|
+
}
|
|
1817
|
+
function tallyTypingOutcome(c, o) {
|
|
1818
|
+
switch (o.kind) {
|
|
1819
|
+
case "unattempted":
|
|
1820
|
+
c.unattempted++;
|
|
1821
|
+
return;
|
|
1822
|
+
case "accepted":
|
|
1823
|
+
c.asked++;
|
|
1824
|
+
return;
|
|
1825
|
+
case "abstain":
|
|
1826
|
+
c.asked++;
|
|
1827
|
+
c.abstained++;
|
|
1828
|
+
return;
|
|
1829
|
+
case "low_confidence":
|
|
1830
|
+
c.asked++;
|
|
1831
|
+
c.lowConfidence++;
|
|
1832
|
+
return;
|
|
1833
|
+
case "invalid":
|
|
1834
|
+
case "threw":
|
|
1835
|
+
c.asked++;
|
|
1836
|
+
c.invalid++;
|
|
1837
|
+
return;
|
|
1838
|
+
case "overflow_skip":
|
|
1839
|
+
c.asked++;
|
|
1840
|
+
c.skipped++;
|
|
1841
|
+
return;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
function typingOutcomeReceipt(base, factId, outcome) {
|
|
1845
|
+
switch (outcome.kind) {
|
|
1846
|
+
case "abstain":
|
|
1847
|
+
return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
|
|
1848
|
+
case "low_confidence":
|
|
1849
|
+
return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
|
|
1850
|
+
case "invalid":
|
|
1851
|
+
return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
|
|
1852
|
+
case "threw":
|
|
1853
|
+
return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
|
|
1854
|
+
case "overflow_skip":
|
|
1855
|
+
return { ...base, code: "context_overflow_skipped", detail: { factId } };
|
|
1856
|
+
default:
|
|
1857
|
+
return null;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
|
|
1861
|
+
const drops = [];
|
|
1862
|
+
const receipts = [];
|
|
1863
|
+
const emit = shouldEmitOntologyReceipt(mode);
|
|
1864
|
+
let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
|
|
1865
|
+
if (emit) {
|
|
1866
|
+
receipts.push(...nodeTypeReceipts(
|
|
1867
|
+
base,
|
|
1868
|
+
factId,
|
|
1869
|
+
typeof fact.okf_type === "string" ? fact.okf_type : "",
|
|
1870
|
+
normalized.okf_type,
|
|
1871
|
+
normalized.match
|
|
1872
|
+
));
|
|
1873
|
+
}
|
|
1874
|
+
let typedByClassifier = false;
|
|
1875
|
+
if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
|
|
1876
|
+
const second = ontology?.validateAndNormalizeFact(
|
|
1877
|
+
{ ...fact, okf_type: outcome.okfType, edges: [] },
|
|
1878
|
+
manifest,
|
|
1879
|
+
{ strict: false }
|
|
1880
|
+
) ?? { okf_type: null};
|
|
1881
|
+
if (emit) {
|
|
1882
|
+
receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
|
|
1883
|
+
}
|
|
1884
|
+
normalized = { okf_type: second.okf_type, edges: [] };
|
|
1885
|
+
if (second.okf_type) {
|
|
1886
|
+
typedByClassifier = true;
|
|
1887
|
+
if (emit) {
|
|
1888
|
+
receipts.push({
|
|
1889
|
+
...base,
|
|
1890
|
+
code: "node_type_assigned",
|
|
1891
|
+
detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
|
|
1892
|
+
});
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
} else if (normalized.okf_type) {
|
|
1896
|
+
if (emit) {
|
|
1897
|
+
receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
|
|
1898
|
+
}
|
|
1899
|
+
}
|
|
1900
|
+
if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
|
|
1901
|
+
const r = typingOutcomeReceipt(base, factId, outcome);
|
|
1902
|
+
if (r) receipts.push(r);
|
|
1903
|
+
}
|
|
1904
|
+
return { normalized, drops, receipts, typedByClassifier };
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
// src/repositories/rowMappers.ts
|
|
1908
|
+
function parseJsonArray(s, fallback) {
|
|
1909
|
+
if (Array.isArray(s)) return s;
|
|
1910
|
+
if (typeof s === "string" && s.length > 0) {
|
|
1911
|
+
try {
|
|
1912
|
+
const p = JSON.parse(s);
|
|
1913
|
+
if (Array.isArray(p)) return p;
|
|
1914
|
+
} catch {
|
|
1915
|
+
}
|
|
1916
|
+
}
|
|
1917
|
+
return fallback;
|
|
1918
|
+
}
|
|
1919
|
+
function parseJsonObject(s, fallback = null) {
|
|
1920
|
+
if (s && typeof s === "object" && !Array.isArray(s)) return s;
|
|
1921
|
+
if (typeof s === "string" && s.length > 0) {
|
|
1922
|
+
try {
|
|
1923
|
+
const p = JSON.parse(s);
|
|
1924
|
+
if (p && typeof p === "object" && !Array.isArray(p)) return p;
|
|
1925
|
+
} catch {
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
return fallback;
|
|
1929
|
+
}
|
|
1930
|
+
|
|
1009
1931
|
// src/db/schema.ts
|
|
1010
1932
|
async function setupDatabase(db, prefix) {
|
|
1011
1933
|
await db.execAsync(`
|
|
@@ -1044,7 +1966,9 @@ async function setupDatabase(db, prefix) {
|
|
|
1044
1966
|
valid_to INTEGER,
|
|
1045
1967
|
superseded_by TEXT,
|
|
1046
1968
|
superseded_at INTEGER,
|
|
1047
|
-
|
|
1969
|
+
prior_valid_to INTEGER,
|
|
1970
|
+
source_pointer TEXT,
|
|
1971
|
+
derived_events TEXT
|
|
1048
1972
|
);
|
|
1049
1973
|
|
|
1050
1974
|
CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
|
|
@@ -1828,8 +2752,34 @@ var MIGRATIONS = [
|
|
|
1828
2752
|
);`
|
|
1829
2753
|
);
|
|
1830
2754
|
}
|
|
2755
|
+
},
|
|
2756
|
+
{
|
|
2757
|
+
version: 18,
|
|
2758
|
+
description: "Partial index on entries(entity_id, deleted_at) for prune and tombstone probes; nullable prior_valid_to column recording the scheduled end a supersede overwrote; nullable derived_events column listing the events an in-place librarian merge drew on",
|
|
2759
|
+
run: async (db, prefix) => {
|
|
2760
|
+
await createEntriesDeletedIndex(db, prefix);
|
|
2761
|
+
await addPriorValidToColumn(db, prefix);
|
|
2762
|
+
await addDerivedEventsColumn(db, prefix);
|
|
2763
|
+
}
|
|
1831
2764
|
}
|
|
1832
2765
|
];
|
|
2766
|
+
async function addPriorValidToColumn(db, prefix) {
|
|
2767
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
2768
|
+
if (!cols.some((c) => c.name === "prior_valid_to")) {
|
|
2769
|
+
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN prior_valid_to INTEGER`);
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
async function createEntriesDeletedIndex(db, prefix) {
|
|
2773
|
+
await db.execAsync(
|
|
2774
|
+
`CREATE INDEX IF NOT EXISTS ${prefix}entries_deleted_idx ON ${prefix}entries(entity_id, deleted_at) WHERE deleted_at IS NOT NULL`
|
|
2775
|
+
);
|
|
2776
|
+
}
|
|
2777
|
+
async function addDerivedEventsColumn(db, prefix) {
|
|
2778
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
2779
|
+
if (!cols.some((c) => c.name === "derived_events")) {
|
|
2780
|
+
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN derived_events TEXT`);
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
1833
2783
|
async function createLegacySourceTypeIndex(db, prefix) {
|
|
1834
2784
|
await db.execAsync(
|
|
1835
2785
|
`CREATE INDEX IF NOT EXISTS ${prefix}entries_legacy_source_type_idx ON ${prefix}entries(source_type) WHERE source_type IN ('user_document', 'agent_inferred')`
|
|
@@ -2122,6 +3072,43 @@ function serializeSourcePointer(p) {
|
|
|
2122
3072
|
return p ? JSON.stringify(p) : null;
|
|
2123
3073
|
}
|
|
2124
3074
|
|
|
3075
|
+
// src/utils/derivedEvents.ts
|
|
3076
|
+
function validateDerivedEventsValue(v) {
|
|
3077
|
+
if (v === null) return null;
|
|
3078
|
+
if (!Array.isArray(v)) return void 0;
|
|
3079
|
+
for (const x of v) {
|
|
3080
|
+
if (typeof x !== "string" || x.length === 0) return void 0;
|
|
3081
|
+
}
|
|
3082
|
+
const out = dedupeEventIds(v);
|
|
3083
|
+
return out.length === 0 ? null : out;
|
|
3084
|
+
}
|
|
3085
|
+
function parseStoredDerivedEvents(raw) {
|
|
3086
|
+
if (typeof raw !== "string") return null;
|
|
3087
|
+
let parsed;
|
|
3088
|
+
try {
|
|
3089
|
+
parsed = JSON.parse(raw);
|
|
3090
|
+
} catch {
|
|
3091
|
+
return null;
|
|
3092
|
+
}
|
|
3093
|
+
if (!Array.isArray(parsed)) return null;
|
|
3094
|
+
const kept = dedupeEventIds(parsed.filter((x) => typeof x === "string"));
|
|
3095
|
+
return kept.length === 0 ? null : kept;
|
|
3096
|
+
}
|
|
3097
|
+
function serializeDerivedEvents(list) {
|
|
3098
|
+
if (!list || list.length === 0) return null;
|
|
3099
|
+
return JSON.stringify(list);
|
|
3100
|
+
}
|
|
3101
|
+
function dedupeEventIds(ids) {
|
|
3102
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3103
|
+
const out = [];
|
|
3104
|
+
for (const id of ids) {
|
|
3105
|
+
if (typeof id !== "string" || id.length === 0 || seen.has(id)) continue;
|
|
3106
|
+
seen.add(id);
|
|
3107
|
+
out.push(id);
|
|
3108
|
+
}
|
|
3109
|
+
return out;
|
|
3110
|
+
}
|
|
3111
|
+
|
|
2125
3112
|
// src/repositories/EntryRepository.ts
|
|
2126
3113
|
function mapRowToFact(row) {
|
|
2127
3114
|
const tags = (() => {
|
|
@@ -2137,6 +3124,7 @@ function mapRowToFact(row) {
|
|
|
2137
3124
|
const now = Date.now();
|
|
2138
3125
|
const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
|
|
2139
3126
|
const sourcePointer = parseStoredSourcePointer(row.source_pointer);
|
|
3127
|
+
const derivedEvents = parseStoredDerivedEvents(row.derived_events);
|
|
2140
3128
|
const mapped = {
|
|
2141
3129
|
id: row.id,
|
|
2142
3130
|
entity_id: row.entity_id,
|
|
@@ -2171,10 +3159,14 @@ function mapRowToFact(row) {
|
|
|
2171
3159
|
...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
|
|
2172
3160
|
...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
|
|
2173
3161
|
...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
|
|
3162
|
+
...row.prior_valid_to != null ? { prior_valid_to: Number(row.prior_valid_to) } : {},
|
|
2174
3163
|
// Source pointer (specs/source-pointers): key appears only when non-null,
|
|
2175
3164
|
// same temporal-fields pattern. Tolerant read: a malformed stored value
|
|
2176
3165
|
// reads as null without throwing (test 1).
|
|
2177
|
-
...sourcePointer ? { source_pointer: sourcePointer } : {}
|
|
3166
|
+
...sourcePointer ? { source_pointer: sourcePointer } : {},
|
|
3167
|
+
// derived_events (specs/inplace-update-provenance §5): present only when
|
|
3168
|
+
// non-empty; a malformed stored value reads as absent without throwing.
|
|
3169
|
+
...derivedEvents ? { derived_events: derivedEvents } : {}
|
|
2178
3170
|
};
|
|
2179
3171
|
return mapped;
|
|
2180
3172
|
}
|
|
@@ -2291,7 +3283,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2291
3283
|
const existingRow = await executor.getFirstAsync(
|
|
2292
3284
|
`SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
|
|
2293
3285
|
okf_sources, okf_verified, okf_usage_window,
|
|
2294
|
-
last_verified_at, last_verified_by, source_pointer
|
|
3286
|
+
last_verified_at, last_verified_by, source_pointer, derived_events
|
|
2295
3287
|
FROM ${this.prefix}entries WHERE id = ?`,
|
|
2296
3288
|
[fact.id]
|
|
2297
3289
|
);
|
|
@@ -2305,8 +3297,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2305
3297
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
2306
3298
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
2307
3299
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
2308
|
-
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
2309
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3300
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
|
|
3301
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2310
3302
|
ON CONFLICT(id) DO UPDATE SET
|
|
2311
3303
|
title = excluded.title,
|
|
2312
3304
|
body = excluded.body,
|
|
@@ -2324,7 +3316,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2324
3316
|
embedding_failed_at = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failed_at END,
|
|
2325
3317
|
embedding_failure_kind = CASE WHEN excluded.embedding_blob IS NOT NULL THEN NULL ELSE embedding_failure_kind END,
|
|
2326
3318
|
embedding_attempts = CASE WHEN excluded.embedding_blob IS NOT NULL THEN 0 ELSE embedding_attempts END,
|
|
2327
|
-
okf_type = excluded.okf_type
|
|
3319
|
+
okf_type = excluded.okf_type,
|
|
3320
|
+
derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END
|
|
2328
3321
|
WHERE ${this.prefix}entries.entity_id = excluded.entity_id`,
|
|
2329
3322
|
[
|
|
2330
3323
|
fact.id,
|
|
@@ -2355,7 +3348,12 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2355
3348
|
fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
|
|
2356
3349
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
2357
3350
|
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
2358
|
-
serializeSourcePointer(fact.source_pointer)
|
|
3351
|
+
serializeSourcePointer(fact.source_pointer),
|
|
3352
|
+
serializeDerivedEvents(fact.derived_events),
|
|
3353
|
+
// derived_events is writable on conflict (the librarian's in-place
|
|
3354
|
+
// UPDATE merges events into it), but only when the caller supplied the
|
|
3355
|
+
// key: an undefined key leaves a stored list untouched.
|
|
3356
|
+
fact.derived_events !== void 0 ? 1 : 0
|
|
2359
3357
|
]
|
|
2360
3358
|
);
|
|
2361
3359
|
if (result.changes === 0) {
|
|
@@ -2379,7 +3377,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2379
3377
|
okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
|
|
2380
3378
|
last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
|
|
2381
3379
|
last_verified_by: existingRow.last_verified_by ?? null,
|
|
2382
|
-
source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
|
|
3380
|
+
source_pointer: parseStoredSourcePointer(existingRow.source_pointer),
|
|
3381
|
+
...fact.derived_events === void 0 ? (() => {
|
|
3382
|
+
const stored = parseStoredDerivedEvents(existingRow.derived_events);
|
|
3383
|
+
return stored ? { derived_events: stored } : {};
|
|
3384
|
+
})() : {}
|
|
2383
3385
|
} : null;
|
|
2384
3386
|
await this.outbox.push({
|
|
2385
3387
|
entityId: fact.entity_id,
|
|
@@ -2444,7 +3446,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2444
3446
|
const rows = await executor.getAllAsync(sql, args);
|
|
2445
3447
|
return rows.map((row) => row.id);
|
|
2446
3448
|
}
|
|
2447
|
-
async upsertForImport(fact, tx, sourcePointerPresent = false) {
|
|
3449
|
+
async upsertForImport(fact, tx, sourcePointerPresent = false, derivedEventsPresent = false) {
|
|
2448
3450
|
const executor = this.getExecutor(tx);
|
|
2449
3451
|
const tagsJson = JSON.stringify(fact.tags);
|
|
2450
3452
|
const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
|
|
@@ -2454,8 +3456,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2454
3456
|
source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
|
|
2455
3457
|
deleted_at, embedding_blob, embedding, okf_type,
|
|
2456
3458
|
lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
|
|
2457
|
-
okf_sources, okf_verified, okf_usage_window, source_pointer
|
|
2458
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
3459
|
+
okf_sources, okf_verified, okf_usage_window, source_pointer, derived_events
|
|
3460
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2459
3461
|
ON CONFLICT(id) DO UPDATE SET
|
|
2460
3462
|
entity_id = excluded.entity_id,
|
|
2461
3463
|
title = excluded.title,
|
|
@@ -2484,7 +3486,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2484
3486
|
okf_sources = excluded.okf_sources,
|
|
2485
3487
|
okf_verified = excluded.okf_verified,
|
|
2486
3488
|
okf_usage_window = excluded.okf_usage_window,
|
|
2487
|
-
source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END
|
|
3489
|
+
source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END,
|
|
3490
|
+
derived_events = CASE WHEN ? THEN excluded.derived_events ELSE derived_events END`,
|
|
2488
3491
|
[
|
|
2489
3492
|
fact.id,
|
|
2490
3493
|
fact.entity_id,
|
|
@@ -2513,9 +3516,13 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2513
3516
|
fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
|
|
2514
3517
|
fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
|
|
2515
3518
|
serializeSourcePointer(fact.source_pointer),
|
|
3519
|
+
serializeDerivedEvents(fact.derived_events),
|
|
2516
3520
|
// The presence flag binds to the SET clause's CASE, AFTER the INSERT
|
|
2517
3521
|
// values above.
|
|
2518
|
-
sourcePointerPresent ? 1 : 0
|
|
3522
|
+
sourcePointerPresent ? 1 : 0,
|
|
3523
|
+
// derived_events follows the same presence-flag pattern: a pre-v18
|
|
3524
|
+
// dump (no key) never nulls a stored list.
|
|
3525
|
+
derivedEventsPresent ? 1 : 0
|
|
2519
3526
|
]
|
|
2520
3527
|
);
|
|
2521
3528
|
return result;
|
|
@@ -2582,15 +3589,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2582
3589
|
}
|
|
2583
3590
|
return result.changes;
|
|
2584
3591
|
}
|
|
3592
|
+
/** Bind values for `EVENT_MATCH_SQL` after an `entity_id = ?` term: the event id twice. */
|
|
3593
|
+
static eventMatchArgs(entityId, eventId) {
|
|
3594
|
+
return [entityId, eventId, eventId];
|
|
3595
|
+
}
|
|
2585
3596
|
/**
|
|
2586
|
-
* IDs of the entity's entries whose source_pointer names the event id.
|
|
3597
|
+
* IDs of the entity's entries whose source_pointer names the event id or whose derived_events list contains it.
|
|
2587
3598
|
* `includeDeleted = true` returns live + tombstoned rows (the forget
|
|
2588
3599
|
* enumeration superset for index sync and the ledger backstop).
|
|
2589
3600
|
*/
|
|
2590
3601
|
async findIdsByPointerEvent(entityId, eventId, tx, includeDeleted = false) {
|
|
2591
3602
|
const executor = this.getExecutor(tx);
|
|
2592
3603
|
let sql = `SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`;
|
|
2593
|
-
const args =
|
|
3604
|
+
const args = _EntryRepository.eventMatchArgs(entityId, eventId);
|
|
2594
3605
|
if (!includeDeleted) sql += ` AND deleted_at IS NULL`;
|
|
2595
3606
|
const rows = await executor.getAllAsync(sql, args);
|
|
2596
3607
|
return rows.map((r) => r.id);
|
|
@@ -2600,7 +3611,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2600
3611
|
const executor = this.getExecutor(tx);
|
|
2601
3612
|
const row = await executor.getFirstAsync(
|
|
2602
3613
|
`SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
|
|
2603
|
-
|
|
3614
|
+
_EntryRepository.eventMatchArgs(entityId, eventId)
|
|
2604
3615
|
);
|
|
2605
3616
|
return row?.n ?? 0;
|
|
2606
3617
|
}
|
|
@@ -2618,11 +3629,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2618
3629
|
const now = Date.now();
|
|
2619
3630
|
const idsToDelete = await executor.getAllAsync(
|
|
2620
3631
|
`SELECT id FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
|
|
2621
|
-
|
|
3632
|
+
_EntryRepository.eventMatchArgs(entityId, eventId)
|
|
2622
3633
|
);
|
|
2623
3634
|
const result = await executor.runAsync(
|
|
2624
3635
|
`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL AND ${_EntryRepository.POINTER_EVENT_MATCH_SQL}`,
|
|
2625
|
-
[now, now, entityId, eventId]
|
|
3636
|
+
[now, now, ..._EntryRepository.eventMatchArgs(entityId, eventId)]
|
|
2626
3637
|
);
|
|
2627
3638
|
for (const row of idsToDelete) {
|
|
2628
3639
|
await this.outbox.push({
|
|
@@ -2942,9 +3953,9 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2942
3953
|
}, tx);
|
|
2943
3954
|
}
|
|
2944
3955
|
}
|
|
2945
|
-
/** Spec §4: write any subset of the
|
|
3956
|
+
/** Spec §4: write any subset of the five temporal columns. Absent key = untouched; null = clear. */
|
|
2946
3957
|
async setTemporal(id, entityId, fields, tx, opts) {
|
|
2947
|
-
const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at"].filter((k) => k in fields);
|
|
3958
|
+
const keys = ["valid_from", "valid_to", "superseded_by", "superseded_at", "prior_valid_to"].filter((k) => k in fields);
|
|
2948
3959
|
if (keys.length === 0) return 0;
|
|
2949
3960
|
const executor = this.getExecutor(tx);
|
|
2950
3961
|
const result = await executor.runAsync(
|
|
@@ -2961,7 +3972,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2961
3972
|
async findTemporalRow(id, tx) {
|
|
2962
3973
|
const executor = this.getExecutor(tx);
|
|
2963
3974
|
const row = await executor.getFirstAsync(
|
|
2964
|
-
`SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by
|
|
3975
|
+
`SELECT id, entity_id, source_type, deleted_at, created_at, valid_from, valid_to, superseded_by, prior_valid_to
|
|
2965
3976
|
FROM ${this.prefix}entries WHERE id = ?`,
|
|
2966
3977
|
[id]
|
|
2967
3978
|
);
|
|
@@ -2974,7 +3985,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2974
3985
|
created_at: Number(row.created_at),
|
|
2975
3986
|
valid_from: row.valid_from != null ? Number(row.valid_from) : null,
|
|
2976
3987
|
valid_to: row.valid_to != null ? Number(row.valid_to) : null,
|
|
2977
|
-
superseded_by: row.superseded_by != null ? String(row.superseded_by) : null
|
|
3988
|
+
superseded_by: row.superseded_by != null ? String(row.superseded_by) : null,
|
|
3989
|
+
prior_valid_to: row.prior_valid_to != null ? Number(row.prior_valid_to) : null
|
|
2978
3990
|
};
|
|
2979
3991
|
}
|
|
2980
3992
|
/**
|
|
@@ -3679,17 +4691,30 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
3679
4691
|
_EntryRepository.MINI_SEARCH_COLUMNS = "id, entity_id, title, body, tags";
|
|
3680
4692
|
_EntryRepository.MINI_SEARCH_LIVE_WHERE = "WHERE deleted_at IS NULL";
|
|
3681
4693
|
/**
|
|
3682
|
-
* Shared JSON match predicate for
|
|
3683
|
-
* (specs/forget-by-event-id §D1
|
|
4694
|
+
* Shared JSON match predicate for an event id
|
|
4695
|
+
* (specs/forget-by-event-id §D1, widened by specs/inplace-update-provenance
|
|
4696
|
+
* §4): a row matches when its `source_pointer` names the event OR its
|
|
4697
|
+
* `derived_events` list contains it. Every JSON call sits under its own
|
|
3684
4698
|
* `json_valid` guard: unguarded JSON functions RAISE on malformed text, and
|
|
3685
4699
|
* three-valued logic forces evaluation of AND operands after a NULL-guarded
|
|
3686
4700
|
* term — a two-term form is only as safe as the planner's term-splitting.
|
|
4701
|
+
* The `json_each` term additionally requires `json_type = 'array'` (a JSON
|
|
4702
|
+
* object or scalar would otherwise iterate its members). The event id binds
|
|
4703
|
+
* TWICE (pointer term, then derived_events term); use `eventMatchArgs`.
|
|
3687
4704
|
* The tombstone guard (`deleted_at IS NULL`) is added per-method.
|
|
3688
4705
|
*/
|
|
3689
|
-
_EntryRepository.
|
|
4706
|
+
_EntryRepository.EVENT_MATCH_SQL = `((CASE WHEN json_valid(source_pointer)
|
|
3690
4707
|
THEN json_type(source_pointer, '$.event_id') = 'text'
|
|
3691
4708
|
AND json_extract(source_pointer, '$.event_id') = ?
|
|
3692
|
-
ELSE 0 END
|
|
4709
|
+
ELSE 0 END)
|
|
4710
|
+
OR
|
|
4711
|
+
(CASE WHEN json_valid(derived_events)
|
|
4712
|
+
THEN (CASE WHEN json_type(derived_events) = 'array'
|
|
4713
|
+
THEN EXISTS (SELECT 1 FROM json_each(derived_events) WHERE json_each.type = 'text' AND json_each.value = ?)
|
|
4714
|
+
ELSE 0 END)
|
|
4715
|
+
ELSE 0 END))`;
|
|
4716
|
+
/** Old name kept as an alias (tests and external references). */
|
|
4717
|
+
_EntryRepository.POINTER_EVENT_MATCH_SQL = _EntryRepository.EVENT_MATCH_SQL;
|
|
3693
4718
|
var EntryRepository = _EntryRepository;
|
|
3694
4719
|
|
|
3695
4720
|
// src/utils/ids.ts
|
|
@@ -4226,6 +5251,24 @@ var EventRepository = class extends BaseRepository {
|
|
|
4226
5251
|
);
|
|
4227
5252
|
return result.changes > 0;
|
|
4228
5253
|
}
|
|
5254
|
+
/**
|
|
5255
|
+
* The subset of `ids` that exist as events of `entityId` (specs/
|
|
5256
|
+
* inplace-update-provenance §3). Chunked so a large batch stays under the
|
|
5257
|
+
* bound-variable limit. Pass `tx` to read inside the caller's transaction.
|
|
5258
|
+
*/
|
|
5259
|
+
async findExistingIds(entityId, ids, tx) {
|
|
5260
|
+
const executor = this.getExecutor(tx);
|
|
5261
|
+
const found = /* @__PURE__ */ new Set();
|
|
5262
|
+
for (let i = 0; i < ids.length; i += 500) {
|
|
5263
|
+
const chunk = ids.slice(i, i + 500);
|
|
5264
|
+
const rows = await executor.getAllAsync(
|
|
5265
|
+
`SELECT id FROM ${this.prefix}events WHERE entity_id = ? AND id IN (${chunk.map(() => "?").join(",")})`,
|
|
5266
|
+
[entityId, ...chunk]
|
|
5267
|
+
);
|
|
5268
|
+
for (const r of rows) found.add(r.id);
|
|
5269
|
+
}
|
|
5270
|
+
return found;
|
|
5271
|
+
}
|
|
4229
5272
|
/**
|
|
4230
5273
|
* Return the most recent events for an entity, newest first.
|
|
4231
5274
|
* Defaults to a limit of 50.
|
|
@@ -4552,244 +5595,29 @@ var EdgeRepository = class extends BaseRepository {
|
|
|
4552
5595
|
opts.maxNodes
|
|
4553
5596
|
];
|
|
4554
5597
|
const rows = await executor.getAllAsync(sql, params);
|
|
4555
|
-
const nodeIds = rows.map((r) => r.node_id);
|
|
4556
|
-
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
4557
|
-
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
4558
|
-
const edgeRows = await executor.getAllAsync(
|
|
4559
|
-
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
4560
|
-
SELECT e.* FROM ${this.prefix}edges e
|
|
4561
|
-
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
4562
|
-
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
4563
|
-
WHERE e.entity_id = ?`,
|
|
4564
|
-
[...nodeIds, entityId]
|
|
4565
|
-
);
|
|
4566
|
-
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
4567
|
-
}
|
|
4568
|
-
};
|
|
4569
|
-
function mapRowToEdge(row) {
|
|
4570
|
-
return {
|
|
4571
|
-
id: String(row.id),
|
|
4572
|
-
entity_id: String(row.entity_id),
|
|
4573
|
-
source_id: String(row.source_id),
|
|
4574
|
-
target_id: String(row.target_id),
|
|
4575
|
-
edge_type: String(row.edge_type),
|
|
4576
|
-
created_at: Number(row.created_at)
|
|
4577
|
-
};
|
|
4578
|
-
}
|
|
4579
|
-
|
|
4580
|
-
// src/utils/ontology.ts
|
|
4581
|
-
function emptyManifest() {
|
|
4582
|
-
return { node_types: [], edge_types: [] };
|
|
4583
|
-
}
|
|
4584
|
-
function normalizeTitleKey(title) {
|
|
4585
|
-
return title.trim().toLowerCase().replace(/\s+/g, " ");
|
|
4586
|
-
}
|
|
4587
|
-
function normalizeSlug(raw) {
|
|
4588
|
-
return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
|
|
4589
|
-
}
|
|
4590
|
-
function resolveNodeTypeMatch(raw, manifest) {
|
|
4591
|
-
const slug = typeof raw === "string" ? raw.trim() : "";
|
|
4592
|
-
if (!slug) return null;
|
|
4593
|
-
const lowered = slug.toLowerCase();
|
|
4594
|
-
const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
|
|
4595
|
-
if (exact) return { slug: exact.type, via: "exact" };
|
|
4596
|
-
const normalized = normalizeSlug(slug);
|
|
4597
|
-
if (!normalized) return null;
|
|
4598
|
-
const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
|
|
4599
|
-
return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
|
|
4600
|
-
}
|
|
4601
|
-
function resolveNodeType(raw, manifest) {
|
|
4602
|
-
return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
|
|
4603
|
-
}
|
|
4604
|
-
var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
|
|
4605
|
-
function isReservedAbstainSlug(raw) {
|
|
4606
|
-
return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
|
|
4607
|
-
}
|
|
4608
|
-
function resolveEdgeDefinitions(rawEdgeType, manifest) {
|
|
4609
|
-
const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
|
|
4610
|
-
if (!slug) return [];
|
|
4611
|
-
const lowered = slug.toLowerCase();
|
|
4612
|
-
const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
|
|
4613
|
-
if (exact.length > 0) return exact;
|
|
4614
|
-
const normalized = normalizeSlug(slug);
|
|
4615
|
-
if (!normalized) return [];
|
|
4616
|
-
const names = new Set(
|
|
4617
|
-
manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
|
|
4618
|
-
);
|
|
4619
|
-
if (names.size !== 1) return [];
|
|
4620
|
-
return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
|
|
4621
|
-
}
|
|
4622
|
-
function edgeTripleKey(type, sourceType, targetType) {
|
|
4623
|
-
return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
|
|
4624
|
-
}
|
|
4625
|
-
function typeSatisfies(declaredType, concreteType, manifest) {
|
|
4626
|
-
const concrete = concreteType.trim().toLowerCase();
|
|
4627
|
-
const declared = declaredType.trim().toLowerCase();
|
|
4628
|
-
if (!concrete || !declared) return false;
|
|
4629
|
-
if (declared === concrete) return true;
|
|
4630
|
-
const def = (manifest.node_types ?? []).find(
|
|
4631
|
-
(n) => typeof n?.type === "string" && n.type.trim().toLowerCase() === concrete
|
|
4632
|
-
);
|
|
4633
|
-
const parent = typeof def?.parent_type === "string" ? def.parent_type.trim().toLowerCase() : "";
|
|
4634
|
-
return parent !== "" && parent === declared;
|
|
4635
|
-
}
|
|
4636
|
-
function edgeTripleAllowed(manifest, edgeType, sourceType, targetType) {
|
|
4637
|
-
const wanted = edgeType.trim().toLowerCase();
|
|
4638
|
-
return (manifest.edge_types ?? []).some((d) => typeof d?.type === "string" && d.type.trim().toLowerCase() === wanted && typeof d.source_type === "string" && typeSatisfies(d.source_type, sourceType, manifest) && typeof d.target_type === "string" && typeSatisfies(d.target_type, targetType, manifest));
|
|
4639
|
-
}
|
|
4640
|
-
function validateManifest(manifest) {
|
|
4641
|
-
const nodeSlugs = /* @__PURE__ */ new Set();
|
|
4642
|
-
for (const node of manifest.node_types ?? []) {
|
|
4643
|
-
const type = node.type?.trim();
|
|
4644
|
-
if (!type) throw new Error("Ontology node type slug must be non-empty");
|
|
4645
|
-
const key = type.toLowerCase();
|
|
4646
|
-
if (nodeSlugs.has(key)) throw new Error(`Duplicate node type: ${type}`);
|
|
4647
|
-
nodeSlugs.add(key);
|
|
4648
|
-
}
|
|
4649
|
-
const parentOf = /* @__PURE__ */ new Map();
|
|
4650
|
-
for (const node of manifest.node_types ?? []) {
|
|
4651
|
-
const parent = typeof node.parent_type === "string" ? node.parent_type.trim().toLowerCase() : void 0;
|
|
4652
|
-
parentOf.set(node.type.trim().toLowerCase(), parent);
|
|
4653
|
-
}
|
|
4654
|
-
for (const node of manifest.node_types ?? []) {
|
|
4655
|
-
if (node.parent_type === void 0) continue;
|
|
4656
|
-
if (typeof node.parent_type !== "string" || !node.parent_type.trim()) {
|
|
4657
|
-
throw new Error(`Ontology parent_type must be a non-empty string when present: ${node.type}`);
|
|
4658
|
-
}
|
|
4659
|
-
const parentSlug = node.parent_type.trim().toLowerCase();
|
|
4660
|
-
if (parentSlug === node.type.trim().toLowerCase()) {
|
|
4661
|
-
throw new Error(`Self-parent: ${node.type}`);
|
|
4662
|
-
}
|
|
4663
|
-
if (!nodeSlugs.has(parentSlug)) {
|
|
4664
|
-
throw new Error(`Parent type not found: ${node.parent_type}`);
|
|
4665
|
-
}
|
|
4666
|
-
const grandparent = parentOf.get(parentSlug);
|
|
4667
|
-
if (grandparent) {
|
|
4668
|
-
throw new Error(`Parent chain too deep: ${node.type} \u2192 ${node.parent_type} \u2192 ${grandparent}`);
|
|
4669
|
-
}
|
|
4670
|
-
}
|
|
4671
|
-
const edgeKeys = /* @__PURE__ */ new Set();
|
|
4672
|
-
const edgeNames = /* @__PURE__ */ new Map();
|
|
4673
|
-
for (const edge of manifest.edge_types ?? []) {
|
|
4674
|
-
const edgeType = edge.type?.trim();
|
|
4675
|
-
const sourceType = edge.source_type?.trim();
|
|
4676
|
-
const targetType = edge.target_type?.trim();
|
|
4677
|
-
if (!edgeType) throw new Error("Ontology edge type slug must be non-empty");
|
|
4678
|
-
if (!sourceType || !targetType || !nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
|
|
4679
|
-
throw new Error(`Edge type ${edgeType} references unknown node type`);
|
|
4680
|
-
}
|
|
4681
|
-
const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
|
|
4682
|
-
if (edgeKeys.has(edgeKey)) {
|
|
4683
|
-
throw new Error(`Duplicate edge definition: ${edgeType} (${sourceType} \u2192 ${targetType})`);
|
|
4684
|
-
}
|
|
4685
|
-
edgeKeys.add(edgeKey);
|
|
4686
|
-
const canonical = edgeNames.get(edgeType.toLowerCase());
|
|
4687
|
-
if (canonical === void 0) {
|
|
4688
|
-
edgeNames.set(edgeType.toLowerCase(), edgeType);
|
|
4689
|
-
} else if (canonical !== edgeType) {
|
|
4690
|
-
throw new Error(`Inconsistent casing for edge type: ${edgeType} conflicts with ${canonical}`);
|
|
4691
|
-
}
|
|
4692
|
-
}
|
|
4693
|
-
}
|
|
4694
|
-
function buildDeclaresParentIndex(nodes) {
|
|
4695
|
-
const declaresParent = /* @__PURE__ */ new Map();
|
|
4696
|
-
for (const n of nodes) {
|
|
4697
|
-
const slug = typeof n?.type === "string" ? n.type.trim().toLowerCase() : "";
|
|
4698
|
-
if (!slug || declaresParent.has(slug)) continue;
|
|
4699
|
-
declaresParent.set(slug, n?.parent_type !== void 0);
|
|
4700
|
-
}
|
|
4701
|
-
return declaresParent;
|
|
4702
|
-
}
|
|
4703
|
-
function mergeOntologyUpdates(current, updates) {
|
|
4704
|
-
const node_types = [...current.node_types];
|
|
4705
|
-
const edge_types = [...current.edge_types];
|
|
4706
|
-
const rejected = [];
|
|
4707
|
-
const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
|
|
4708
|
-
const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
|
|
4709
|
-
const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
|
|
4710
|
-
const declaresParent = buildDeclaresParentIndex([
|
|
4711
|
-
...current.node_types,
|
|
4712
|
-
...updates.node_types ?? []
|
|
4713
|
-
]);
|
|
4714
|
-
for (const node of updates.node_types ?? []) {
|
|
4715
|
-
const type = node?.type?.trim();
|
|
4716
|
-
if (!type) {
|
|
4717
|
-
rejected.push("invalid_shape");
|
|
4718
|
-
continue;
|
|
4719
|
-
}
|
|
4720
|
-
const key = type.toLowerCase();
|
|
4721
|
-
if (nodeSlugs.has(key)) {
|
|
4722
|
-
rejected.push("duplicate_node_type");
|
|
4723
|
-
continue;
|
|
4724
|
-
}
|
|
4725
|
-
const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
|
|
4726
|
-
const parentSlug = rawParent.toLowerCase();
|
|
4727
|
-
const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
|
|
4728
|
-
node_types.push({
|
|
4729
|
-
type,
|
|
4730
|
-
description: String(node.description ?? ""),
|
|
4731
|
-
...keepParent ? { parent_type: rawParent } : {}
|
|
4732
|
-
});
|
|
4733
|
-
nodeSlugs.add(key);
|
|
4734
|
-
}
|
|
4735
|
-
for (const edge of updates.edge_types ?? []) {
|
|
4736
|
-
const rawEdgeType = edge?.type?.trim();
|
|
4737
|
-
const sourceType = edge?.source_type?.trim();
|
|
4738
|
-
const targetType = edge?.target_type?.trim();
|
|
4739
|
-
if (!rawEdgeType || !sourceType || !targetType) {
|
|
4740
|
-
rejected.push("invalid_shape");
|
|
4741
|
-
continue;
|
|
4742
|
-
}
|
|
4743
|
-
const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
|
|
4744
|
-
const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
|
|
4745
|
-
if (edgeKeys.has(edgeKey)) {
|
|
4746
|
-
rejected.push("duplicate_edge");
|
|
4747
|
-
continue;
|
|
4748
|
-
}
|
|
4749
|
-
if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
|
|
4750
|
-
rejected.push("unknown_endpoint");
|
|
4751
|
-
continue;
|
|
4752
|
-
}
|
|
4753
|
-
edgeNames.set(edgeType.toLowerCase(), edgeType);
|
|
4754
|
-
edge_types.push({
|
|
4755
|
-
type: edgeType,
|
|
4756
|
-
source_type: sourceType,
|
|
4757
|
-
target_type: targetType,
|
|
4758
|
-
description: String(edge.description ?? "")
|
|
4759
|
-
});
|
|
4760
|
-
edgeKeys.add(edgeKey);
|
|
5598
|
+
const nodeIds = rows.map((r) => r.node_id);
|
|
5599
|
+
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
5600
|
+
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
5601
|
+
const edgeRows = await executor.getAllAsync(
|
|
5602
|
+
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
5603
|
+
SELECT e.* FROM ${this.prefix}edges e
|
|
5604
|
+
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
5605
|
+
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
5606
|
+
WHERE e.entity_id = ?`,
|
|
5607
|
+
[...nodeIds, entityId]
|
|
5608
|
+
);
|
|
5609
|
+
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
4761
5610
|
}
|
|
4762
|
-
|
|
4763
|
-
|
|
4764
|
-
|
|
4765
|
-
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
4769
|
-
|
|
5611
|
+
};
|
|
5612
|
+
function mapRowToEdge(row) {
|
|
5613
|
+
return {
|
|
5614
|
+
id: String(row.id),
|
|
5615
|
+
entity_id: String(row.entity_id),
|
|
5616
|
+
source_id: String(row.source_id),
|
|
5617
|
+
target_id: String(row.target_id),
|
|
5618
|
+
edge_type: String(row.edge_type),
|
|
5619
|
+
created_at: Number(row.created_at)
|
|
4770
5620
|
};
|
|
4771
|
-
if (!Array.isArray(edges)) {
|
|
4772
|
-
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", "");
|
|
4773
|
-
drop("invalid_shape", null);
|
|
4774
|
-
return [];
|
|
4775
|
-
}
|
|
4776
|
-
const valid = [];
|
|
4777
|
-
for (const edge of edges) {
|
|
4778
|
-
if (typeof edge?.edge_type !== "string" || typeof edge?.target_title !== "string") {
|
|
4779
|
-
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", String(edge?.edge_type ?? ""));
|
|
4780
|
-
drop("invalid_shape", typeof edge?.edge_type === "string" ? edge.edge_type : null);
|
|
4781
|
-
continue;
|
|
4782
|
-
}
|
|
4783
|
-
const defs = resolveEdgeDefinitions(edge.edge_type, manifest);
|
|
4784
|
-
const match = defs.find((d) => typeSatisfies(d.source_type, sourceType, manifest));
|
|
4785
|
-
if (!match) {
|
|
4786
|
-
if (strict) throw new WikiStrictOntologyViolation(entityId, "edge", edge.edge_type);
|
|
4787
|
-
drop("type_not_in_manifest", edge.edge_type);
|
|
4788
|
-
continue;
|
|
4789
|
-
}
|
|
4790
|
-
valid.push({ edge_type: match.type, target_title: edge.target_title });
|
|
4791
|
-
}
|
|
4792
|
-
return valid;
|
|
4793
5621
|
}
|
|
4794
5622
|
|
|
4795
5623
|
// src/repositories/MetadataRepository.ts
|
|
@@ -7739,16 +8567,36 @@ ${guidanceSection(guidance)}`;
|
|
|
7739
8567
|
} while (out !== prev);
|
|
7740
8568
|
return out;
|
|
7741
8569
|
}
|
|
7742
|
-
|
|
8570
|
+
/** Write-site variant (ingest, librarian, ops extract). Body identical to the backfill variant by design (specs/type-on-write §5). */
|
|
8571
|
+
buildWriteSystemPrompt(template, variables, ontologyContext) {
|
|
8572
|
+
const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
|
|
8573
|
+
const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
|
|
8574
|
+
const shouldHydrate = Object.keys(variables).some(
|
|
8575
|
+
(key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
|
|
8576
|
+
) || ontologyContext != null && hasOntologyPlaceholders;
|
|
8577
|
+
const hydrated = shouldHydrate ? this.hydrate(effective, {
|
|
8578
|
+
...variables,
|
|
8579
|
+
...ontologyContext ? { ontologyManifest: ontologyContext.ontologyManifest, ontologyModeInstructions: ontologyContext.ontologyModeInstructions } : {}
|
|
8580
|
+
}) : effective;
|
|
8581
|
+
return hasOntologyPlaceholders ? hydrated : this.appendWriteOntology(hydrated, ontologyContext);
|
|
8582
|
+
}
|
|
8583
|
+
appendWriteOntology(systemPrompt, ctx) {
|
|
8584
|
+
if (!ctx) return systemPrompt;
|
|
8585
|
+
return `${systemPrompt}
|
|
8586
|
+
|
|
8587
|
+
${ctx.ontologyModeInstructions}`;
|
|
8588
|
+
}
|
|
8589
|
+
/** Backfill-site variant. Body identical to the write variant by design (specs/type-on-write §5). */
|
|
8590
|
+
buildBackfillSystemPrompt(template, variables, ontologyContext) {
|
|
7743
8591
|
const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
|
|
7744
8592
|
const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
|
|
7745
8593
|
const shouldHydrate = Object.keys(variables).some(
|
|
7746
8594
|
(key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
|
|
7747
8595
|
) || ontologyContext != null && hasOntologyPlaceholders;
|
|
7748
8596
|
const hydrated = shouldHydrate ? this.hydrate(effective, { ...variables, ...ontologyContext ?? {} }) : effective;
|
|
7749
|
-
return hasOntologyPlaceholders ? hydrated : this.
|
|
8597
|
+
return hasOntologyPlaceholders ? hydrated : this.appendBackfillOntology(hydrated, ontologyContext);
|
|
7750
8598
|
}
|
|
7751
|
-
|
|
8599
|
+
appendBackfillOntology(systemPrompt, ctx) {
|
|
7752
8600
|
if (!ctx) return systemPrompt;
|
|
7753
8601
|
return `${systemPrompt}
|
|
7754
8602
|
|
|
@@ -7759,13 +8607,13 @@ ${ctx.ontologyModeInstructions}`;
|
|
|
7759
8607
|
const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
|
|
7760
8608
|
if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
|
|
7761
8609
|
return {
|
|
7762
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
8610
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
|
|
7763
8611
|
userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
|
|
7764
8612
|
${documentChunk}`
|
|
7765
8613
|
};
|
|
7766
8614
|
}
|
|
7767
8615
|
return {
|
|
7768
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
8616
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "ingest"),
|
|
7769
8617
|
userPrompt: `Document Chunk:
|
|
7770
8618
|
${documentChunk}`
|
|
7771
8619
|
};
|
|
@@ -7778,7 +8626,7 @@ ${documentChunk}`
|
|
|
7778
8626
|
const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
|
|
7779
8627
|
if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
|
|
7780
8628
|
return {
|
|
7781
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
8629
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
|
|
7782
8630
|
userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
|
|
7783
8631
|
${JSON.stringify(events, null, 2)}
|
|
7784
8632
|
|
|
@@ -7788,7 +8636,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
|
|
|
7788
8636
|
};
|
|
7789
8637
|
}
|
|
7790
8638
|
return {
|
|
7791
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
8639
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "librarian"),
|
|
7792
8640
|
userPrompt: `Events:
|
|
7793
8641
|
${JSON.stringify(events, null, 2)}
|
|
7794
8642
|
|
|
@@ -7879,7 +8727,7 @@ The following document anchors are provided for contradiction detection only. Do
|
|
|
7879
8727
|
const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
|
|
7880
8728
|
if (hasFacts || this.hasOntologyPlaceholders(template)) {
|
|
7881
8729
|
return {
|
|
7882
|
-
systemPrompt: this.
|
|
8730
|
+
systemPrompt: this.buildBackfillSystemPrompt(template, { facts }, ontologyContext),
|
|
7883
8731
|
userPrompt: hasFacts ? "Please classify the facts." : `Facts:
|
|
7884
8732
|
${JSON.stringify(facts, null, 2)}`
|
|
7885
8733
|
};
|
|
@@ -7887,7 +8735,7 @@ ${JSON.stringify(facts, null, 2)}`
|
|
|
7887
8735
|
const factsBlock = `Facts:
|
|
7888
8736
|
${JSON.stringify(facts, null, 2)}`;
|
|
7889
8737
|
return {
|
|
7890
|
-
systemPrompt: this.
|
|
8738
|
+
systemPrompt: this.appendBackfillOntology(template, ontologyContext),
|
|
7891
8739
|
userPrompt: candidateSections !== void 0 ? `${factsBlock}
|
|
7892
8740
|
|
|
7893
8741
|
${candidateSections}` : factsBlock
|
|
@@ -7898,7 +8746,7 @@ ${candidateSections}` : factsBlock
|
|
|
7898
8746
|
const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
|
|
7899
8747
|
const grounding = this.groundingFor("librarian");
|
|
7900
8748
|
return {
|
|
7901
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
8749
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
|
|
7902
8750
|
userPrompt: `Events:
|
|
7903
8751
|
${lines.join("\n")}`,
|
|
7904
8752
|
// Corpus entries are one-per-batch-event in batch order (summaries are
|
|
@@ -7919,13 +8767,14 @@ ${JSON.stringify({ items })}` };
|
|
|
7919
8767
|
* placeholders and leaves data placeholders verbatim; heal never receives
|
|
7920
8768
|
* ontology context, matching `buildHealPrompt`.
|
|
7921
8769
|
*/
|
|
7922
|
-
buildInstructionTemplates(
|
|
8770
|
+
buildInstructionTemplates(writeContext, librarianStrategy, guidance, backfillContext, ingestContext) {
|
|
7923
8771
|
const o = this.globalOverrides;
|
|
8772
|
+
const backfill = backfillContext !== void 0 ? backfillContext : writeContext ? { ontologyManifest: writeContext.ontologyManifest, ontologyModeInstructions: writeContext.ontologyModeInstructions } : null;
|
|
7924
8773
|
return {
|
|
7925
|
-
ingest: this.appendGrounding(this.appendGuidance(this.
|
|
7926
|
-
librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.
|
|
8774
|
+
ingest: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ingestContext !== void 0 ? ingestContext : writeContext), guidance), "ingest"),
|
|
8775
|
+
librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, writeContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, writeContext), guidance), "librarian"),
|
|
7927
8776
|
heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
|
|
7928
|
-
ontologyBackfill: this.
|
|
8777
|
+
ontologyBackfill: this.buildBackfillSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, backfill)
|
|
7929
8778
|
};
|
|
7930
8779
|
}
|
|
7931
8780
|
};
|
|
@@ -7946,202 +8795,31 @@ function applyBodyTruncation(candidates, attemptLevel, bodyTruncationChars) {
|
|
|
7946
8795
|
shapedCandidates.push(c);
|
|
7947
8796
|
continue;
|
|
7948
8797
|
}
|
|
7949
|
-
if (typeof fact.id !== "string") {
|
|
7950
|
-
shapedCandidates.push(c);
|
|
7951
|
-
continue;
|
|
7952
|
-
}
|
|
7953
|
-
const originalBodyChars = body.length;
|
|
7954
|
-
const prefix = safeSlice(body, 0, bodyTruncationChars);
|
|
7955
|
-
const truncatedBodyChars = prefix.length;
|
|
7956
|
-
const truncated = `${prefix}\u2026[truncated at ${truncatedBodyChars} chars, original was ${originalBodyChars}]`;
|
|
7957
|
-
shapedCandidates.push({ ...fact, body: truncated });
|
|
7958
|
-
degraded.push({ id: fact.id, originalBodyChars, truncatedBodyChars });
|
|
7959
|
-
}
|
|
7960
|
-
return { shapedCandidates, degraded };
|
|
7961
|
-
}
|
|
7962
|
-
function summaryOf(event) {
|
|
7963
|
-
return event?.summary;
|
|
7964
|
-
}
|
|
7965
|
-
function toGroundingAnchor(anchor) {
|
|
7966
|
-
if (typeof anchor !== "object" || anchor === null) return anchor;
|
|
7967
|
-
const a = anchor;
|
|
7968
|
-
return {
|
|
7969
|
-
id: a.id,
|
|
7970
|
-
title: a.title,
|
|
7971
|
-
source_ref: a.source_ref,
|
|
7972
|
-
body: typeof a.body === "string" ? safeSlice(a.body, 0, HEAL_ANCHOR_BODY_CHARS) : ""
|
|
7973
|
-
};
|
|
7974
|
-
}
|
|
7975
|
-
|
|
7976
|
-
// src/utils/chunkingDefaults.ts
|
|
7977
|
-
var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
|
|
7978
|
-
var DEFAULT_CHUNK_OVERLAP = 400;
|
|
7979
|
-
|
|
7980
|
-
// src/utils/contextCaps.ts
|
|
7981
|
-
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
7982
|
-
var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
7983
|
-
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
7984
|
-
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
7985
|
-
|
|
7986
|
-
// src/config/context.ts
|
|
7987
|
-
var DEFAULT_CHARS_PER_TOKEN = 4;
|
|
7988
|
-
var DEFAULT_SAFETY_FRACTION = 0.9;
|
|
7989
|
-
var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
|
|
7990
|
-
var OP_FLOOR = {
|
|
7991
|
-
resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
7992
|
-
heal: HEAL_MAX_PROMPT_CHARS,
|
|
7993
|
-
extract: OPS_MAX_EXTRACT_CHARS,
|
|
7994
|
-
backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
|
|
7995
|
-
};
|
|
7996
|
-
function bad(key, value, why) {
|
|
7997
|
-
return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
|
|
7998
|
-
}
|
|
7999
|
-
function resolveContextBudget(config) {
|
|
8000
|
-
const context = config?.context;
|
|
8001
|
-
if (!context || context.budget === void 0) {
|
|
8002
|
-
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
8003
|
-
}
|
|
8004
|
-
if (context.budget !== "legacy" && context.budget !== "declared") {
|
|
8005
|
-
throw bad("budget", context.budget, "'legacy' or 'declared'");
|
|
8006
|
-
}
|
|
8007
|
-
if (context.budget === "legacy") {
|
|
8008
|
-
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
8009
|
-
}
|
|
8010
|
-
const window = context.contextWindowTokens;
|
|
8011
|
-
if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
|
|
8012
|
-
throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
|
|
8013
|
-
}
|
|
8014
|
-
const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
8015
|
-
if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
|
|
8016
|
-
throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
|
|
8017
|
-
}
|
|
8018
|
-
const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
|
|
8019
|
-
if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
|
|
8020
|
-
throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
|
|
8021
|
-
}
|
|
8022
|
-
const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
|
|
8023
|
-
if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
|
|
8024
|
-
throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
|
|
8025
|
-
}
|
|
8026
|
-
return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
|
|
8027
|
-
}
|
|
8028
|
-
function declaredPromptCap(budget, op) {
|
|
8029
|
-
const derived = Math.floor(
|
|
8030
|
-
(budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
|
|
8031
|
-
);
|
|
8032
|
-
return Math.max(OP_FLOOR[op], derived);
|
|
8033
|
-
}
|
|
8034
|
-
function resolveMaxPromptChars(budget, op) {
|
|
8035
|
-
if (budget.mode !== "declared") {
|
|
8036
|
-
return OP_FLOOR[op];
|
|
8037
|
-
}
|
|
8038
|
-
if (op === "extract") {
|
|
8039
|
-
const resolveDerived = declaredPromptCap(budget, "resolve");
|
|
8040
|
-
const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
|
|
8041
|
-
return Math.max(OP_FLOOR.extract, extractDerived);
|
|
8042
|
-
}
|
|
8043
|
-
return declaredPromptCap(budget, op);
|
|
8044
|
-
}
|
|
8045
|
-
function resolveDefaultChunkLength(budget) {
|
|
8046
|
-
return DEFAULT_MAX_CHUNK_LENGTH;
|
|
8047
|
-
}
|
|
8048
|
-
|
|
8049
|
-
// src/utils/usage.ts
|
|
8050
|
-
function estimateTokens(text) {
|
|
8051
|
-
return Math.ceil(text.length / 4);
|
|
8052
|
-
}
|
|
8053
|
-
var UsageMeter = class {
|
|
8054
|
-
constructor(budget) {
|
|
8055
|
-
this.used = 0;
|
|
8056
|
-
this.estimated = false;
|
|
8057
|
-
if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
|
|
8058
|
-
throw new TypeError("tokenBudget must be a finite number >= 0");
|
|
8059
|
-
}
|
|
8060
|
-
this.budget = budget;
|
|
8061
|
-
}
|
|
8062
|
-
get remaining() {
|
|
8063
|
-
return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
|
|
8064
|
-
}
|
|
8065
|
-
fits(estimate) {
|
|
8066
|
-
return estimate <= this.remaining;
|
|
8067
|
-
}
|
|
8068
|
-
record(r) {
|
|
8069
|
-
this.used += r.inputTokens + r.outputTokens;
|
|
8070
|
-
if (r.estimated) this.estimated = true;
|
|
8071
|
-
}
|
|
8072
|
-
};
|
|
8073
|
-
var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
|
|
8074
|
-
constructor(requiredEstimate, remaining) {
|
|
8075
|
-
super(`LLM call needs ~${requiredEstimate} input tokens; ${remaining} remain in the budget.`);
|
|
8076
|
-
this.name = "WikiBudgetExhausted";
|
|
8077
|
-
this.requiredEstimate = requiredEstimate;
|
|
8078
|
-
this.remaining = remaining;
|
|
8079
|
-
Object.setPrototypeOf(this, _WikiBudgetExhausted.prototype);
|
|
8080
|
-
}
|
|
8081
|
-
};
|
|
8082
|
-
|
|
8083
|
-
// src/utils/llmCall.ts
|
|
8084
|
-
function validUsage(u) {
|
|
8085
|
-
if (!u || typeof u !== "object") return false;
|
|
8086
|
-
const { inputTokens, outputTokens } = u;
|
|
8087
|
-
return [inputTokens, outputTokens].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0);
|
|
8088
|
-
}
|
|
8089
|
-
async function callLlm(options, ctx, prompts) {
|
|
8090
|
-
const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
|
|
8091
|
-
if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
|
|
8092
|
-
throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
|
|
8093
|
-
}
|
|
8094
|
-
const provider = options.llmProvider;
|
|
8095
|
-
const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
|
|
8096
|
-
let text;
|
|
8097
|
-
let reported;
|
|
8098
|
-
if (typeof provider.generateTextWithUsage === "function") {
|
|
8099
|
-
const result = await provider.generateTextWithUsage(params);
|
|
8100
|
-
if (!result || typeof result.text !== "string") {
|
|
8101
|
-
throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
|
|
8102
|
-
}
|
|
8103
|
-
text = result.text;
|
|
8104
|
-
reported = validUsage(result.usage) ? result.usage : void 0;
|
|
8105
|
-
} else {
|
|
8106
|
-
text = await provider.generateText(params);
|
|
8107
|
-
}
|
|
8108
|
-
const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
|
|
8109
|
-
ctx.meter?.record(record);
|
|
8110
|
-
if (options.config?.reportLlmUsage === true) {
|
|
8111
|
-
emitDiagnostic(options, {
|
|
8112
|
-
code: "llm_usage",
|
|
8113
|
-
operation: ctx.operation,
|
|
8114
|
-
trigger: ctx.trigger,
|
|
8115
|
-
entityId: ctx.entityId,
|
|
8116
|
-
detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
|
|
8117
|
-
});
|
|
8118
|
-
}
|
|
8119
|
-
return text;
|
|
8120
|
-
}
|
|
8121
|
-
async function callClassify(options, ctx, request) {
|
|
8122
|
-
const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
|
|
8123
|
-
if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
|
|
8124
|
-
throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
|
|
8125
|
-
}
|
|
8126
|
-
const provider = options.llmProvider;
|
|
8127
|
-
if (typeof provider.classify !== "function") {
|
|
8128
|
-
throw new TypeError("callClassify requires a provider with classify()");
|
|
8129
|
-
}
|
|
8130
|
-
const response = await provider.classify(request);
|
|
8131
|
-
const reported = validUsage(response?.usage) ? response.usage : void 0;
|
|
8132
|
-
const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
|
|
8133
|
-
const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
|
|
8134
|
-
ctx.meter?.record(record);
|
|
8135
|
-
if (options.config?.reportLlmUsage === true) {
|
|
8136
|
-
emitDiagnostic(options, {
|
|
8137
|
-
code: "llm_usage",
|
|
8138
|
-
operation: ctx.operation,
|
|
8139
|
-
trigger: ctx.trigger,
|
|
8140
|
-
entityId: ctx.entityId,
|
|
8141
|
-
detail: { inputTokens: record.inputTokens, outputTokens: record.outputTokens, estimated: record.estimated }
|
|
8142
|
-
});
|
|
8798
|
+
if (typeof fact.id !== "string") {
|
|
8799
|
+
shapedCandidates.push(c);
|
|
8800
|
+
continue;
|
|
8801
|
+
}
|
|
8802
|
+
const originalBodyChars = body.length;
|
|
8803
|
+
const prefix = safeSlice(body, 0, bodyTruncationChars);
|
|
8804
|
+
const truncatedBodyChars = prefix.length;
|
|
8805
|
+
const truncated = `${prefix}\u2026[truncated at ${truncatedBodyChars} chars, original was ${originalBodyChars}]`;
|
|
8806
|
+
shapedCandidates.push({ ...fact, body: truncated });
|
|
8807
|
+
degraded.push({ id: fact.id, originalBodyChars, truncatedBodyChars });
|
|
8143
8808
|
}
|
|
8144
|
-
return
|
|
8809
|
+
return { shapedCandidates, degraded };
|
|
8810
|
+
}
|
|
8811
|
+
function summaryOf(event) {
|
|
8812
|
+
return event?.summary;
|
|
8813
|
+
}
|
|
8814
|
+
function toGroundingAnchor(anchor) {
|
|
8815
|
+
if (typeof anchor !== "object" || anchor === null) return anchor;
|
|
8816
|
+
const a = anchor;
|
|
8817
|
+
return {
|
|
8818
|
+
id: a.id,
|
|
8819
|
+
title: a.title,
|
|
8820
|
+
source_ref: a.source_ref,
|
|
8821
|
+
body: typeof a.body === "string" ? safeSlice(a.body, 0, HEAL_ANCHOR_BODY_CHARS) : ""
|
|
8822
|
+
};
|
|
8145
8823
|
}
|
|
8146
8824
|
|
|
8147
8825
|
// src/services/IngestionService.ts
|
|
@@ -8211,7 +8889,7 @@ var IngestionService = class {
|
|
|
8211
8889
|
}
|
|
8212
8890
|
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
8213
8891
|
if (chunks2.length === 0) return zeroChunkResult();
|
|
8214
|
-
const ontologyContext = await this.ontologyService?.
|
|
8892
|
+
const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
|
|
8215
8893
|
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
|
|
8216
8894
|
if (diagnostic) {
|
|
8217
8895
|
emitDiagnostic(this.options, {
|
|
@@ -8888,51 +9566,6 @@ var IngestionService = class {
|
|
|
8888
9566
|
}
|
|
8889
9567
|
};
|
|
8890
9568
|
|
|
8891
|
-
// src/utils/classifier.ts
|
|
8892
|
-
var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
8893
|
-
function validateClassifierAnswer(response, key, question) {
|
|
8894
|
-
try {
|
|
8895
|
-
if (response === null || typeof response !== "object") return { ok: false, reason: "malformed" };
|
|
8896
|
-
const answers = response.answers;
|
|
8897
|
-
if (answers === null || typeof answers !== "object") return { ok: false, reason: "missing_answer" };
|
|
8898
|
-
if (!Object.prototype.hasOwnProperty.call(answers, key)) return { ok: false, reason: "missing_answer" };
|
|
8899
|
-
const raw = answers[key];
|
|
8900
|
-
if (raw === null || typeof raw !== "object") return { ok: false, reason: "missing_answer" };
|
|
8901
|
-
const a = raw;
|
|
8902
|
-
if (a.kind !== question.kind) return { ok: false, reason: "kind_mismatch" };
|
|
8903
|
-
if (question.kind === "choice") {
|
|
8904
|
-
if (typeof a.choice !== "string" || !question.options.includes(a.choice)) return { ok: false, reason: "choice_not_offered" };
|
|
8905
|
-
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
8906
|
-
const probs = a.probabilities;
|
|
8907
|
-
if (probs === null || typeof probs !== "object" || Array.isArray(probs)) return { ok: false, reason: "invalid_probability" };
|
|
8908
|
-
const probabilities = {};
|
|
8909
|
-
for (const [k, v] of Object.entries(probs)) {
|
|
8910
|
-
if (!isUnit(v)) return { ok: false, reason: "invalid_probability" };
|
|
8911
|
-
probabilities[k] = v;
|
|
8912
|
-
}
|
|
8913
|
-
return { ok: true, answer: { kind: "choice", choice: a.choice, confidence: a.confidence, probabilities } };
|
|
8914
|
-
}
|
|
8915
|
-
if (question.kind === "binary") {
|
|
8916
|
-
if (!isUnit(a.probability)) return { ok: false, reason: "invalid_probability" };
|
|
8917
|
-
return { ok: true, answer: { kind: "binary", probability: a.probability } };
|
|
8918
|
-
}
|
|
8919
|
-
const maxScore = question.levels.length - 1;
|
|
8920
|
-
if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
|
|
8921
|
-
return { ok: false, reason: "score_out_of_range" };
|
|
8922
|
-
}
|
|
8923
|
-
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
8924
|
-
if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
|
|
8925
|
-
return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
|
|
8926
|
-
} catch {
|
|
8927
|
-
return { ok: false, reason: "malformed" };
|
|
8928
|
-
}
|
|
8929
|
-
}
|
|
8930
|
-
function classifierStateForFact(fact) {
|
|
8931
|
-
const parts = [fact.title, fact.body];
|
|
8932
|
-
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
8933
|
-
return parts.join("\n\n");
|
|
8934
|
-
}
|
|
8935
|
-
|
|
8936
9569
|
// src/utils/shortlist.ts
|
|
8937
9570
|
function shortlistScore(factTitle, factBody, row) {
|
|
8938
9571
|
const factTokens = /* @__PURE__ */ new Set([...titleTokens(factTitle), ...titleTokens(factBody)]);
|
|
@@ -9010,10 +9643,17 @@ var TemporalService = class {
|
|
|
9010
9643
|
if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
|
|
9011
9644
|
const start = old.valid_from ?? old.created_at;
|
|
9012
9645
|
if (t <= start) throw new WikiSupersedeError("invalid_interval");
|
|
9013
|
-
|
|
9646
|
+
const replacedScheduledEnd = old.valid_to;
|
|
9647
|
+
await this.entryRepo.setTemporal(oldId, entityId, {
|
|
9648
|
+
valid_to: t,
|
|
9649
|
+
superseded_by: newId,
|
|
9650
|
+
superseded_at: now,
|
|
9651
|
+
prior_valid_to: replacedScheduledEnd
|
|
9652
|
+
}, tx);
|
|
9014
9653
|
if (repl.valid_from == null) {
|
|
9015
9654
|
await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
|
|
9016
9655
|
}
|
|
9656
|
+
return { replacedScheduledEnd };
|
|
9017
9657
|
}
|
|
9018
9658
|
async supersede(entityId, oldId, replacement, options) {
|
|
9019
9659
|
const now = Date.now();
|
|
@@ -9042,6 +9682,7 @@ var TemporalService = class {
|
|
|
9042
9682
|
}
|
|
9043
9683
|
const newId = typeof replacement === "string" ? replacement : created.id;
|
|
9044
9684
|
const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
|
|
9685
|
+
let replacedScheduledEnd = null;
|
|
9045
9686
|
await this.db.withTransactionAsync(async (tx) => {
|
|
9046
9687
|
if (created) {
|
|
9047
9688
|
await this.entryRepo.upsert(created, tx);
|
|
@@ -9049,8 +9690,17 @@ var TemporalService = class {
|
|
|
9049
9690
|
await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
|
|
9050
9691
|
}
|
|
9051
9692
|
}
|
|
9052
|
-
await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
|
|
9693
|
+
({ replacedScheduledEnd } = await this.supersedeInTx(tx, entityId, oldId, newId, t, now));
|
|
9053
9694
|
});
|
|
9695
|
+
if (replacedScheduledEnd != null) {
|
|
9696
|
+
emitDiagnostic(this.options, {
|
|
9697
|
+
code: "supersede_scheduled_end_replaced",
|
|
9698
|
+
operation: "supersede",
|
|
9699
|
+
trigger: "call",
|
|
9700
|
+
entityId,
|
|
9701
|
+
detail: { factId: oldId, priorValidTo: replacedScheduledEnd }
|
|
9702
|
+
});
|
|
9703
|
+
}
|
|
9054
9704
|
await this.searchService.syncEntries(entityId, [oldId, newId]);
|
|
9055
9705
|
if (created) {
|
|
9056
9706
|
await this.embeddingService.embedFact(
|
|
@@ -9082,179 +9732,43 @@ var TemporalService = class {
|
|
|
9082
9732
|
await this.searchService.syncEntries(entityId, [factId]);
|
|
9083
9733
|
this.searchService.evictCache(entityId);
|
|
9084
9734
|
}
|
|
9085
|
-
|
|
9086
|
-
|
|
9087
|
-
|
|
9088
|
-
|
|
9089
|
-
|
|
9090
|
-
|
|
9091
|
-
|
|
9092
|
-
|
|
9093
|
-
|
|
9094
|
-
|
|
9095
|
-
|
|
9096
|
-
|
|
9097
|
-
|
|
9098
|
-
|
|
9099
|
-
|
|
9100
|
-
|
|
9101
|
-
|
|
9102
|
-
|
|
9103
|
-
|
|
9104
|
-
|
|
9105
|
-
|
|
9106
|
-
|
|
9107
|
-
|
|
9108
|
-
|
|
9109
|
-
|
|
9110
|
-
|
|
9111
|
-
|
|
9112
|
-
|
|
9113
|
-
}
|
|
9114
|
-
|
|
9115
|
-
|
|
9116
|
-
|
|
9117
|
-
);
|
|
9118
|
-
|
|
9119
|
-
|
|
9120
|
-
|
|
9121
|
-
|
|
9122
|
-
);
|
|
9123
|
-
}
|
|
9124
|
-
return warnings;
|
|
9125
|
-
}
|
|
9126
|
-
var warnedDefaults = /* @__PURE__ */ new Set();
|
|
9127
|
-
function warnChangedDefaultsOnce(config) {
|
|
9128
|
-
for (const message of changedDefaultWarnings(config)) {
|
|
9129
|
-
if (warnedDefaults.has(message)) continue;
|
|
9130
|
-
warnedDefaults.add(message);
|
|
9131
|
-
console.warn(message);
|
|
9132
|
-
}
|
|
9133
|
-
}
|
|
9134
|
-
function warnOnce(message) {
|
|
9135
|
-
if (warnedDefaults.has(message)) return;
|
|
9136
|
-
warnedDefaults.add(message);
|
|
9137
|
-
console.warn(message);
|
|
9138
|
-
}
|
|
9139
|
-
function formatConfigValue(value) {
|
|
9140
|
-
try {
|
|
9141
|
-
const json = JSON.stringify(value);
|
|
9142
|
-
return json ?? String(value);
|
|
9143
|
-
} catch {
|
|
9144
|
-
return `[unserializable: ${typeof value}]`;
|
|
9145
|
-
}
|
|
9146
|
-
}
|
|
9147
|
-
var isTypingMode = (v) => v === "auto" || v === "llm";
|
|
9148
|
-
var isConfidenceFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
|
|
9149
|
-
function resolveSystemOneTyping(config, classifierCallOption) {
|
|
9150
|
-
const systemOne = config?.systemOne;
|
|
9151
|
-
const legacy = config?.ontology?.backfillClassifier;
|
|
9152
|
-
const systemOneValid = isTypingMode(systemOne?.typing);
|
|
9153
|
-
const legacyValid = isTypingMode(legacy);
|
|
9154
|
-
if (systemOne?.typing !== void 0 && !systemOneValid) {
|
|
9155
|
-
warnOnce(
|
|
9156
|
-
`[core-llm-wiki] systemOne: \`systemOne.typing\` is ${formatConfigValue(systemOne.typing)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
9157
|
-
);
|
|
9158
|
-
}
|
|
9159
|
-
if (legacy !== void 0 && !legacyValid) {
|
|
9160
|
-
warnOnce(
|
|
9161
|
-
`[core-llm-wiki] systemOne: \`ontology.backfillClassifier\` is ${formatConfigValue(legacy)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
9162
|
-
);
|
|
9163
|
-
}
|
|
9164
|
-
if (systemOneValid && legacyValid && systemOne.typing !== legacy) {
|
|
9165
|
-
warnOnce(
|
|
9166
|
-
`[core-llm-wiki] systemOne: \`systemOne.typing\` (${systemOne.typing}) and \`ontology.backfillClassifier\` (${legacy}) disagree; \`systemOne.typing\` wins. Remove the legacy key to silence this warning.`
|
|
9167
|
-
);
|
|
9168
|
-
}
|
|
9169
|
-
return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
|
|
9170
|
-
}
|
|
9171
|
-
function resolveSystemOneEdges(config) {
|
|
9172
|
-
const edges = config?.systemOne?.edges;
|
|
9173
|
-
if (edges !== void 0 && !isTypingMode(edges)) {
|
|
9174
|
-
warnOnce(
|
|
9175
|
-
`[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
9176
|
-
);
|
|
9177
|
-
return "llm";
|
|
9178
|
-
}
|
|
9179
|
-
return edges ?? "llm";
|
|
9180
|
-
}
|
|
9181
|
-
function resolveSystemOneResolve(config) {
|
|
9182
|
-
const resolve = config?.systemOne?.resolve;
|
|
9183
|
-
if (resolve !== void 0 && !isTypingMode(resolve)) {
|
|
9184
|
-
warnOnce(
|
|
9185
|
-
`[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
9186
|
-
);
|
|
9187
|
-
return "llm";
|
|
9188
|
-
}
|
|
9189
|
-
return resolve ?? "llm";
|
|
9190
|
-
}
|
|
9191
|
-
var DEFAULT_SHORTLIST_K = 10;
|
|
9192
|
-
function resolveShortlistK(config) {
|
|
9193
|
-
const k = config?.ontology?.shortlistK;
|
|
9194
|
-
if (k === void 0) return DEFAULT_SHORTLIST_K;
|
|
9195
|
-
if (typeof k !== "number" || !Number.isInteger(k) || k < 1) {
|
|
9196
|
-
throw new Error(
|
|
9197
|
-
`[core-llm-wiki] \`ontology.shortlistK\` is ${formatConfigValue(k)}, which is not a finite integer >= 1.`
|
|
9198
|
-
);
|
|
9199
|
-
}
|
|
9200
|
-
return k;
|
|
9201
|
-
}
|
|
9202
|
-
var DEFAULT_TYPING_MIN_CONFIDENCE = 0.5;
|
|
9203
|
-
function resolveTypingMinConfidence(config) {
|
|
9204
|
-
const systemOneFloor = config?.systemOne?.minConfidence?.typing;
|
|
9205
|
-
const legacyFloor = config?.ontology?.classifyMinConfidence;
|
|
9206
|
-
const systemOneValid = isConfidenceFloor(systemOneFloor);
|
|
9207
|
-
const legacyValid = isConfidenceFloor(legacyFloor);
|
|
9208
|
-
if (systemOneFloor !== void 0 && !systemOneValid) {
|
|
9209
|
-
warnOnce(
|
|
9210
|
-
`[core-llm-wiki] systemOne: \`systemOne.minConfidence.typing\` is ${formatConfigValue(systemOneFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
|
|
9211
|
-
);
|
|
9212
|
-
}
|
|
9213
|
-
if (legacyFloor !== void 0 && !legacyValid) {
|
|
9214
|
-
warnOnce(
|
|
9215
|
-
`[core-llm-wiki] systemOne: \`ontology.classifyMinConfidence\` is ${formatConfigValue(legacyFloor)}, which is not a finite number in [0, 1]. The key is treated as unset and the chain continues.`
|
|
9216
|
-
);
|
|
9217
|
-
}
|
|
9218
|
-
return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
|
|
9219
|
-
}
|
|
9220
|
-
var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
|
|
9221
|
-
function resolveEdgesMinConfidence(config) {
|
|
9222
|
-
if (resolveSystemOneEdges(config) !== "auto") return void 0;
|
|
9223
|
-
const floor = config?.systemOne?.minConfidence?.edges;
|
|
9224
|
-
if (isEdgesFloor(floor)) return floor;
|
|
9225
|
-
warnOnce(
|
|
9226
|
-
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
|
|
9227
|
-
);
|
|
9228
|
-
return void 0;
|
|
9229
|
-
}
|
|
9230
|
-
function resolveResolveMinConfidence(config) {
|
|
9231
|
-
if (resolveSystemOneResolve(config) !== "auto") return void 0;
|
|
9232
|
-
const floor = config?.systemOne?.minConfidence?.resolve;
|
|
9233
|
-
if (isEdgesFloor(floor)) return floor;
|
|
9234
|
-
warnOnce(
|
|
9235
|
-
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
|
|
9236
|
-
);
|
|
9237
|
-
return void 0;
|
|
9238
|
-
}
|
|
9239
|
-
function resolveSystemOneHealScreen(config) {
|
|
9240
|
-
const healScreen = config?.systemOne?.healScreen;
|
|
9241
|
-
if (healScreen !== void 0 && !isTypingMode(healScreen)) {
|
|
9242
|
-
warnOnce(
|
|
9243
|
-
`[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
|
|
9244
|
-
);
|
|
9245
|
-
return "llm";
|
|
9246
|
-
}
|
|
9247
|
-
return healScreen ?? "llm";
|
|
9248
|
-
}
|
|
9249
|
-
function resolveHealScreenMinConfidence(config) {
|
|
9250
|
-
if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
|
|
9251
|
-
const floor = config?.systemOne?.minConfidence?.healScreen;
|
|
9252
|
-
if (isEdgesFloor(floor)) return floor;
|
|
9253
|
-
warnOnce(
|
|
9254
|
-
floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
|
|
9255
|
-
);
|
|
9256
|
-
return void 0;
|
|
9257
|
-
}
|
|
9735
|
+
/**
|
|
9736
|
+
* Return a superseded fact to live once its replacement is forgotten or gone
|
|
9737
|
+
* (INTENT rule 12, specs/supersede-future-valid-to D4). Restores `valid_to`
|
|
9738
|
+
* to `prior_valid_to` (null when none was recorded).
|
|
9739
|
+
*/
|
|
9740
|
+
async reopen(entityId, factId) {
|
|
9741
|
+
let restored = null;
|
|
9742
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
9743
|
+
const row = await this.entryRepo.findTemporalRow(factId, tx);
|
|
9744
|
+
if (!row || row.deleted_at != null) throw new WikiSupersedeError("not_found", "reopen()");
|
|
9745
|
+
if (row.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "reopen()");
|
|
9746
|
+
if (row.superseded_by == null) throw new WikiSupersedeError("not_superseded", "reopen()");
|
|
9747
|
+
if (row.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "reopen()");
|
|
9748
|
+
const successor = await this.entryRepo.findTemporalRow(row.superseded_by, tx);
|
|
9749
|
+
if (successor && successor.deleted_at == null) throw new WikiSupersedeError("successor_live", "reopen()");
|
|
9750
|
+
const p = row.prior_valid_to;
|
|
9751
|
+
restored = p != null && Number.isInteger(p) && p > (row.valid_from ?? row.created_at) ? p : null;
|
|
9752
|
+
const changes = await this.entryRepo.setTemporal(factId, entityId, {
|
|
9753
|
+
valid_to: restored,
|
|
9754
|
+
superseded_by: null,
|
|
9755
|
+
superseded_at: null,
|
|
9756
|
+
prior_valid_to: null
|
|
9757
|
+
}, tx);
|
|
9758
|
+
if (changes === 0) throw new WikiSupersedeError("cross_entity", "reopen()");
|
|
9759
|
+
});
|
|
9760
|
+
await this.searchService.syncEntries(entityId, [factId]);
|
|
9761
|
+
this.searchService.evictCache(entityId);
|
|
9762
|
+
return { valid_to: restored };
|
|
9763
|
+
}
|
|
9764
|
+
async history(entityId, factId) {
|
|
9765
|
+
const start = await this.entryRepo.findTemporalRow(factId);
|
|
9766
|
+
if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
|
|
9767
|
+
const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
|
|
9768
|
+
const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
|
|
9769
|
+
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));
|
|
9770
|
+
}
|
|
9771
|
+
};
|
|
9258
9772
|
|
|
9259
9773
|
// src/repositories/VectorRemovalRepository.ts
|
|
9260
9774
|
var CHUNK2 = 500;
|
|
@@ -9815,166 +10329,6 @@ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
|
|
|
9815
10329
|
return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
|
|
9816
10330
|
}
|
|
9817
10331
|
|
|
9818
|
-
// src/services/BoundedLlmCall.ts
|
|
9819
|
-
var DEFAULT_BATCH_SIZE = 10;
|
|
9820
|
-
var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
|
|
9821
|
-
var OUTPUT_BUDGET_FRACTION = 0.8;
|
|
9822
|
-
var TRUNCATION_PATTERNS = [
|
|
9823
|
-
/truncat/i,
|
|
9824
|
-
/token limit/i,
|
|
9825
|
-
/max(imum)?[ _-]?tokens?/i,
|
|
9826
|
-
/output limit/i,
|
|
9827
|
-
/length limit/i,
|
|
9828
|
-
/finish[_ ]?reason/i
|
|
9829
|
-
];
|
|
9830
|
-
var EXCEEDS_LIMIT_PATTERN = /exceed[a-z]*[^.]{0,40}\b(model|context)?[ _-]?limit/i;
|
|
9831
|
-
var RATE_LIMIT_PATTERN = /\b(?:status|http|code|error)[^\d]{0,10}429\b|\b429[ _-]?too[ _-]?many[ _-]?requests\b|\b(rate[ _-]?limit|too many requests|(tokens?|requests?)[ _-]?per[ _-]?(minute|min)\b|retry[ _-]?after|quota exceeded)\b/i;
|
|
9832
|
-
var CONTEXT_OVERFLOW_PATTERNS = [
|
|
9833
|
-
/maximum context length/i,
|
|
9834
|
-
/context[_ ]?length[_ ]?exceeded/i,
|
|
9835
|
-
/prompt is too long/i,
|
|
9836
|
-
/input (token count|is too long)/i,
|
|
9837
|
-
/exceeds? the (available )?context( size)?/i,
|
|
9838
|
-
// Tail requires a context-window clause (context|maximum), NOT bare `token`:
|
|
9839
|
-
// a 429 body like "input exceeds the tokens-per-minute limit" must NOT
|
|
9840
|
-
// classify as input overflow (it would split the batch and stamp a cooldown).
|
|
9841
|
-
/(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
|
|
9842
|
-
/context limit/i,
|
|
9843
|
-
// llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
|
|
9844
|
-
/\bcontext is full\b/i,
|
|
9845
|
-
/too long for (the )?requested model/i,
|
|
9846
|
-
// vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
|
|
9847
|
-
// "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
|
|
9848
|
-
/max[_ ]?tokens?.{0,40}too large.{0,80}context/i
|
|
9849
|
-
];
|
|
9850
|
-
function isContextOverflowError(err) {
|
|
9851
|
-
const message = getErrorMessage(err);
|
|
9852
|
-
if (message === void 0) return false;
|
|
9853
|
-
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9854
|
-
return CONTEXT_OVERFLOW_PATTERNS.some((p) => p.test(message));
|
|
9855
|
-
}
|
|
9856
|
-
function getErrorMessage(err) {
|
|
9857
|
-
try {
|
|
9858
|
-
return err instanceof Error ? err.message : String(err ?? "");
|
|
9859
|
-
} catch {
|
|
9860
|
-
return void 0;
|
|
9861
|
-
}
|
|
9862
|
-
}
|
|
9863
|
-
function isTruncationError(err) {
|
|
9864
|
-
const message = getErrorMessage(err);
|
|
9865
|
-
if (message === void 0) return false;
|
|
9866
|
-
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9867
|
-
if (EXCEEDS_LIMIT_PATTERN.test(message)) return false;
|
|
9868
|
-
return TRUNCATION_PATTERNS.some((pattern) => pattern.test(message));
|
|
9869
|
-
}
|
|
9870
|
-
function isConfigError(err) {
|
|
9871
|
-
const message = getErrorMessage(err);
|
|
9872
|
-
if (message === void 0) return false;
|
|
9873
|
-
if (RATE_LIMIT_PATTERN.test(message)) return false;
|
|
9874
|
-
return EXCEEDS_LIMIT_PATTERN.test(message);
|
|
9875
|
-
}
|
|
9876
|
-
function initialBatchSize(maxOutputTokens) {
|
|
9877
|
-
if (!maxOutputTokens || !Number.isFinite(maxOutputTokens) || maxOutputTokens <= 0) {
|
|
9878
|
-
return DEFAULT_BATCH_SIZE;
|
|
9879
|
-
}
|
|
9880
|
-
const estimate = Math.floor(
|
|
9881
|
-
maxOutputTokens * OUTPUT_BUDGET_FRACTION / ESTIMATED_OUTPUT_TOKENS_PER_ITEM
|
|
9882
|
-
);
|
|
9883
|
-
return Math.max(DEFAULT_BATCH_SIZE, estimate);
|
|
9884
|
-
}
|
|
9885
|
-
var promptLength = (prompts) => prompts.systemPrompt.length + prompts.userPrompt.length;
|
|
9886
|
-
async function runBatched(args) {
|
|
9887
|
-
const { items, buildPrompt, call, parse, maxPromptChars, maxOutputTokens, onSkip, supportsEscalation } = args;
|
|
9888
|
-
const results = [];
|
|
9889
|
-
const skipped = [];
|
|
9890
|
-
let batches = 0;
|
|
9891
|
-
const settled = /* @__PURE__ */ new Set();
|
|
9892
|
-
let budgetStop;
|
|
9893
|
-
let batchSize = initialBatchSize(maxOutputTokens);
|
|
9894
|
-
const trim = async (candidate) => {
|
|
9895
|
-
const whole = await buildPrompt(candidate);
|
|
9896
|
-
if (candidate.length <= 1 || promptLength(whole) <= maxPromptChars) {
|
|
9897
|
-
return { batch: candidate, prompts: whole };
|
|
9898
|
-
}
|
|
9899
|
-
let low = 2;
|
|
9900
|
-
let high = candidate.length - 1;
|
|
9901
|
-
let best;
|
|
9902
|
-
let bestPrompts;
|
|
9903
|
-
while (low <= high) {
|
|
9904
|
-
const mid = Math.floor((low + high) / 2);
|
|
9905
|
-
const batch = candidate.slice(0, mid);
|
|
9906
|
-
const prompts = await buildPrompt(batch);
|
|
9907
|
-
if (promptLength(prompts) <= maxPromptChars) {
|
|
9908
|
-
best = batch;
|
|
9909
|
-
bestPrompts = prompts;
|
|
9910
|
-
low = mid + 1;
|
|
9911
|
-
} else {
|
|
9912
|
-
high = mid - 1;
|
|
9913
|
-
}
|
|
9914
|
-
}
|
|
9915
|
-
if (best && bestPrompts) return { batch: best, prompts: bestPrompts };
|
|
9916
|
-
const single = candidate.slice(0, 1);
|
|
9917
|
-
return { batch: single, prompts: await buildPrompt(single) };
|
|
9918
|
-
};
|
|
9919
|
-
const onFailure = async (batch, err, attemptLevel, fromCall) => {
|
|
9920
|
-
if (batch.length === 1) {
|
|
9921
|
-
if (fromCall && (isContextOverflowError(err) ? supportsEscalation : isTruncationError(err)) && attemptLevel < 3) {
|
|
9922
|
-
await attempt(batch, void 0, attemptLevel + 1);
|
|
9923
|
-
} else {
|
|
9924
|
-
const reason = fromCall && !isTruncationError(err) && !isConfigError(err) && !isContextOverflowError(err) ? "call_error" : "non_convergent";
|
|
9925
|
-
skipped.push({ item: batch[0], reason });
|
|
9926
|
-
settled.add(batch[0]);
|
|
9927
|
-
onSkip?.(batch[0], err);
|
|
9928
|
-
}
|
|
9929
|
-
return;
|
|
9930
|
-
}
|
|
9931
|
-
if (fromCall && !isTruncationError(err) && !isContextOverflowError(err)) throw err;
|
|
9932
|
-
const mid = Math.ceil(batch.length / 2);
|
|
9933
|
-
if (mid < batchSize) batchSize = mid;
|
|
9934
|
-
let i = 0;
|
|
9935
|
-
while (i < batch.length && !budgetStop) {
|
|
9936
|
-
const size = Math.min(batchSize, batch.length - i);
|
|
9937
|
-
const trimmed = await trim(batch.slice(i, i + size));
|
|
9938
|
-
await attempt(trimmed.batch, trimmed.prompts);
|
|
9939
|
-
i += trimmed.batch.length;
|
|
9940
|
-
}
|
|
9941
|
-
};
|
|
9942
|
-
const attempt = async (batch, prebuilt, attemptLevel = 0) => {
|
|
9943
|
-
if (budgetStop) return;
|
|
9944
|
-
if (batch.length === 0) return;
|
|
9945
|
-
const prompts = prebuilt && attemptLevel === 0 ? prebuilt : await buildPrompt(batch, attemptLevel);
|
|
9946
|
-
batches++;
|
|
9947
|
-
let responseText;
|
|
9948
|
-
try {
|
|
9949
|
-
responseText = await call(prompts);
|
|
9950
|
-
} catch (err) {
|
|
9951
|
-
if (err instanceof WikiBudgetExhausted) {
|
|
9952
|
-
budgetStop = { requiredEstimate: err.requiredEstimate };
|
|
9953
|
-
return;
|
|
9954
|
-
}
|
|
9955
|
-
await onFailure(batch, err, attemptLevel, true);
|
|
9956
|
-
return;
|
|
9957
|
-
}
|
|
9958
|
-
let result;
|
|
9959
|
-
try {
|
|
9960
|
-
result = parse(responseText, batch, prompts);
|
|
9961
|
-
} catch (err) {
|
|
9962
|
-
await onFailure(batch, err, attemptLevel, false);
|
|
9963
|
-
return;
|
|
9964
|
-
}
|
|
9965
|
-
results.push(result);
|
|
9966
|
-
for (const item of batch) settled.add(item);
|
|
9967
|
-
};
|
|
9968
|
-
let index = 0;
|
|
9969
|
-
while (index < items.length && !budgetStop) {
|
|
9970
|
-
const { batch, prompts } = await trim(items.slice(index, index + batchSize));
|
|
9971
|
-
index += batch.length;
|
|
9972
|
-
await attempt(batch, prompts, 0);
|
|
9973
|
-
}
|
|
9974
|
-
const unattempted = budgetStop ? items.filter((item) => !settled.has(item)) : [];
|
|
9975
|
-
return { results, skipped, batches, unattempted, ...budgetStop ? { budgetStop } : {} };
|
|
9976
|
-
}
|
|
9977
|
-
|
|
9978
10332
|
// src/services/librarian/constants.ts
|
|
9979
10333
|
var FUZZY_THRESHOLD = 0.5;
|
|
9980
10334
|
var MIN_TOKENS_TO_QUALIFY = 3;
|
|
@@ -9992,7 +10346,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
9992
10346
|
tags: typeof rest.tags === "string" ? JSON.parse(rest.tags) : rest.tags
|
|
9993
10347
|
};
|
|
9994
10348
|
});
|
|
9995
|
-
const
|
|
10349
|
+
const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
|
|
10350
|
+
const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
|
|
10351
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
|
|
9996
10352
|
const promptEvents = events.reverse();
|
|
9997
10353
|
const librarianGrounding = deps.promptService.groundingFor("librarian");
|
|
9998
10354
|
const { systemPrompt, userPrompt, groundingCorpus: librarianCorpus = [] } = deps.promptService.buildLibrarianPrompt(
|
|
@@ -10038,6 +10394,22 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
10038
10394
|
if (valid) validTasks.push(valid);
|
|
10039
10395
|
else diagBuffer.push({ ...diagBase, code: "task_rejected", detail: { itemIndex, reason: taskRejectionReason(raw) } });
|
|
10040
10396
|
});
|
|
10397
|
+
const typingCounters = engaged ? emptyTypingCounters() : void 0;
|
|
10398
|
+
const typingOutcomes = /* @__PURE__ */ new Map();
|
|
10399
|
+
if (engaged && typingState && typingCounters) {
|
|
10400
|
+
const asked = validFacts.filter((f) => !volunteeredTypeResolves(f.okf_type, typingState.manifest));
|
|
10401
|
+
const outcomes = await classifyFactsForWrite(
|
|
10402
|
+
deps.options,
|
|
10403
|
+
{ entityId, trigger, meter: ctx.meter, operation: "librarian" },
|
|
10404
|
+
asked,
|
|
10405
|
+
typingState.manifest,
|
|
10406
|
+
resolveTypingMinConfidence(deps.options.config)
|
|
10407
|
+
);
|
|
10408
|
+
asked.forEach((f, i) => {
|
|
10409
|
+
typingOutcomes.set(f, outcomes[i]);
|
|
10410
|
+
tallyTypingOutcome(typingCounters, outcomes[i]);
|
|
10411
|
+
});
|
|
10412
|
+
}
|
|
10041
10413
|
const now = Date.now();
|
|
10042
10414
|
const insertedFacts = [];
|
|
10043
10415
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
@@ -10084,20 +10456,18 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
10084
10456
|
}
|
|
10085
10457
|
const ontologyFact = fact;
|
|
10086
10458
|
const id = generateId("fact_");
|
|
10087
|
-
const validationDrops =
|
|
10088
|
-
|
|
10459
|
+
const { normalized, drops: validationDrops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
|
|
10460
|
+
deps.ontologyService,
|
|
10461
|
+
ontologyFact,
|
|
10462
|
+
manifest,
|
|
10463
|
+
mode,
|
|
10464
|
+
typingOutcomes.get(fact),
|
|
10465
|
+
diagBase,
|
|
10466
|
+
id
|
|
10467
|
+
);
|
|
10089
10468
|
for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
|
|
10090
|
-
|
|
10091
|
-
|
|
10092
|
-
{ entityId, operation: "librarian", trigger },
|
|
10093
|
-
id,
|
|
10094
|
-
ontologyFact.okf_type ?? "",
|
|
10095
|
-
normalized.okf_type,
|
|
10096
|
-
normalized.match
|
|
10097
|
-
)) {
|
|
10098
|
-
diagBuffer.push(receipt);
|
|
10099
|
-
}
|
|
10100
|
-
}
|
|
10469
|
+
for (const receipt of doorReceipts) diagBuffer.push(receipt);
|
|
10470
|
+
if (typedByClassifier && typingCounters) typingCounters.typed++;
|
|
10101
10471
|
const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
|
|
10102
10472
|
if (grounding?.diagnostic) {
|
|
10103
10473
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
@@ -10177,7 +10547,7 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
10177
10547
|
}
|
|
10178
10548
|
deps.searchService.evictCache(entityId);
|
|
10179
10549
|
const processedThrough = events.length > 0 ? { at: events[events.length - 1].created_at, id: events[events.length - 1].id } : null;
|
|
10180
|
-
const out = { processedThrough, factsWritten: insertedFacts.length };
|
|
10550
|
+
const out = { processedThrough, factsWritten: insertedFacts.length, ...typingCounters ? { typing: typingCounters } : {} };
|
|
10181
10551
|
return out;
|
|
10182
10552
|
};
|
|
10183
10553
|
|
|
@@ -10204,7 +10574,7 @@ var RESOLVE_RESERVE_FACTOR = 2;
|
|
|
10204
10574
|
var MIN_SEGMENT_CHARS = 500;
|
|
10205
10575
|
var MAX_SEGMENT_CALLS = 8;
|
|
10206
10576
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
10207
|
-
async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
10577
|
+
async function selectBatch(deps, entityId, wm, meter, guidance, budget, engaged = false) {
|
|
10208
10578
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
10209
10579
|
if (events.length === 0) return { batch: [] };
|
|
10210
10580
|
const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
|
|
@@ -10217,7 +10587,7 @@ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
|
10217
10587
|
}
|
|
10218
10588
|
let batch = labelEvents(events.slice(0, n));
|
|
10219
10589
|
if (meter && meter.budget !== void 0) {
|
|
10220
|
-
const ontologyContext = await deps.ontologyService?.
|
|
10590
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
|
|
10221
10591
|
for (; ; ) {
|
|
10222
10592
|
const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
|
|
10223
10593
|
if (meter.fits(need)) break;
|
|
@@ -10373,8 +10743,8 @@ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe
|
|
|
10373
10743
|
return { ...merged, batch: [lone] };
|
|
10374
10744
|
}
|
|
10375
10745
|
}
|
|
10376
|
-
async function runExtract(deps, ctx, batch) {
|
|
10377
|
-
const ontologyContext = await deps.ontologyService?.
|
|
10746
|
+
async function runExtract(deps, ctx, batch, engaged = false) {
|
|
10747
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(ctx.entityId, { engaged }) ?? null;
|
|
10378
10748
|
return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
|
|
10379
10749
|
}
|
|
10380
10750
|
async function extractOnce(deps, ctx, ontologyContext, batch) {
|
|
@@ -10678,6 +11048,17 @@ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
|
|
|
10678
11048
|
}
|
|
10679
11049
|
return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
|
|
10680
11050
|
}
|
|
11051
|
+
function mergeDerivedEvents(existing, contributing) {
|
|
11052
|
+
if (contributing === null || contributing === existing.source_pointer?.event_id) return void 0;
|
|
11053
|
+
const prior = existing.derived_events ?? [];
|
|
11054
|
+
if (prior.includes(contributing)) return void 0;
|
|
11055
|
+
return dedupeEventIds([...prior, contributing]);
|
|
11056
|
+
}
|
|
11057
|
+
function inheritedDerivedEvents(target, ownEventId) {
|
|
11058
|
+
if (!target) return {};
|
|
11059
|
+
const list = dedupeEventIds([target.source_pointer?.event_id, ...target.derived_events ?? []]).filter((id) => id !== ownEventId);
|
|
11060
|
+
return list.length > 0 ? { derived_events: list } : {};
|
|
11061
|
+
}
|
|
10681
11062
|
async function applyOps(deps, ctx, input) {
|
|
10682
11063
|
const { entityId, trigger } = ctx;
|
|
10683
11064
|
const diagBase = { entityId, operation: "librarian", trigger };
|
|
@@ -10687,6 +11068,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
10687
11068
|
const failed = new Set(input.failed);
|
|
10688
11069
|
const written = [];
|
|
10689
11070
|
const updatedIds = [];
|
|
11071
|
+
const supersededIds = [];
|
|
10690
11072
|
const now = Date.now();
|
|
10691
11073
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
10692
11074
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
@@ -10707,24 +11089,22 @@ async function applyOps(deps, ctx, input) {
|
|
|
10707
11089
|
titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
|
|
10708
11090
|
}
|
|
10709
11091
|
const pendingEdges = [];
|
|
10710
|
-
const insert = async (g, draft, validFrom, overrides) => {
|
|
11092
|
+
const insert = async (g, draft, validFrom, overrides, inheritFrom) => {
|
|
10711
11093
|
const fact = g.candidate.fact;
|
|
10712
11094
|
const title = overrides?.title ?? fact.title;
|
|
10713
11095
|
const body = overrides?.body ?? fact.body;
|
|
10714
11096
|
const id = generateId("fact_");
|
|
10715
|
-
const drops =
|
|
10716
|
-
|
|
10717
|
-
|
|
10718
|
-
|
|
10719
|
-
|
|
10720
|
-
|
|
10721
|
-
|
|
10722
|
-
|
|
10723
|
-
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
}
|
|
10727
|
-
}
|
|
11097
|
+
const { normalized, drops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
|
|
11098
|
+
deps.ontologyService,
|
|
11099
|
+
fact,
|
|
11100
|
+
manifest,
|
|
11101
|
+
mode,
|
|
11102
|
+
input.typing?.outcomes.get(g),
|
|
11103
|
+
diagBase,
|
|
11104
|
+
id
|
|
11105
|
+
);
|
|
11106
|
+
for (const receipt of doorReceipts) input.diagnostics.push(receipt);
|
|
11107
|
+
if (typedByClassifier && input.typing) input.typing.counters.typed++;
|
|
10728
11108
|
for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
|
|
10729
11109
|
const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
|
|
10730
11110
|
const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
|
|
@@ -10753,6 +11133,9 @@ async function applyOps(deps, ctx, input) {
|
|
|
10753
11133
|
deleted_at: null,
|
|
10754
11134
|
okf_type: normalized.okf_type,
|
|
10755
11135
|
source_pointer: pointer,
|
|
11136
|
+
// §2: only an UPDATE converted to SUPERSEDE inherits (the merged text
|
|
11137
|
+
// rests on the target); ADD and plain SUPERSEDE carry no list.
|
|
11138
|
+
...inheritedDerivedEvents(inheritFrom, pointer?.event_id ?? null),
|
|
10756
11139
|
...g2?.trust,
|
|
10757
11140
|
...draft ? { lifecycle_status: "draft" } : {}
|
|
10758
11141
|
};
|
|
@@ -10771,7 +11154,18 @@ async function applyOps(deps, ctx, input) {
|
|
|
10771
11154
|
written.push({ id, vector: textChanged ? null : g.vector, fact: { id, entity_id: entityId, title, body, tags: fact.tags } });
|
|
10772
11155
|
return id;
|
|
10773
11156
|
};
|
|
11157
|
+
const sourceIds = [...new Set(input.gated.map((g) => g.candidate.sourceEventId).filter((x) => x !== null))];
|
|
11158
|
+
const presentIds = sourceIds.length > 0 ? await deps.eventRepo.findExistingIds(entityId, sourceIds, tx) : /* @__PURE__ */ new Set();
|
|
11159
|
+
const gatedLive = [];
|
|
10774
11160
|
for (const g of input.gated) {
|
|
11161
|
+
const ev = g.candidate.sourceEventId;
|
|
11162
|
+
if (ev !== null && !presentIds.has(ev)) {
|
|
11163
|
+
input.diagnostics.push({ ...diagBase, code: "source_event_gone", detail: { itemIndex: g.candidate.index, sourceRef: ev } });
|
|
11164
|
+
continue;
|
|
11165
|
+
}
|
|
11166
|
+
gatedLive.push(g);
|
|
11167
|
+
}
|
|
11168
|
+
for (const g of gatedLive) {
|
|
10775
11169
|
const idx = g.candidate.index;
|
|
10776
11170
|
const vf = g.candidate.validFrom;
|
|
10777
11171
|
if (g.decision.kind === "noop") continue;
|
|
@@ -10800,28 +11194,50 @@ async function applyOps(deps, ctx, input) {
|
|
|
10800
11194
|
const [existing] = await deps.entryRepo.findByIds([op.targetId], [entityId], tx);
|
|
10801
11195
|
if (existing) {
|
|
10802
11196
|
const newTitle = op.title ?? g.candidate.fact.title;
|
|
11197
|
+
const contributing = g.candidate.sourceEventId;
|
|
11198
|
+
if (contributing === null && g.candidate.pointerUnresolved !== null) {
|
|
11199
|
+
input.diagnostics.push({
|
|
11200
|
+
...diagBase,
|
|
11201
|
+
code: "source_pointer_unresolved",
|
|
11202
|
+
detail: { factId: existing.id, itemIndex: idx, reason: g.candidate.pointerUnresolved }
|
|
11203
|
+
});
|
|
11204
|
+
}
|
|
11205
|
+
const derived = mergeDerivedEvents(existing, contributing);
|
|
10803
11206
|
await deps.entryRepo.upsert({
|
|
10804
11207
|
...existing,
|
|
10805
11208
|
title: newTitle,
|
|
10806
11209
|
body: op.body ?? g.candidate.fact.body,
|
|
10807
|
-
updated_at: now
|
|
11210
|
+
updated_at: now,
|
|
11211
|
+
...derived ? { derived_events: derived } : {}
|
|
10808
11212
|
}, tx);
|
|
10809
11213
|
titleIndex.delete(normalizeTitleKey(existing.title));
|
|
10810
11214
|
titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
|
|
10811
11215
|
updatedIds.push(existing.id);
|
|
11216
|
+
input.diagnostics.push({ ...diagBase, code: "librarian_rewritten", detail: { factId: existing.id } });
|
|
10812
11217
|
continue;
|
|
10813
11218
|
}
|
|
10814
11219
|
}
|
|
10815
11220
|
const supersedeFrom = op.op === "SUPERSEDE" && op.validFrom !== void 0 ? op.validFrom : vf;
|
|
10816
11221
|
const overrides = op.op === "UPDATE" ? { title: op.title, body: op.body } : void 0;
|
|
10817
11222
|
if (target.source_type === "immutable_document") {
|
|
10818
|
-
const
|
|
11223
|
+
const docTarget = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
|
|
11224
|
+
const id = await insert(g, true, supersedeFrom, overrides, docTarget);
|
|
10819
11225
|
input.diagnostics.push({ ...diagBase, code: "contradicts_document", detail: { factId: id, itemIndex: idx } });
|
|
10820
11226
|
continue;
|
|
10821
11227
|
}
|
|
10822
|
-
const
|
|
11228
|
+
const inheritFrom = op.op === "UPDATE" ? (await deps.entryRepo.findByIds([op.targetId], [entityId], tx))[0] : void 0;
|
|
11229
|
+
const newId = await insert(g, false, supersedeFrom, overrides, inheritFrom);
|
|
10823
11230
|
try {
|
|
10824
|
-
await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
|
|
11231
|
+
const { replacedScheduledEnd } = await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
|
|
11232
|
+
supersededIds.push(op.targetId);
|
|
11233
|
+
input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
|
|
11234
|
+
if (replacedScheduledEnd != null) {
|
|
11235
|
+
input.diagnostics.push({
|
|
11236
|
+
...diagBase,
|
|
11237
|
+
code: "supersede_scheduled_end_replaced",
|
|
11238
|
+
detail: { factId: op.targetId, priorValidTo: replacedScheduledEnd }
|
|
11239
|
+
});
|
|
11240
|
+
}
|
|
10825
11241
|
} catch (err) {
|
|
10826
11242
|
if (!(err instanceof WikiSupersedeError)) throw err;
|
|
10827
11243
|
input.diagnostics.push({
|
|
@@ -10861,7 +11277,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
10861
11277
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
10862
11278
|
}
|
|
10863
11279
|
});
|
|
10864
|
-
return { written, updatedIds };
|
|
11280
|
+
return { written, updatedIds, supersededIds };
|
|
10865
11281
|
}
|
|
10866
11282
|
|
|
10867
11283
|
// src/services/librarian/ops/index.ts
|
|
@@ -10870,7 +11286,9 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10870
11286
|
const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
|
|
10871
11287
|
await deps.seedWatermark(entityId);
|
|
10872
11288
|
const wm = await deps.getWatermark(entityId);
|
|
10873
|
-
const
|
|
11289
|
+
const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
|
|
11290
|
+
const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
|
|
11291
|
+
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config), engaged);
|
|
10874
11292
|
if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
|
|
10875
11293
|
if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
|
|
10876
11294
|
if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
|
|
@@ -10878,7 +11296,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10878
11296
|
}
|
|
10879
11297
|
let ex;
|
|
10880
11298
|
try {
|
|
10881
|
-
ex = await runExtract(deps, ctx, sel.batch);
|
|
11299
|
+
ex = await runExtract(deps, ctx, sel.batch, engaged);
|
|
10882
11300
|
} catch (err) {
|
|
10883
11301
|
if (err instanceof WikiBudgetExhausted) {
|
|
10884
11302
|
return { processedThrough: null, factsWritten: 0, budgetStop: { requiredEstimate: err.requiredEstimate } };
|
|
@@ -10923,7 +11341,33 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10923
11341
|
diagnostics.discard();
|
|
10924
11342
|
return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
|
|
10925
11343
|
}
|
|
10926
|
-
const
|
|
11344
|
+
const typingCounters = engaged ? emptyTypingCounters() : void 0;
|
|
11345
|
+
const typingOutcomes = /* @__PURE__ */ new Map();
|
|
11346
|
+
if (engaged && typingState && typingCounters) {
|
|
11347
|
+
const failed = new Set(res.failed);
|
|
11348
|
+
const rejected = new Set(res.rejected);
|
|
11349
|
+
const asked = gated.filter((g) => {
|
|
11350
|
+
if (g.decision.kind === "noop") return false;
|
|
11351
|
+
if (volunteeredTypeResolves(g.candidate.fact.okf_type, typingState.manifest)) return false;
|
|
11352
|
+
if (g.decision.kind === "add" || failed.has(g)) return true;
|
|
11353
|
+
const op = res.ops.get(g);
|
|
11354
|
+
if (rejected.has(g) || !op) return true;
|
|
11355
|
+
return op.op !== "NOOP";
|
|
11356
|
+
});
|
|
11357
|
+
const outcomes = await classifyFactsForWrite(
|
|
11358
|
+
deps.options,
|
|
11359
|
+
{ entityId, trigger, meter: ctx.meter, operation: "librarian" },
|
|
11360
|
+
asked.map((g) => g.candidate.fact),
|
|
11361
|
+
typingState.manifest,
|
|
11362
|
+
resolveTypingMinConfidence(deps.options.config)
|
|
11363
|
+
);
|
|
11364
|
+
asked.forEach((g, n) => {
|
|
11365
|
+
typingOutcomes.set(g, outcomes[n]);
|
|
11366
|
+
tallyTypingOutcome(typingCounters, outcomes[n]);
|
|
11367
|
+
});
|
|
11368
|
+
}
|
|
11369
|
+
const { written, updatedIds, supersededIds } = await applyOps(deps, ctx, {
|
|
11370
|
+
typing: typingCounters ? { outcomes: typingOutcomes, counters: typingCounters } : void 0,
|
|
10927
11371
|
gated,
|
|
10928
11372
|
ops: res.ops,
|
|
10929
11373
|
rejected: res.rejected,
|
|
@@ -10952,7 +11396,10 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
10952
11396
|
const last = ex.batch[ex.batch.length - 1].event;
|
|
10953
11397
|
return {
|
|
10954
11398
|
processedThrough: { at: last.created_at, id: last.id },
|
|
10955
|
-
factsWritten: written.length + updatedIds.length
|
|
11399
|
+
factsWritten: written.length + updatedIds.length,
|
|
11400
|
+
...typingCounters ? { typing: typingCounters } : {},
|
|
11401
|
+
rewrittenIds: updatedIds,
|
|
11402
|
+
supersededIds
|
|
10956
11403
|
};
|
|
10957
11404
|
};
|
|
10958
11405
|
|
|
@@ -10974,7 +11421,6 @@ async function runLibrarianStrategy(deps, ctx) {
|
|
|
10974
11421
|
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.`;
|
|
10975
11422
|
var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
|
|
10976
11423
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
10977
|
-
var CLASSIFIER_MAX_CHOICES = 255;
|
|
10978
11424
|
var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
|
|
10979
11425
|
var HEAL_BATCH_SIZE = 25;
|
|
10980
11426
|
var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -12562,8 +13008,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
12562
13008
|
const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
|
|
12563
13009
|
const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
|
|
12564
13010
|
if (classifierMode === "auto" && typeof classify === "function") {
|
|
12565
|
-
|
|
12566
|
-
if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
|
|
13011
|
+
if (isManifestRepresentable(effectiveManifest)) {
|
|
12567
13012
|
const classifierRun = await this._runClassifierBackfill(
|
|
12568
13013
|
entityId,
|
|
12569
13014
|
candidates,
|
|
@@ -12812,12 +13257,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
12812
13257
|
const minConfidence = resolveTypingMinConfidence(this.options.config);
|
|
12813
13258
|
const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
|
|
12814
13259
|
const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
|
|
12815
|
-
const question =
|
|
12816
|
-
kind: "choice",
|
|
12817
|
-
options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
|
|
12818
|
-
instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
|
|
12819
|
-
` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
|
|
12820
|
-
};
|
|
13260
|
+
const question = buildTypingQuestion(manifest);
|
|
12821
13261
|
const edgeScreen = /* @__PURE__ */ new Map();
|
|
12822
13262
|
if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
|
|
12823
13263
|
const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
|
|
@@ -13305,8 +13745,8 @@ var MaintenanceScheduler = class {
|
|
|
13305
13745
|
* `budget_too_small` > `complete`. `budget_too_small` means a job's smallest
|
|
13306
13746
|
* unit needs more than the WHOLE budget — that job is skipped this run and
|
|
13307
13747
|
* the run continues; `budget_exhausted` means a unit needs more than what
|
|
13308
|
-
* REMAINS — the run stops. The token budget meters
|
|
13309
|
-
*
|
|
13748
|
+
* REMAINS — the run stops. The token budget meters generation and classify
|
|
13749
|
+
* calls; embeddings are never metered.
|
|
13310
13750
|
*/
|
|
13311
13751
|
async run(opts = {}) {
|
|
13312
13752
|
if (opts.deadlineMs !== void 0 && (typeof opts.deadlineMs !== "number" || !Number.isFinite(opts.deadlineMs) || opts.deadlineMs < 0)) {
|
|
@@ -13387,7 +13827,12 @@ var MaintenanceScheduler = class {
|
|
|
13387
13827
|
}
|
|
13388
13828
|
st.report.librarianPasses++;
|
|
13389
13829
|
st.report.factsWritten += r.factsWritten;
|
|
13830
|
+
if (r.typing) st.report.typedOnWrite = (st.report.typedOnWrite ?? 0) + r.typing.typed;
|
|
13390
13831
|
progressed = true;
|
|
13832
|
+
if ((r.typing?.unattempted ?? 0) > 0) {
|
|
13833
|
+
stopped = exhaustedStop();
|
|
13834
|
+
break rounds;
|
|
13835
|
+
}
|
|
13391
13836
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
13392
13837
|
if (await this.eventRepo.countAfter(entityId, wm) === 0) st.librarian = false;
|
|
13393
13838
|
continue;
|
|
@@ -13909,6 +14354,19 @@ var ImportExportService = class {
|
|
|
13909
14354
|
});
|
|
13910
14355
|
}
|
|
13911
14356
|
const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
|
|
14357
|
+
const rawDerived = fact["derived_events"];
|
|
14358
|
+
const hasDerivedEventsKey = rawDerived !== void 0;
|
|
14359
|
+
const derivedValidated = hasDerivedEventsKey ? validateDerivedEventsValue(rawDerived) : null;
|
|
14360
|
+
if (derivedValidated === void 0) {
|
|
14361
|
+
refusalDiagnostics.push({
|
|
14362
|
+
code: "derived_events_invalid",
|
|
14363
|
+
operation: "importDump",
|
|
14364
|
+
trigger: "call",
|
|
14365
|
+
entityId,
|
|
14366
|
+
detail: { factId: fact.id }
|
|
14367
|
+
});
|
|
14368
|
+
}
|
|
14369
|
+
const derivedEvents = derivedValidated ?? null;
|
|
13912
14370
|
const factObj = {
|
|
13913
14371
|
id: fact.id,
|
|
13914
14372
|
entity_id: entityId,
|
|
@@ -13927,6 +14385,7 @@ var ImportExportService = class {
|
|
|
13927
14385
|
embedding_blob: blobData ?? void 0,
|
|
13928
14386
|
okf_type: fact.okf_type ?? null,
|
|
13929
14387
|
source_pointer: sourcePointer,
|
|
14388
|
+
...derivedEvents ? { derived_events: derivedEvents } : {},
|
|
13930
14389
|
// OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
|
|
13931
14390
|
// populating these per spec, importDump does not derive or validate them.
|
|
13932
14391
|
lifecycle_status: fact.lifecycle_status ?? "stable",
|
|
@@ -13944,12 +14403,15 @@ var ImportExportService = class {
|
|
|
13944
14403
|
return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
|
|
13945
14404
|
})()
|
|
13946
14405
|
};
|
|
13947
|
-
await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
|
|
14406
|
+
await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey, hasDerivedEventsKey);
|
|
13948
14407
|
await this.entryRepo.setTemporal(fact.id, entityId, {
|
|
13949
14408
|
valid_from: fact.valid_from ?? null,
|
|
13950
14409
|
valid_to: fact.valid_to ?? null,
|
|
13951
14410
|
superseded_by: fact.superseded_by ?? null,
|
|
13952
|
-
superseded_at: fact.superseded_at ?? null
|
|
14411
|
+
superseded_at: fact.superseded_at ?? null,
|
|
14412
|
+
// prior_valid_to (spec D5): replace semantics like the four siblings;
|
|
14413
|
+
// null whenever the row is not superseded (the column's invariant).
|
|
14414
|
+
prior_valid_to: fact.superseded_by == null ? null : fact.prior_valid_to ?? null
|
|
13953
14415
|
}, tx, { outbox: false });
|
|
13954
14416
|
if (blobData != null) {
|
|
13955
14417
|
factsWithPreservedBlob.set(fact.id, blobData);
|
|
@@ -15723,6 +16185,33 @@ function buildOntologyPromptAppendix(mode, manifestJson) {
|
|
|
15723
16185
|
].filter(Boolean).join("\n");
|
|
15724
16186
|
return { ontologyManifest: manifestJson, ontologyModeInstructions };
|
|
15725
16187
|
}
|
|
16188
|
+
var WRITE_FACT_ONTOLOGY_FIELDS = `
|
|
16189
|
+
Each fact may optionally include:
|
|
16190
|
+
- "okf_type": string \u2014 must be one of the node_types in the manifest
|
|
16191
|
+
- "edges": [{ "edge_type": string, "target_title": string }] \u2014 target_title must match another fact's title in this response or existing memory
|
|
16192
|
+
- An edge_type may appear in the manifest multiple times with different source_type/target_type; use the row whose types match your fact and target.
|
|
16193
|
+
Each node is a fact. To link two things with an edge, each must exist as its own fact, titled by the same name you use in \`target_title\`.`;
|
|
16194
|
+
var WRITE_EMERGENT_EXTRA = `
|
|
16195
|
+
You may also return "ontology_updates" to propose new types:
|
|
16196
|
+
"ontology_updates": {
|
|
16197
|
+
"node_types": [{ "type": "slug", "description": "...", "parent_type": "optional existing slug" }],
|
|
16198
|
+
"edge_types": [{ "type": "slug", "source_type": "...", "target_type": "...", "description": "..." }]
|
|
16199
|
+
}
|
|
16200
|
+
Only propose types not already in the manifest. Do not redefine existing types.`;
|
|
16201
|
+
function buildWriteOntologyAppendix(mode, manifestJson) {
|
|
16202
|
+
const strictRules = mode === "strict" ? "STRICT MODE: Use ONLY types defined in the manifest. If a fact does not fit a node_type, choose the closest type the fact is an example of; omit only when none applies even broadly." : "EMERGENT MODE: Prefer manifest types. You may propose new types via ontology_updates when necessary.";
|
|
16203
|
+
const fallback = "If okf_type or an edge is invalid, omit them rather than inventing unlisted types.";
|
|
16204
|
+
const ontologyModeInstructions = [
|
|
16205
|
+
"## Ontology constraints",
|
|
16206
|
+
strictRules,
|
|
16207
|
+
fallback,
|
|
16208
|
+
WRITE_FACT_ONTOLOGY_FIELDS,
|
|
16209
|
+
mode === "emergent" ? WRITE_EMERGENT_EXTRA : "",
|
|
16210
|
+
"Manifest:",
|
|
16211
|
+
manifestJson
|
|
16212
|
+
].filter(Boolean).join("\n");
|
|
16213
|
+
return { site: "write", ontologyManifest: manifestJson, ontologyModeInstructions };
|
|
16214
|
+
}
|
|
15726
16215
|
|
|
15727
16216
|
// src/services/OntologyService.ts
|
|
15728
16217
|
var OntologyService = class {
|
|
@@ -15771,6 +16260,17 @@ var OntologyService = class {
|
|
|
15771
16260
|
const manifestJson = JSON.stringify(manifest, null, 2);
|
|
15772
16261
|
return buildOntologyPromptAppendix(mode, manifestJson);
|
|
15773
16262
|
}
|
|
16263
|
+
/**
|
|
16264
|
+
* Ontology prompt context for the WRITE builders (specs/type-on-write §5).
|
|
16265
|
+
* `null` when the mode is `'off'` or when write-time typing is `engaged`
|
|
16266
|
+
* (the classifier types the fact, so the manifest leaves the write prompt).
|
|
16267
|
+
* Backfill keeps `buildPromptContext`.
|
|
16268
|
+
*/
|
|
16269
|
+
async buildWritePromptContext(entityId, opts) {
|
|
16270
|
+
const { mode, manifest } = await this.getEffectiveState(entityId);
|
|
16271
|
+
if (mode === "off" || opts.engaged) return null;
|
|
16272
|
+
return buildWriteOntologyAppendix(mode, JSON.stringify(manifest, null, 2));
|
|
16273
|
+
}
|
|
15774
16274
|
async mergeEmergentUpdates(entityId, updates, tx) {
|
|
15775
16275
|
const filtered = updates.node_types ? { ...updates, node_types: updates.node_types.filter((nt) => !isReservedAbstainSlug(nt.type)) } : updates;
|
|
15776
16276
|
const { manifest: merged, rejected } = await this.metadataRepo.mergeManifestUpdates(entityId, filtered, tx);
|
|
@@ -16634,6 +17134,7 @@ var WikiMemory = class {
|
|
|
16634
17134
|
if (!entriesExistedBeforeSetup) {
|
|
16635
17135
|
await this.db.withTransactionAsync(async (tx) => {
|
|
16636
17136
|
await createLegacySourceTypeIndex(tx, this.prefix);
|
|
17137
|
+
await createEntriesDeletedIndex(tx, this.prefix);
|
|
16637
17138
|
await writeNormalizeStamp(this.metadataRepo, tx);
|
|
16638
17139
|
await this.metadataRepo.setMeta("schema_version", String(CURRENT_SCHEMA_VERSION), tx);
|
|
16639
17140
|
});
|
|
@@ -16841,7 +17342,11 @@ var WikiMemory = class {
|
|
|
16841
17342
|
*/
|
|
16842
17343
|
async getInstructions(entityId) {
|
|
16843
17344
|
assertEntityId2(entityId);
|
|
16844
|
-
const
|
|
17345
|
+
const state = await this.ontologyService.getEffectiveState(entityId);
|
|
17346
|
+
const engaged = canEngageWriteTyping(this.options.config, this.options.llmProvider, state.mode, state.manifest);
|
|
17347
|
+
const writeContext = await this.ontologyService.buildWritePromptContext(entityId, { engaged });
|
|
17348
|
+
const ingestContext = engaged ? await this.ontologyService.buildWritePromptContext(entityId, { engaged: false }) : writeContext;
|
|
17349
|
+
const backfillContext = await this.ontologyService.buildPromptContext(entityId);
|
|
16845
17350
|
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
|
|
16846
17351
|
if (diagnostic) {
|
|
16847
17352
|
emitDiagnostic(this.options, {
|
|
@@ -16852,7 +17357,7 @@ var WikiMemory = class {
|
|
|
16852
17357
|
detail: diagnostic.detail
|
|
16853
17358
|
});
|
|
16854
17359
|
}
|
|
16855
|
-
return this.promptService.buildInstructionTemplates(
|
|
17360
|
+
return this.promptService.buildInstructionTemplates(writeContext, resolveLibrarianStrategy(this.options.config), guidance, backfillContext, ingestContext);
|
|
16856
17361
|
}
|
|
16857
17362
|
/**
|
|
16858
17363
|
* Returns the live source_refs for an entity, one row per ref, with the most
|
|
@@ -17210,7 +17715,10 @@ var WikiMemory = class {
|
|
|
17210
17715
|
* End `oldId`'s validity and link it to its replacement (spec §4.3). One
|
|
17211
17716
|
* transaction. Throws `WikiSupersedeError` for missing, foreign, already
|
|
17212
17717
|
* superseded, already expired, immutable-document, or cyclic targets, and
|
|
17213
|
-
* for an inverted or empty interval (`invalid_interval`).
|
|
17718
|
+
* for an inverted or empty interval (`invalid_interval`). When the old
|
|
17719
|
+
* fact carried a future `valid_to`, that scheduled end is overwritten but
|
|
17720
|
+
* kept in `prior_valid_to` (restored by `reopen()`) and reported as the
|
|
17721
|
+
* `supersede_scheduled_end_replaced` diagnostic.
|
|
17214
17722
|
*/
|
|
17215
17723
|
async supersede(entityId, oldId, replacement, options) {
|
|
17216
17724
|
return this.temporalService.supersede(entityId, oldId, replacement, options);
|
|
@@ -17227,6 +17735,20 @@ var WikiMemory = class {
|
|
|
17227
17735
|
async expire(entityId, factId, options) {
|
|
17228
17736
|
return this.temporalService.expire(entityId, factId, options);
|
|
17229
17737
|
}
|
|
17738
|
+
/**
|
|
17739
|
+
* Return a superseded fact to live once its replacement has been forgotten
|
|
17740
|
+
* or hard-deleted (INTENT rule 12). Clears `superseded_by`/`superseded_at`
|
|
17741
|
+
* and restores `valid_to` to the scheduled end `supersede()` overwrote
|
|
17742
|
+
* (`prior_valid_to`), or null when the fact was open-ended. Resolves with
|
|
17743
|
+
* the restored `valid_to`. Throws `WikiSupersedeError` for a missing or
|
|
17744
|
+
* foreign fact, one that is not superseded (an `expire()`-ended fact is
|
|
17745
|
+
* not reopened), an immutable-document fact, or `successor_live` while the
|
|
17746
|
+
* direct replacement is still live. A restored end that has already passed
|
|
17747
|
+
* leaves the fact expired.
|
|
17748
|
+
*/
|
|
17749
|
+
async reopen(entityId, factId) {
|
|
17750
|
+
return this.temporalService.reopen(entityId, factId);
|
|
17751
|
+
}
|
|
17230
17752
|
/** The supersession chain containing `factId`, oldest first. [] when unknown. */
|
|
17231
17753
|
async history(entityId, factId) {
|
|
17232
17754
|
return this.temporalService.history(entityId, factId);
|
|
@@ -17915,8 +18437,11 @@ function factFrontmatterV2(f) {
|
|
|
17915
18437
|
...f.valid_to != null ? { valid_to: f.valid_to } : {},
|
|
17916
18438
|
...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
|
|
17917
18439
|
...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
|
|
18440
|
+
...f.prior_valid_to != null ? { prior_valid_to: f.prior_valid_to } : {},
|
|
17918
18441
|
// Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
|
|
17919
|
-
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
18442
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
18443
|
+
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
18444
|
+
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
17920
18445
|
};
|
|
17921
18446
|
}
|
|
17922
18447
|
function taskFrontmatterV2(t) {
|
|
@@ -17962,7 +18487,9 @@ function factFrontmatterV1(f) {
|
|
|
17962
18487
|
last_accessed_at: f.last_accessed_at,
|
|
17963
18488
|
deleted_at: f.deleted_at,
|
|
17964
18489
|
// Source pointer (specs/source-pointers): same map rule as the v2 path.
|
|
17965
|
-
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
|
|
18490
|
+
...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {},
|
|
18491
|
+
// derived_events (specs/inplace-update-provenance §5): optional list, only when non-empty.
|
|
18492
|
+
...f.derived_events && f.derived_events.length > 0 ? { derived_events: f.derived_events } : {}
|
|
17966
18493
|
};
|
|
17967
18494
|
}
|
|
17968
18495
|
function taskFrontmatterV1(t) {
|
|
@@ -18273,6 +18800,7 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
|
|
|
18273
18800
|
...optionalEpoch("valid_to", frontmatter.valid_to),
|
|
18274
18801
|
...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
|
|
18275
18802
|
...optionalEpoch("superseded_at", frontmatter.superseded_at),
|
|
18803
|
+
...optionalEpoch("prior_valid_to", frontmatter.prior_valid_to),
|
|
18276
18804
|
// Source pointer (specs/source-pointers §Export, import, and OKF): the
|
|
18277
18805
|
// parse path has no diagnostic channel, so it reports through the result.
|
|
18278
18806
|
// ABSENT key → the property is omitted (not null), so the import
|
|
@@ -18288,6 +18816,19 @@ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerV
|
|
|
18288
18816
|
return {};
|
|
18289
18817
|
}
|
|
18290
18818
|
return { source_pointer: v };
|
|
18819
|
+
})(),
|
|
18820
|
+
// derived_events (specs/inplace-update-provenance §5): a well-formed list
|
|
18821
|
+
// is restored; absent or empty omits the property (import presence rule);
|
|
18822
|
+
// malformed omits it AND is reported by id + slug, never the raw value.
|
|
18823
|
+
...(() => {
|
|
18824
|
+
const raw = frontmatter.derived_events;
|
|
18825
|
+
if (raw === void 0) return {};
|
|
18826
|
+
const v = validateDerivedEventsValue(raw);
|
|
18827
|
+
if (v === void 0) {
|
|
18828
|
+
droppedPointerValues.push({ factId: id, reason: "derived_events_malformed" });
|
|
18829
|
+
return {};
|
|
18830
|
+
}
|
|
18831
|
+
return v ? { derived_events: v } : {};
|
|
18291
18832
|
})()
|
|
18292
18833
|
};
|
|
18293
18834
|
}
|
|
@@ -18612,6 +19153,7 @@ exports.resolveResolveMinConfidence = resolveResolveMinConfidence;
|
|
|
18612
19153
|
exports.resolveSystemOneEdges = resolveSystemOneEdges;
|
|
18613
19154
|
exports.resolveSystemOneHealScreen = resolveSystemOneHealScreen;
|
|
18614
19155
|
exports.resolveSystemOneResolve = resolveSystemOneResolve;
|
|
19156
|
+
exports.resolveSystemOneTypeOnWrite = resolveSystemOneTypeOnWrite;
|
|
18615
19157
|
exports.resolveSystemOneTyping = resolveSystemOneTyping;
|
|
18616
19158
|
exports.resolveTypingMinConfidence = resolveTypingMinConfidence;
|
|
18617
19159
|
exports.safeSlice = safeSlice;
|