@equationalapplications/core-llm-wiki 9.6.0 → 9.8.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-TZMLWQ3G.mjs → chunk-EN37KODZ.mjs} +338 -43
- package/dist/chunk-EN37KODZ.mjs.map +1 -0
- package/dist/index.d.mts +47 -19
- package/dist/index.d.ts +47 -19
- package/dist/index.js +426 -59
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +90 -22
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BBeQQIYp.d.mts → testing-CDSfjx8j.d.mts} +64 -9
- package/dist/{testing-BBeQQIYp.d.ts → testing-CDSfjx8j.d.ts} +64 -9
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +299 -26
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-TZMLWQ3G.mjs.map +0 -1
package/dist/testing.js
CHANGED
|
@@ -758,7 +758,11 @@ var SEVERITY = {
|
|
|
758
758
|
source_store_budget_exceeded: "warn",
|
|
759
759
|
source_store_hash_mismatch: "warn",
|
|
760
760
|
source_store_duplicate_hash: "warn",
|
|
761
|
-
source_store_text_not_storable: "warn"
|
|
761
|
+
source_store_text_not_storable: "warn",
|
|
762
|
+
node_type_dropped: "warn",
|
|
763
|
+
node_type_folded: "info",
|
|
764
|
+
ontology_update_rejected: "warn",
|
|
765
|
+
ingest_zero_facts: "warn"
|
|
762
766
|
};
|
|
763
767
|
var MESSAGE = {
|
|
764
768
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -807,8 +811,48 @@ var MESSAGE = {
|
|
|
807
811
|
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
808
812
|
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
809
813
|
source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
|
|
810
|
-
source_store_text_not_storable: "A source document text could not be stored as given."
|
|
814
|
+
source_store_text_not_storable: "A source document text could not be stored as given.",
|
|
815
|
+
node_type_dropped: "A supplied node type missed the ontology manifest and the fact was stored untyped.",
|
|
816
|
+
node_type_folded: "A supplied node type was normalized into the manifest canonical slug.",
|
|
817
|
+
ontology_update_rejected: "An emergent ontology proposal was rejected during the merge.",
|
|
818
|
+
ingest_zero_facts: "A re-ingest tombstoned prior facts and edges and then wrote zero facts."
|
|
811
819
|
};
|
|
820
|
+
function shouldEmitOntologyReceipt(mode) {
|
|
821
|
+
return mode !== "off";
|
|
822
|
+
}
|
|
823
|
+
function capReceiptSlug(slug) {
|
|
824
|
+
return typeof slug === "string" ? slug.slice(0, 64) : "";
|
|
825
|
+
}
|
|
826
|
+
function nodeTypeReceipts(base, factId, rawType, okfType, match) {
|
|
827
|
+
const out = [];
|
|
828
|
+
const supplied = typeof rawType === "string" ? rawType.trim() : "";
|
|
829
|
+
if (match && match.via === "normalize") {
|
|
830
|
+
const to = capReceiptSlug(match.canonical);
|
|
831
|
+
out.push({
|
|
832
|
+
...base,
|
|
833
|
+
code: "node_type_folded",
|
|
834
|
+
detail: {
|
|
835
|
+
factId,
|
|
836
|
+
nodeType: to,
|
|
837
|
+
from: capReceiptSlug(match.raw),
|
|
838
|
+
to,
|
|
839
|
+
via: "normalize"
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
if (!okfType && supplied) {
|
|
844
|
+
out.push({
|
|
845
|
+
...base,
|
|
846
|
+
code: "node_type_dropped",
|
|
847
|
+
detail: {
|
|
848
|
+
factId,
|
|
849
|
+
nodeType: capReceiptSlug(supplied),
|
|
850
|
+
reason: "not_in_manifest"
|
|
851
|
+
}
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
return out;
|
|
855
|
+
}
|
|
812
856
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
813
857
|
function copyDetail(detail) {
|
|
814
858
|
const copy = { ...detail };
|
|
@@ -1270,10 +1314,27 @@ var BaseRepository = class {
|
|
|
1270
1314
|
function normalizeTitleKey(title) {
|
|
1271
1315
|
return title.trim().toLowerCase().replace(/\s+/g, " ");
|
|
1272
1316
|
}
|
|
1317
|
+
function normalizeSlug(raw) {
|
|
1318
|
+
return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
|
|
1319
|
+
}
|
|
1273
1320
|
var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
|
|
1274
1321
|
function isReservedAbstainSlug(raw) {
|
|
1275
1322
|
return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
|
|
1276
1323
|
}
|
|
1324
|
+
function resolveEdgeDefinitions(rawEdgeType, manifest) {
|
|
1325
|
+
const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
|
|
1326
|
+
if (!slug) return [];
|
|
1327
|
+
const lowered = slug.toLowerCase();
|
|
1328
|
+
const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
|
|
1329
|
+
if (exact.length > 0) return exact;
|
|
1330
|
+
const normalized = normalizeSlug(slug);
|
|
1331
|
+
if (!normalized) return [];
|
|
1332
|
+
const names = new Set(
|
|
1333
|
+
manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
|
|
1334
|
+
);
|
|
1335
|
+
if (names.size !== 1) return [];
|
|
1336
|
+
return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
|
|
1337
|
+
}
|
|
1277
1338
|
function typeSatisfies(declaredType, concreteType, manifest) {
|
|
1278
1339
|
const concrete = concreteType.trim().toLowerCase();
|
|
1279
1340
|
const declared = declaredType.trim().toLowerCase();
|
|
@@ -2414,7 +2475,8 @@ Return ONLY a valid JSON object matching this schema:
|
|
|
2414
2475
|
{
|
|
2415
2476
|
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
2416
2477
|
}
|
|
2417
|
-
Extract verbatim factual content. JSON escaping rules: every literal " character in the source must be escaped as \\" inside any JSON string body, and every literal newline as \\n. Source prose containing quotes (e.g. a worked example with "...") must still be reproduced exactly \u2014 re-escape, do not omit. Do not return markdown, just raw JSON
|
|
2478
|
+
Extract verbatim factual content. JSON escaping rules: every literal " character in the source must be escaped as \\" inside any JSON string body, and every literal newline as \\n. Source prose containing quotes (e.g. a worked example with "...") must still be reproduced exactly \u2014 re-escape, do not omit. Do not return markdown, just raw JSON.
|
|
2479
|
+
When the ontology manifest is present in your instructions, supply okf_type for each fact: use a manifest slug exactly as spelled (spelling variants like underscores, hyphens, or spaces are folded to the manifest form), or omit okf_type when no manifest type fits.`;
|
|
2418
2480
|
var ONTOLOGY_BACKFILL_SYSTEM_PROMPT = `You are a knowledge classification agent. You will receive existing memory facts that currently have no ontology type. For each input fact { "id", "title", "body", "tags" }, assign the best matching okf_type from the ontology manifest and optionally propose edges to related facts by title.
|
|
2419
2481
|
Return ONLY a valid JSON object matching this schema:
|
|
2420
2482
|
{
|
|
@@ -2422,7 +2484,7 @@ Return ONLY a valid JSON object matching this schema:
|
|
|
2422
2484
|
{ "id": "string (input fact id, copied verbatim)", "okf_type": "string (manifest node type slug)", "edges": [{ "edge_type": "string", "target_title": "string" }] }
|
|
2423
2485
|
]
|
|
2424
2486
|
}
|
|
2425
|
-
If no manifest type fits a fact, omit that fact from "classifications"
|
|
2487
|
+
If no manifest type fits a fact, assign the closest type the fact is an example of; omit that fact from "classifications" only when no type applies even broadly. Use the manifest slug EXACTLY as spelled (spelling variants are folded to the manifest form).
|
|
2426
2488
|
When echoing an existing fact's title verbatim into "target_title", preserve every JSON escape sequence (\\", \\n, \\\\, \\/) exactly as it appeared in the input body \u2014 do not strip backslashes, do not add unescaped quotes. Do not return markdown, just raw JSON.`;
|
|
2427
2489
|
var TITLE_CATALOG_MAX_ENTRIES = 200;
|
|
2428
2490
|
function buildTitleCatalogBlock(rows) {
|
|
@@ -2898,6 +2960,74 @@ function toGroundingAnchor(anchor) {
|
|
|
2898
2960
|
var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
|
|
2899
2961
|
var DEFAULT_CHUNK_OVERLAP = 400;
|
|
2900
2962
|
|
|
2963
|
+
// src/utils/contextCaps.ts
|
|
2964
|
+
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
2965
|
+
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
2966
|
+
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
2967
|
+
|
|
2968
|
+
// src/config/context.ts
|
|
2969
|
+
var DEFAULT_CHARS_PER_TOKEN = 4;
|
|
2970
|
+
var DEFAULT_SAFETY_FRACTION = 0.9;
|
|
2971
|
+
var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
|
|
2972
|
+
var OP_FLOOR = {
|
|
2973
|
+
resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
2974
|
+
heal: HEAL_MAX_PROMPT_CHARS,
|
|
2975
|
+
extract: OPS_MAX_EXTRACT_CHARS
|
|
2976
|
+
};
|
|
2977
|
+
function bad(key, value, why) {
|
|
2978
|
+
return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
|
|
2979
|
+
}
|
|
2980
|
+
function resolveContextBudget(config) {
|
|
2981
|
+
const context = config?.context;
|
|
2982
|
+
if (!context || context.budget === void 0) {
|
|
2983
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
2984
|
+
}
|
|
2985
|
+
if (context.budget !== "legacy" && context.budget !== "declared") {
|
|
2986
|
+
throw bad("budget", context.budget, "'legacy' or 'declared'");
|
|
2987
|
+
}
|
|
2988
|
+
if (context.budget === "legacy") {
|
|
2989
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
2990
|
+
}
|
|
2991
|
+
const window = context.contextWindowTokens;
|
|
2992
|
+
if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
|
|
2993
|
+
throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
|
|
2994
|
+
}
|
|
2995
|
+
const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
2996
|
+
if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
|
|
2997
|
+
throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
|
|
2998
|
+
}
|
|
2999
|
+
const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
|
|
3000
|
+
if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
|
|
3001
|
+
throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
|
|
3002
|
+
}
|
|
3003
|
+
const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
|
|
3004
|
+
if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
|
|
3005
|
+
throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
|
|
3006
|
+
}
|
|
3007
|
+
return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
|
|
3008
|
+
}
|
|
3009
|
+
function declaredPromptCap(budget, op) {
|
|
3010
|
+
const derived = Math.floor(
|
|
3011
|
+
(budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
|
|
3012
|
+
);
|
|
3013
|
+
if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
|
|
3014
|
+
return Math.max(OP_FLOOR.heal, derived);
|
|
3015
|
+
}
|
|
3016
|
+
function resolveMaxPromptChars(budget, op) {
|
|
3017
|
+
if (budget.mode !== "declared") {
|
|
3018
|
+
return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
|
|
3019
|
+
}
|
|
3020
|
+
if (op === "extract") {
|
|
3021
|
+
const resolveDerived = declaredPromptCap(budget, "resolve");
|
|
3022
|
+
const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
|
|
3023
|
+
return Math.max(OP_FLOOR.extract, extractDerived);
|
|
3024
|
+
}
|
|
3025
|
+
return declaredPromptCap(budget, op);
|
|
3026
|
+
}
|
|
3027
|
+
function resolveDefaultChunkLength(budget) {
|
|
3028
|
+
return DEFAULT_MAX_CHUNK_LENGTH;
|
|
3029
|
+
}
|
|
3030
|
+
|
|
2901
3031
|
// src/utils/usage.ts
|
|
2902
3032
|
function estimateTokens(text) {
|
|
2903
3033
|
return Math.ceil(text.length / 4);
|
|
@@ -3038,7 +3168,7 @@ var IngestionService = class {
|
|
|
3038
3168
|
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
3039
3169
|
const sourceHash = normalizeSourceHash(params.sourceHash);
|
|
3040
3170
|
if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
|
|
3041
|
-
const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ??
|
|
3171
|
+
const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
|
|
3042
3172
|
const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
|
|
3043
3173
|
const chunkOverlap = Math.min(
|
|
3044
3174
|
Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
|
|
@@ -3228,6 +3358,15 @@ var IngestionService = class {
|
|
|
3228
3358
|
});
|
|
3229
3359
|
deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
|
|
3230
3360
|
insertedFacts.push(...fullResult.insertedFacts);
|
|
3361
|
+
if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
|
|
3362
|
+
diagBuffer.push({
|
|
3363
|
+
entityId,
|
|
3364
|
+
operation: "ingest",
|
|
3365
|
+
trigger: "call",
|
|
3366
|
+
code: "ingest_zero_facts",
|
|
3367
|
+
detail: { sourceRef, chunks: chunks2.length }
|
|
3368
|
+
});
|
|
3369
|
+
}
|
|
3231
3370
|
} else {
|
|
3232
3371
|
const partialResult = await this.db.withTransactionAsync(async (tx) => {
|
|
3233
3372
|
const flat = [];
|
|
@@ -3365,6 +3504,20 @@ var IngestionService = class {
|
|
|
3365
3504
|
strict: strictEffective,
|
|
3366
3505
|
entityId
|
|
3367
3506
|
}) ?? { okf_type: null};
|
|
3507
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
3508
|
+
for (const receipt of nodeTypeReceipts(
|
|
3509
|
+
{ entityId, operation: opts?.diag?.operation ?? "upsertGraph", trigger: "call" },
|
|
3510
|
+
node.id,
|
|
3511
|
+
node.type ?? "",
|
|
3512
|
+
normalized.okf_type,
|
|
3513
|
+
normalized.match
|
|
3514
|
+
)) {
|
|
3515
|
+
opts?.diag?.buffer.push({
|
|
3516
|
+
...receipt,
|
|
3517
|
+
detail: { ...receipt.detail, sourceRef: params.sourceRef }
|
|
3518
|
+
});
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3368
3521
|
const wikiFact = {
|
|
3369
3522
|
id: node.id,
|
|
3370
3523
|
entity_id: entityId,
|
|
@@ -3419,8 +3572,8 @@ var IngestionService = class {
|
|
|
3419
3572
|
continue;
|
|
3420
3573
|
}
|
|
3421
3574
|
const sourceType = sourceIdToType.get(edge.sourceId);
|
|
3422
|
-
const candidates = (
|
|
3423
|
-
(d) =>
|
|
3575
|
+
const candidates = resolveEdgeDefinitions(edge.type, manifest).filter(
|
|
3576
|
+
(d) => typeSatisfies(d.source_type, sourceType ?? "", manifest)
|
|
3424
3577
|
);
|
|
3425
3578
|
const match = candidates[0];
|
|
3426
3579
|
if (!match) {
|
|
@@ -3499,9 +3652,18 @@ var IngestionService = class {
|
|
|
3499
3652
|
const now = Date.now();
|
|
3500
3653
|
for (const { facts, ontology_updates } of orderedChunkFacts) {
|
|
3501
3654
|
if (mode === "emergent" && ontology_updates && this.ontologyService) {
|
|
3502
|
-
manifest = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
|
|
3655
|
+
const { manifest: merged, rejected } = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
|
|
3656
|
+
manifest = merged;
|
|
3657
|
+
for (const reason of rejected) {
|
|
3658
|
+
diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason } });
|
|
3659
|
+
}
|
|
3503
3660
|
ontologyState = await this.ontologyService.getEffectiveState(entityId, tx);
|
|
3504
3661
|
mode = ontologyState.mode;
|
|
3662
|
+
} else if (mode === "strict" && ontology_updates) {
|
|
3663
|
+
const proposalCount = (Array.isArray(ontology_updates.node_types) ? ontology_updates.node_types.length : 0) + (Array.isArray(ontology_updates.edge_types) ? ontology_updates.edge_types.length : 0);
|
|
3664
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
3665
|
+
diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
3666
|
+
}
|
|
3505
3667
|
}
|
|
3506
3668
|
for (const fact of facts) {
|
|
3507
3669
|
const ontologyFact = fact;
|
|
@@ -3599,6 +3761,14 @@ var IngestionService = class {
|
|
|
3599
3761
|
const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
|
|
3600
3762
|
const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
|
|
3601
3763
|
const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
|
|
3764
|
+
const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
3765
|
+
const { mode, manifest } = ontologyState;
|
|
3766
|
+
const titleIndex = /* @__PURE__ */ new Map();
|
|
3767
|
+
const indexedFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx);
|
|
3768
|
+
for (const f of indexedFacts) {
|
|
3769
|
+
titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
|
|
3770
|
+
}
|
|
3771
|
+
const pendingEdges = [];
|
|
3602
3772
|
let inserted = 0;
|
|
3603
3773
|
let skippedDuplicate = 0;
|
|
3604
3774
|
const now = Date.now();
|
|
@@ -3623,6 +3793,26 @@ var IngestionService = class {
|
|
|
3623
3793
|
detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
|
|
3624
3794
|
});
|
|
3625
3795
|
}
|
|
3796
|
+
const ontologyFact = fact;
|
|
3797
|
+
const validationDrops = [];
|
|
3798
|
+
const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
|
|
3799
|
+
for (const drop of validationDrops) {
|
|
3800
|
+
diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
|
|
3801
|
+
}
|
|
3802
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
3803
|
+
for (const receipt of nodeTypeReceipts(
|
|
3804
|
+
{ entityId, operation: "ingest", trigger: "call" },
|
|
3805
|
+
id,
|
|
3806
|
+
ontologyFact.okf_type ?? "",
|
|
3807
|
+
normalized.okf_type,
|
|
3808
|
+
normalized.match
|
|
3809
|
+
)) {
|
|
3810
|
+
diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
if (normalized.edges.length > 0) {
|
|
3814
|
+
pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
|
|
3815
|
+
}
|
|
3626
3816
|
const wikiFact = {
|
|
3627
3817
|
id,
|
|
3628
3818
|
entity_id: entityId,
|
|
@@ -3641,10 +3831,11 @@ var IngestionService = class {
|
|
|
3641
3831
|
last_accessed_at: null,
|
|
3642
3832
|
access_count: 0,
|
|
3643
3833
|
deleted_at: null,
|
|
3644
|
-
okf_type:
|
|
3834
|
+
okf_type: normalized.okf_type,
|
|
3645
3835
|
...outcome?.trust
|
|
3646
3836
|
};
|
|
3647
3837
|
await this.entryRepo.upsert(wikiFact, tx);
|
|
3838
|
+
titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
|
|
3648
3839
|
insertedDescriptors.push({
|
|
3649
3840
|
id,
|
|
3650
3841
|
entity_id: entityId,
|
|
@@ -3654,6 +3845,27 @@ var IngestionService = class {
|
|
|
3654
3845
|
});
|
|
3655
3846
|
inserted++;
|
|
3656
3847
|
}
|
|
3848
|
+
if (pendingEdges.length > 0) {
|
|
3849
|
+
for (const req of pendingEdges) {
|
|
3850
|
+
const resolveDrops = [];
|
|
3851
|
+
const resolved = this.ontologyService?.resolveEdges(
|
|
3852
|
+
entityId,
|
|
3853
|
+
req.sourceId,
|
|
3854
|
+
req.sourceType,
|
|
3855
|
+
req.edges,
|
|
3856
|
+
manifest,
|
|
3857
|
+
titleIndex,
|
|
3858
|
+
now,
|
|
3859
|
+
resolveDrops
|
|
3860
|
+
) ?? [];
|
|
3861
|
+
for (const drop of resolveDrops) {
|
|
3862
|
+
diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef }));
|
|
3863
|
+
}
|
|
3864
|
+
for (const edge of resolved) {
|
|
3865
|
+
await this.edgeRepo.addIgnoreDuplicate(edge, tx);
|
|
3866
|
+
}
|
|
3867
|
+
}
|
|
3868
|
+
}
|
|
3657
3869
|
return { inserted, skippedDuplicate, insertedDescriptors };
|
|
3658
3870
|
}
|
|
3659
3871
|
};
|
|
@@ -4802,7 +5014,16 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
4802
5014
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
4803
5015
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
4804
5016
|
if (mode === "emergent" && ontologyUpdates && deps.ontologyService) {
|
|
4805
|
-
manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
5017
|
+
const { manifest: merged, rejected } = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
5018
|
+
manifest = merged;
|
|
5019
|
+
for (const reason of rejected) {
|
|
5020
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
5021
|
+
}
|
|
5022
|
+
} else if (mode === "strict" && ontologyUpdates) {
|
|
5023
|
+
const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
|
|
5024
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
5025
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
5026
|
+
}
|
|
4806
5027
|
}
|
|
4807
5028
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
4808
5029
|
for (const existing of currentFactsRows) {
|
|
@@ -4837,6 +5058,17 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
4837
5058
|
const validationDrops = [];
|
|
4838
5059
|
const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
|
|
4839
5060
|
for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
|
|
5061
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
5062
|
+
for (const receipt of nodeTypeReceipts(
|
|
5063
|
+
{ entityId, operation: "librarian", trigger },
|
|
5064
|
+
id,
|
|
5065
|
+
ontologyFact.okf_type ?? "",
|
|
5066
|
+
normalized.okf_type,
|
|
5067
|
+
normalized.match
|
|
5068
|
+
)) {
|
|
5069
|
+
diagBuffer.push(receipt);
|
|
5070
|
+
}
|
|
5071
|
+
}
|
|
4840
5072
|
const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
|
|
4841
5073
|
if (grounding?.diagnostic) {
|
|
4842
5074
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
@@ -4939,18 +5171,18 @@ function parseValidFrom(v) {
|
|
|
4939
5171
|
|
|
4940
5172
|
// src/services/librarian/ops/extract.ts
|
|
4941
5173
|
var OPS_MAX_EVENTS_PER_PASS = 50;
|
|
4942
|
-
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
4943
5174
|
var RESOLVE_RESERVE_FACTOR = 2;
|
|
4944
5175
|
var MIN_SEGMENT_CHARS = 500;
|
|
4945
5176
|
var MAX_SEGMENT_CALLS = 8;
|
|
4946
5177
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
4947
|
-
async function selectBatch(deps, entityId, wm, meter, guidance) {
|
|
5178
|
+
async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
4948
5179
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
4949
5180
|
if (events.length === 0) return { batch: [] };
|
|
5181
|
+
const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
|
|
4950
5182
|
let n = 0;
|
|
4951
5183
|
let chars = 0;
|
|
4952
5184
|
for (const e of events) {
|
|
4953
|
-
if (n > 0 && chars + e.summary.length >
|
|
5185
|
+
if (n > 0 && chars + e.summary.length > extractCap) break;
|
|
4954
5186
|
chars += e.summary.length;
|
|
4955
5187
|
n++;
|
|
4956
5188
|
}
|
|
@@ -5289,7 +5521,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
|
|
|
5289
5521
|
}
|
|
5290
5522
|
|
|
5291
5523
|
// src/services/librarian/ops/resolve.ts
|
|
5292
|
-
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
5293
5524
|
function validateOp(raw, aliases) {
|
|
5294
5525
|
if (!raw || typeof raw !== "object") return null;
|
|
5295
5526
|
const r = raw;
|
|
@@ -5308,7 +5539,7 @@ function validateOp(raw, aliases) {
|
|
|
5308
5539
|
return update;
|
|
5309
5540
|
}
|
|
5310
5541
|
var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
|
|
5311
|
-
async function runResolve(deps, ctx, ambiguous) {
|
|
5542
|
+
async function runResolve(deps, ctx, ambiguous, budget) {
|
|
5312
5543
|
const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
|
|
5313
5544
|
if (ambiguous.length === 0) return out;
|
|
5314
5545
|
const { entityId, trigger } = ctx;
|
|
@@ -5334,7 +5565,7 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
5334
5565
|
onSkip: (g, err) => {
|
|
5335
5566
|
if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
|
|
5336
5567
|
},
|
|
5337
|
-
maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
5568
|
+
maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
5338
5569
|
maxOutputTokens: deps.options.llmProvider.maxOutputTokens
|
|
5339
5570
|
});
|
|
5340
5571
|
if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
|
|
@@ -5384,7 +5615,16 @@ async function applyOps(deps, ctx, input) {
|
|
|
5384
5615
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
5385
5616
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
5386
5617
|
if (mode === "emergent" && input.ontologyUpdates && deps.ontologyService) {
|
|
5387
|
-
manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
|
|
5618
|
+
const { manifest: merged, rejected: rejected2 } = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
|
|
5619
|
+
manifest = merged;
|
|
5620
|
+
for (const reason of rejected2) {
|
|
5621
|
+
input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
5622
|
+
}
|
|
5623
|
+
} else if (mode === "strict" && input.ontologyUpdates) {
|
|
5624
|
+
const proposalCount = (Array.isArray(input.ontologyUpdates.node_types) ? input.ontologyUpdates.node_types.length : 0) + (Array.isArray(input.ontologyUpdates.edge_types) ? input.ontologyUpdates.edge_types.length : 0);
|
|
5625
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
5626
|
+
input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
5627
|
+
}
|
|
5388
5628
|
}
|
|
5389
5629
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
5390
5630
|
for (const f of await deps.entryRepo.findRecentByEntityId(entityId, 100, tx)) {
|
|
@@ -5398,6 +5638,17 @@ async function applyOps(deps, ctx, input) {
|
|
|
5398
5638
|
const id = generateId("fact_");
|
|
5399
5639
|
const drops = [];
|
|
5400
5640
|
const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
|
|
5641
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
5642
|
+
for (const receipt of nodeTypeReceipts(
|
|
5643
|
+
{ entityId, operation: "librarian", trigger },
|
|
5644
|
+
id,
|
|
5645
|
+
typeof fact.okf_type === "string" ? fact.okf_type : "",
|
|
5646
|
+
normalized.okf_type,
|
|
5647
|
+
normalized.match
|
|
5648
|
+
)) {
|
|
5649
|
+
input.diagnostics.push(receipt);
|
|
5650
|
+
}
|
|
5651
|
+
}
|
|
5401
5652
|
for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
|
|
5402
5653
|
const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
|
|
5403
5654
|
const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
|
|
@@ -5543,7 +5794,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
5543
5794
|
const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
|
|
5544
5795
|
await deps.seedWatermark(entityId);
|
|
5545
5796
|
const wm = await deps.getWatermark(entityId);
|
|
5546
|
-
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
|
|
5797
|
+
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
|
|
5547
5798
|
if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
|
|
5548
5799
|
if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
|
|
5549
5800
|
if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
|
|
@@ -5571,7 +5822,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
5571
5822
|
});
|
|
5572
5823
|
}
|
|
5573
5824
|
diagnostics.push(gateDiagnostic);
|
|
5574
|
-
const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
|
|
5825
|
+
const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
|
|
5575
5826
|
for (const itemIndex of res.overflowSkipped) {
|
|
5576
5827
|
diagnostics.push({
|
|
5577
5828
|
entityId,
|
|
@@ -5640,7 +5891,6 @@ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
|
5640
5891
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
5641
5892
|
var CLASSIFIER_MAX_CHOICES = 255;
|
|
5642
5893
|
var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
|
|
5643
|
-
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
5644
5894
|
var HEAL_BATCH_SIZE = 25;
|
|
5645
5895
|
var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
5646
5896
|
var MAX_EMBED_ATTEMPTS = 5;
|
|
@@ -6944,7 +7194,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
6944
7194
|
};
|
|
6945
7195
|
},
|
|
6946
7196
|
maxOutputTokens: this.options.llmProvider.maxOutputTokens,
|
|
6947
|
-
maxPromptChars:
|
|
7197
|
+
maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
|
|
6948
7198
|
// heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
|
|
6949
7199
|
supportsEscalation: true,
|
|
6950
7200
|
onSkip: (fact, err) => {
|
|
@@ -7107,12 +7357,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7107
7357
|
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
7108
7358
|
throw new Error("Invalid batchSize: must be an integer >= 1");
|
|
7109
7359
|
}
|
|
7360
|
+
if (options?.recheckCheckedBefore !== void 0 && (!Number.isInteger(options.recheckCheckedBefore) || options.recheckCheckedBefore < 0)) {
|
|
7361
|
+
throw new Error("Invalid recheckCheckedBefore: must be an integer >= 0");
|
|
7362
|
+
}
|
|
7110
7363
|
if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
|
|
7111
7364
|
throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
|
|
7112
7365
|
}
|
|
7113
7366
|
const trigger = options?.trigger ?? "call";
|
|
7114
7367
|
const now = Date.now();
|
|
7115
|
-
const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
|
|
7368
|
+
const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
|
|
7116
7369
|
const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
|
|
7117
7370
|
const ontologyService = this.ontologyService;
|
|
7118
7371
|
if (!ontologyService) {
|
|
@@ -7156,7 +7409,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7156
7409
|
promptOverride: options?.promptOverride,
|
|
7157
7410
|
meter: options?.meter,
|
|
7158
7411
|
trigger,
|
|
7159
|
-
batchSize: escalated.length
|
|
7412
|
+
batchSize: escalated.length,
|
|
7413
|
+
recheckCutoff
|
|
7160
7414
|
});
|
|
7161
7415
|
return {
|
|
7162
7416
|
scanned: classifierRun.result.scanned,
|
|
@@ -7176,7 +7430,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7176
7430
|
return this._runGenerativeBackfill(entityId, candidates, {
|
|
7177
7431
|
promptOverride: options?.promptOverride,
|
|
7178
7432
|
meter: options?.meter,
|
|
7179
|
-
trigger
|
|
7433
|
+
trigger,
|
|
7434
|
+
recheckCutoff
|
|
7180
7435
|
});
|
|
7181
7436
|
}
|
|
7182
7437
|
/**
|
|
@@ -7206,7 +7461,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7206
7461
|
runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
|
|
7207
7462
|
const ontologyService = this.ontologyService;
|
|
7208
7463
|
const now = Date.now();
|
|
7209
|
-
const recheckCutoff =
|
|
7464
|
+
const recheckCutoff = runOpts.recheckCutoff;
|
|
7210
7465
|
const ontologyContext = await ontologyService.buildPromptContext(entityId);
|
|
7211
7466
|
const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
|
|
7212
7467
|
const titleCatalog = buildTitleCatalogBlock(titleRows);
|
|
@@ -7458,7 +7713,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7458
7713
|
return;
|
|
7459
7714
|
}
|
|
7460
7715
|
if (txMode === "emergent" && ontologyUpdates) {
|
|
7461
|
-
manifest = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
7716
|
+
const { manifest: merged, rejected } = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
7717
|
+
manifest = merged;
|
|
7718
|
+
for (const reason of rejected) {
|
|
7719
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
7720
|
+
}
|
|
7721
|
+
} else if (txMode === "strict" && ontologyUpdates) {
|
|
7722
|
+
const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
|
|
7723
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
7724
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
7725
|
+
}
|
|
7462
7726
|
}
|
|
7463
7727
|
const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId, tx);
|
|
7464
7728
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
@@ -7492,6 +7756,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7492
7756
|
for (const drop of validationDrops) {
|
|
7493
7757
|
diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: fact.id }));
|
|
7494
7758
|
}
|
|
7759
|
+
for (const receipt of nodeTypeReceipts(
|
|
7760
|
+
{ entityId, operation: "ontologyBackfill", trigger: "call" },
|
|
7761
|
+
fact.id,
|
|
7762
|
+
typeof classification.okf_type === "string" ? classification.okf_type : "",
|
|
7763
|
+
normalized.okf_type,
|
|
7764
|
+
normalized.match
|
|
7765
|
+
)) {
|
|
7766
|
+
diagBuffer.push(receipt);
|
|
7767
|
+
}
|
|
7495
7768
|
if (!normalized.okf_type) {
|
|
7496
7769
|
failedValidation++;
|
|
7497
7770
|
continue;
|