@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
|
@@ -775,20 +775,40 @@ function emptyManifest() {
|
|
|
775
775
|
function normalizeTitleKey(title) {
|
|
776
776
|
return title.trim().toLowerCase().replace(/\s+/g, " ");
|
|
777
777
|
}
|
|
778
|
-
function
|
|
779
|
-
|
|
778
|
+
function normalizeSlug(raw) {
|
|
779
|
+
return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
|
|
780
|
+
}
|
|
781
|
+
function resolveNodeTypeMatch(raw, manifest) {
|
|
782
|
+
const slug = typeof raw === "string" ? raw.trim() : "";
|
|
780
783
|
if (!slug) return null;
|
|
781
|
-
const
|
|
782
|
-
|
|
784
|
+
const lowered = slug.toLowerCase();
|
|
785
|
+
const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
|
|
786
|
+
if (exact) return { slug: exact.type, via: "exact" };
|
|
787
|
+
const normalized = normalizeSlug(slug);
|
|
788
|
+
if (!normalized) return null;
|
|
789
|
+
const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
|
|
790
|
+
return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
|
|
791
|
+
}
|
|
792
|
+
function resolveNodeType(raw, manifest) {
|
|
793
|
+
return resolveNodeTypeMatch(raw, manifest)?.slug ?? null;
|
|
783
794
|
}
|
|
784
795
|
var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
|
|
785
796
|
function isReservedAbstainSlug(raw) {
|
|
786
797
|
return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
|
|
787
798
|
}
|
|
788
799
|
function resolveEdgeDefinitions(rawEdgeType, manifest) {
|
|
789
|
-
const slug = rawEdgeType.trim();
|
|
800
|
+
const slug = typeof rawEdgeType === "string" ? rawEdgeType.trim() : "";
|
|
790
801
|
if (!slug) return [];
|
|
791
|
-
|
|
802
|
+
const lowered = slug.toLowerCase();
|
|
803
|
+
const exact = manifest.edge_types.filter((e) => e.type.toLowerCase() === lowered);
|
|
804
|
+
if (exact.length > 0) return exact;
|
|
805
|
+
const normalized = normalizeSlug(slug);
|
|
806
|
+
if (!normalized) return [];
|
|
807
|
+
const names = new Set(
|
|
808
|
+
manifest.edge_types.filter((e) => normalizeSlug(e.type) === normalized).map((e) => e.type.toLowerCase())
|
|
809
|
+
);
|
|
810
|
+
if (names.size !== 1) return [];
|
|
811
|
+
return manifest.edge_types.filter((e) => e.type.toLowerCase() === [...names][0]);
|
|
792
812
|
}
|
|
793
813
|
function edgeTripleKey(type, sourceType, targetType) {
|
|
794
814
|
return `${type.trim().toLowerCase()}|${sourceType.trim().toLowerCase()}|${targetType.trim().toLowerCase()}`;
|
|
@@ -874,6 +894,7 @@ function buildDeclaresParentIndex(nodes) {
|
|
|
874
894
|
function mergeOntologyUpdates(current, updates) {
|
|
875
895
|
const node_types = [...current.node_types];
|
|
876
896
|
const edge_types = [...current.edge_types];
|
|
897
|
+
const rejected = [];
|
|
877
898
|
const nodeSlugs = new Set(node_types.map((n) => n.type.trim().toLowerCase()));
|
|
878
899
|
const edgeKeys = new Set(edge_types.map((e) => edgeTripleKey(e.type, e.source_type, e.target_type)));
|
|
879
900
|
const edgeNames = new Map(edge_types.map((e) => [e.type.trim().toLowerCase(), e.type.trim()]));
|
|
@@ -883,9 +904,15 @@ function mergeOntologyUpdates(current, updates) {
|
|
|
883
904
|
]);
|
|
884
905
|
for (const node of updates.node_types ?? []) {
|
|
885
906
|
const type = node?.type?.trim();
|
|
886
|
-
if (!type)
|
|
907
|
+
if (!type) {
|
|
908
|
+
rejected.push("invalid_shape");
|
|
909
|
+
continue;
|
|
910
|
+
}
|
|
887
911
|
const key = type.toLowerCase();
|
|
888
|
-
if (nodeSlugs.has(key))
|
|
912
|
+
if (nodeSlugs.has(key)) {
|
|
913
|
+
rejected.push("duplicate_node_type");
|
|
914
|
+
continue;
|
|
915
|
+
}
|
|
889
916
|
const rawParent = typeof node?.parent_type === "string" ? node.parent_type.trim() : "";
|
|
890
917
|
const parentSlug = rawParent.toLowerCase();
|
|
891
918
|
const keepParent = parentSlug !== "" && parentSlug !== key && declaresParent.get(parentSlug) === false;
|
|
@@ -900,11 +927,20 @@ function mergeOntologyUpdates(current, updates) {
|
|
|
900
927
|
const rawEdgeType = edge?.type?.trim();
|
|
901
928
|
const sourceType = edge?.source_type?.trim();
|
|
902
929
|
const targetType = edge?.target_type?.trim();
|
|
903
|
-
if (!rawEdgeType || !sourceType || !targetType)
|
|
930
|
+
if (!rawEdgeType || !sourceType || !targetType) {
|
|
931
|
+
rejected.push("invalid_shape");
|
|
932
|
+
continue;
|
|
933
|
+
}
|
|
904
934
|
const edgeType = edgeNames.get(rawEdgeType.toLowerCase()) ?? rawEdgeType;
|
|
905
935
|
const edgeKey = edgeTripleKey(edgeType, sourceType, targetType);
|
|
906
|
-
if (edgeKeys.has(edgeKey))
|
|
907
|
-
|
|
936
|
+
if (edgeKeys.has(edgeKey)) {
|
|
937
|
+
rejected.push("duplicate_edge");
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
if (!nodeSlugs.has(sourceType.toLowerCase()) || !nodeSlugs.has(targetType.toLowerCase())) {
|
|
941
|
+
rejected.push("unknown_endpoint");
|
|
942
|
+
continue;
|
|
943
|
+
}
|
|
908
944
|
edgeNames.set(edgeType.toLowerCase(), edgeType);
|
|
909
945
|
edge_types.push({
|
|
910
946
|
type: edgeType,
|
|
@@ -914,7 +950,7 @@ function mergeOntologyUpdates(current, updates) {
|
|
|
914
950
|
});
|
|
915
951
|
edgeKeys.add(edgeKey);
|
|
916
952
|
}
|
|
917
|
-
return { node_types, edge_types };
|
|
953
|
+
return { manifest: { node_types, edge_types }, rejected };
|
|
918
954
|
}
|
|
919
955
|
function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
|
|
920
956
|
const strict = opts?.strict === true;
|
|
@@ -1208,9 +1244,9 @@ var MetadataRepository = class extends BaseRepository {
|
|
|
1208
1244
|
mode: "emergent",
|
|
1209
1245
|
manifest: emptyManifest()
|
|
1210
1246
|
};
|
|
1211
|
-
const merged = mergeOntologyUpdates(current.manifest, updates);
|
|
1247
|
+
const { manifest: merged, rejected } = mergeOntologyUpdates(current.manifest, updates);
|
|
1212
1248
|
await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
|
|
1213
|
-
return merged;
|
|
1249
|
+
return { manifest: merged, rejected };
|
|
1214
1250
|
}
|
|
1215
1251
|
};
|
|
1216
1252
|
|
|
@@ -2245,7 +2281,8 @@ Return ONLY a valid JSON object matching this schema:
|
|
|
2245
2281
|
{
|
|
2246
2282
|
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
2247
2283
|
}
|
|
2248
|
-
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
|
|
2284
|
+
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.
|
|
2285
|
+
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.`;
|
|
2249
2286
|
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.
|
|
2250
2287
|
Return ONLY a valid JSON object matching this schema:
|
|
2251
2288
|
{
|
|
@@ -2253,7 +2290,7 @@ Return ONLY a valid JSON object matching this schema:
|
|
|
2253
2290
|
{ "id": "string (input fact id, copied verbatim)", "okf_type": "string (manifest node type slug)", "edges": [{ "edge_type": "string", "target_title": "string" }] }
|
|
2254
2291
|
]
|
|
2255
2292
|
}
|
|
2256
|
-
If no manifest type fits a fact, omit that fact from "classifications"
|
|
2293
|
+
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).
|
|
2257
2294
|
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.`;
|
|
2258
2295
|
var TITLE_CATALOG_MAX_ENTRIES = 200;
|
|
2259
2296
|
function buildTitleCatalogBlock(rows) {
|
|
@@ -2729,6 +2766,74 @@ function toGroundingAnchor(anchor) {
|
|
|
2729
2766
|
var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
|
|
2730
2767
|
var DEFAULT_CHUNK_OVERLAP = 400;
|
|
2731
2768
|
|
|
2769
|
+
// src/utils/contextCaps.ts
|
|
2770
|
+
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
2771
|
+
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
2772
|
+
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
2773
|
+
|
|
2774
|
+
// src/config/context.ts
|
|
2775
|
+
var DEFAULT_CHARS_PER_TOKEN = 4;
|
|
2776
|
+
var DEFAULT_SAFETY_FRACTION = 0.9;
|
|
2777
|
+
var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
|
|
2778
|
+
var OP_FLOOR = {
|
|
2779
|
+
resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
2780
|
+
heal: HEAL_MAX_PROMPT_CHARS,
|
|
2781
|
+
extract: OPS_MAX_EXTRACT_CHARS
|
|
2782
|
+
};
|
|
2783
|
+
function bad(key, value, why) {
|
|
2784
|
+
return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
|
|
2785
|
+
}
|
|
2786
|
+
function resolveContextBudget(config) {
|
|
2787
|
+
const context = config?.context;
|
|
2788
|
+
if (!context || context.budget === void 0) {
|
|
2789
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
2790
|
+
}
|
|
2791
|
+
if (context.budget !== "legacy" && context.budget !== "declared") {
|
|
2792
|
+
throw bad("budget", context.budget, "'legacy' or 'declared'");
|
|
2793
|
+
}
|
|
2794
|
+
if (context.budget === "legacy") {
|
|
2795
|
+
return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
|
|
2796
|
+
}
|
|
2797
|
+
const window = context.contextWindowTokens;
|
|
2798
|
+
if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
|
|
2799
|
+
throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
|
|
2800
|
+
}
|
|
2801
|
+
const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
|
|
2802
|
+
if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
|
|
2803
|
+
throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
|
|
2804
|
+
}
|
|
2805
|
+
const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
|
|
2806
|
+
if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
|
|
2807
|
+
throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
|
|
2808
|
+
}
|
|
2809
|
+
const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
|
|
2810
|
+
if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
|
|
2811
|
+
throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
|
|
2812
|
+
}
|
|
2813
|
+
return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
|
|
2814
|
+
}
|
|
2815
|
+
function declaredPromptCap(budget, op) {
|
|
2816
|
+
const derived = Math.floor(
|
|
2817
|
+
(budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
|
|
2818
|
+
);
|
|
2819
|
+
if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
|
|
2820
|
+
return Math.max(OP_FLOOR.heal, derived);
|
|
2821
|
+
}
|
|
2822
|
+
function resolveMaxPromptChars(budget, op) {
|
|
2823
|
+
if (budget.mode !== "declared") {
|
|
2824
|
+
return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
|
|
2825
|
+
}
|
|
2826
|
+
if (op === "extract") {
|
|
2827
|
+
const resolveDerived = declaredPromptCap(budget, "resolve");
|
|
2828
|
+
const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
|
|
2829
|
+
return Math.max(OP_FLOOR.extract, extractDerived);
|
|
2830
|
+
}
|
|
2831
|
+
return declaredPromptCap(budget, op);
|
|
2832
|
+
}
|
|
2833
|
+
function resolveDefaultChunkLength(budget) {
|
|
2834
|
+
return DEFAULT_MAX_CHUNK_LENGTH;
|
|
2835
|
+
}
|
|
2836
|
+
|
|
2732
2837
|
// src/utils/diagnostics.ts
|
|
2733
2838
|
var SEVERITY = {
|
|
2734
2839
|
ingest_chunk_failed: "warn",
|
|
@@ -2777,7 +2882,11 @@ var SEVERITY = {
|
|
|
2777
2882
|
source_store_budget_exceeded: "warn",
|
|
2778
2883
|
source_store_hash_mismatch: "warn",
|
|
2779
2884
|
source_store_duplicate_hash: "warn",
|
|
2780
|
-
source_store_text_not_storable: "warn"
|
|
2885
|
+
source_store_text_not_storable: "warn",
|
|
2886
|
+
node_type_dropped: "warn",
|
|
2887
|
+
node_type_folded: "info",
|
|
2888
|
+
ontology_update_rejected: "warn",
|
|
2889
|
+
ingest_zero_facts: "warn"
|
|
2781
2890
|
};
|
|
2782
2891
|
var MESSAGE = {
|
|
2783
2892
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -2826,8 +2935,48 @@ var MESSAGE = {
|
|
|
2826
2935
|
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
2827
2936
|
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
2828
2937
|
source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
|
|
2829
|
-
source_store_text_not_storable: "A source document text could not be stored as given."
|
|
2938
|
+
source_store_text_not_storable: "A source document text could not be stored as given.",
|
|
2939
|
+
node_type_dropped: "A supplied node type missed the ontology manifest and the fact was stored untyped.",
|
|
2940
|
+
node_type_folded: "A supplied node type was normalized into the manifest canonical slug.",
|
|
2941
|
+
ontology_update_rejected: "An emergent ontology proposal was rejected during the merge.",
|
|
2942
|
+
ingest_zero_facts: "A re-ingest tombstoned prior facts and edges and then wrote zero facts."
|
|
2830
2943
|
};
|
|
2944
|
+
function shouldEmitOntologyReceipt(mode) {
|
|
2945
|
+
return mode !== "off";
|
|
2946
|
+
}
|
|
2947
|
+
function capReceiptSlug(slug) {
|
|
2948
|
+
return typeof slug === "string" ? slug.slice(0, 64) : "";
|
|
2949
|
+
}
|
|
2950
|
+
function nodeTypeReceipts(base, factId, rawType, okfType, match) {
|
|
2951
|
+
const out = [];
|
|
2952
|
+
const supplied = typeof rawType === "string" ? rawType.trim() : "";
|
|
2953
|
+
if (match && match.via === "normalize") {
|
|
2954
|
+
const to = capReceiptSlug(match.canonical);
|
|
2955
|
+
out.push({
|
|
2956
|
+
...base,
|
|
2957
|
+
code: "node_type_folded",
|
|
2958
|
+
detail: {
|
|
2959
|
+
factId,
|
|
2960
|
+
nodeType: to,
|
|
2961
|
+
from: capReceiptSlug(match.raw),
|
|
2962
|
+
to,
|
|
2963
|
+
via: "normalize"
|
|
2964
|
+
}
|
|
2965
|
+
});
|
|
2966
|
+
}
|
|
2967
|
+
if (!okfType && supplied) {
|
|
2968
|
+
out.push({
|
|
2969
|
+
...base,
|
|
2970
|
+
code: "node_type_dropped",
|
|
2971
|
+
detail: {
|
|
2972
|
+
factId,
|
|
2973
|
+
nodeType: capReceiptSlug(supplied),
|
|
2974
|
+
reason: "not_in_manifest"
|
|
2975
|
+
}
|
|
2976
|
+
});
|
|
2977
|
+
}
|
|
2978
|
+
return out;
|
|
2979
|
+
}
|
|
2831
2980
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
2832
2981
|
function copyDetail(detail) {
|
|
2833
2982
|
const copy = { ...detail };
|
|
@@ -3052,7 +3201,7 @@ var IngestionService = class {
|
|
|
3052
3201
|
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
3053
3202
|
const sourceHash = normalizeSourceHash(params.sourceHash);
|
|
3054
3203
|
if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
|
|
3055
|
-
const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ??
|
|
3204
|
+
const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
|
|
3056
3205
|
const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
|
|
3057
3206
|
const chunkOverlap = Math.min(
|
|
3058
3207
|
Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
|
|
@@ -3242,6 +3391,15 @@ var IngestionService = class {
|
|
|
3242
3391
|
});
|
|
3243
3392
|
deletedSourceFactIds.push(...fullResult.deletedSourceFactIds);
|
|
3244
3393
|
insertedFacts.push(...fullResult.insertedFacts);
|
|
3394
|
+
if (ontologyContext !== null && insertedFacts.length === 0 && deletedSourceFactIds.length > 0) {
|
|
3395
|
+
diagBuffer.push({
|
|
3396
|
+
entityId,
|
|
3397
|
+
operation: "ingest",
|
|
3398
|
+
trigger: "call",
|
|
3399
|
+
code: "ingest_zero_facts",
|
|
3400
|
+
detail: { sourceRef, chunks: chunks2.length }
|
|
3401
|
+
});
|
|
3402
|
+
}
|
|
3245
3403
|
} else {
|
|
3246
3404
|
const partialResult = await this.db.withTransactionAsync(async (tx) => {
|
|
3247
3405
|
const flat = [];
|
|
@@ -3379,6 +3537,20 @@ var IngestionService = class {
|
|
|
3379
3537
|
strict: strictEffective,
|
|
3380
3538
|
entityId
|
|
3381
3539
|
}) ?? { okf_type: null};
|
|
3540
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
3541
|
+
for (const receipt of nodeTypeReceipts(
|
|
3542
|
+
{ entityId, operation: opts?.diag?.operation ?? "upsertGraph", trigger: "call" },
|
|
3543
|
+
node.id,
|
|
3544
|
+
node.type ?? "",
|
|
3545
|
+
normalized.okf_type,
|
|
3546
|
+
normalized.match
|
|
3547
|
+
)) {
|
|
3548
|
+
opts?.diag?.buffer.push({
|
|
3549
|
+
...receipt,
|
|
3550
|
+
detail: { ...receipt.detail, sourceRef: params.sourceRef }
|
|
3551
|
+
});
|
|
3552
|
+
}
|
|
3553
|
+
}
|
|
3382
3554
|
const wikiFact = {
|
|
3383
3555
|
id: node.id,
|
|
3384
3556
|
entity_id: entityId,
|
|
@@ -3433,8 +3605,8 @@ var IngestionService = class {
|
|
|
3433
3605
|
continue;
|
|
3434
3606
|
}
|
|
3435
3607
|
const sourceType = sourceIdToType.get(edge.sourceId);
|
|
3436
|
-
const candidates = (
|
|
3437
|
-
(d) =>
|
|
3608
|
+
const candidates = resolveEdgeDefinitions(edge.type, manifest).filter(
|
|
3609
|
+
(d) => typeSatisfies(d.source_type, sourceType ?? "", manifest)
|
|
3438
3610
|
);
|
|
3439
3611
|
const match = candidates[0];
|
|
3440
3612
|
if (!match) {
|
|
@@ -3513,9 +3685,18 @@ var IngestionService = class {
|
|
|
3513
3685
|
const now = Date.now();
|
|
3514
3686
|
for (const { facts, ontology_updates } of orderedChunkFacts) {
|
|
3515
3687
|
if (mode === "emergent" && ontology_updates && this.ontologyService) {
|
|
3516
|
-
manifest = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
|
|
3688
|
+
const { manifest: merged, rejected } = await this.ontologyService.mergeEmergentUpdates(entityId, ontology_updates, tx);
|
|
3689
|
+
manifest = merged;
|
|
3690
|
+
for (const reason of rejected) {
|
|
3691
|
+
diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason } });
|
|
3692
|
+
}
|
|
3517
3693
|
ontologyState = await this.ontologyService.getEffectiveState(entityId, tx);
|
|
3518
3694
|
mode = ontologyState.mode;
|
|
3695
|
+
} else if (mode === "strict" && ontology_updates) {
|
|
3696
|
+
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);
|
|
3697
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
3698
|
+
diagBuffer.push({ entityId, operation: "ingest", trigger: "call", code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
3699
|
+
}
|
|
3519
3700
|
}
|
|
3520
3701
|
for (const fact of facts) {
|
|
3521
3702
|
const ontologyFact = fact;
|
|
@@ -3613,6 +3794,14 @@ var IngestionService = class {
|
|
|
3613
3794
|
const liveIds = await this.entryRepo.findIdsBySource(entityId, sourceRef, null, tx, false);
|
|
3614
3795
|
const liveFacts = liveIds.length === 0 ? [] : await this.entryRepo.findByIds(liveIds, void 0, tx);
|
|
3615
3796
|
const liveTitles = new Set(liveFacts.map((f) => normalizeTitleKey(f.title)));
|
|
3797
|
+
const ontologyState = await this.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
3798
|
+
const { mode, manifest } = ontologyState;
|
|
3799
|
+
const titleIndex = /* @__PURE__ */ new Map();
|
|
3800
|
+
const indexedFacts = await this.entryRepo.findRecentByEntityId(entityId, 500, tx);
|
|
3801
|
+
for (const f of indexedFacts) {
|
|
3802
|
+
titleIndex.set(normalizeTitleKey(f.title), { id: f.id, okf_type: f.okf_type ?? null });
|
|
3803
|
+
}
|
|
3804
|
+
const pendingEdges = [];
|
|
3616
3805
|
let inserted = 0;
|
|
3617
3806
|
let skippedDuplicate = 0;
|
|
3618
3807
|
const now = Date.now();
|
|
@@ -3637,6 +3826,26 @@ var IngestionService = class {
|
|
|
3637
3826
|
detail: { factId: id, sourceRef, chunkIndex: locator.chunkIndex, itemIndex: locator.itemIndex, reason: outcome.diagnostic.reason }
|
|
3638
3827
|
});
|
|
3639
3828
|
}
|
|
3829
|
+
const ontologyFact = fact;
|
|
3830
|
+
const validationDrops = [];
|
|
3831
|
+
const normalized = this.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
|
|
3832
|
+
for (const drop of validationDrops) {
|
|
3833
|
+
diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef, factId: id }));
|
|
3834
|
+
}
|
|
3835
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
3836
|
+
for (const receipt of nodeTypeReceipts(
|
|
3837
|
+
{ entityId, operation: "ingest", trigger: "call" },
|
|
3838
|
+
id,
|
|
3839
|
+
ontologyFact.okf_type ?? "",
|
|
3840
|
+
normalized.okf_type,
|
|
3841
|
+
normalized.match
|
|
3842
|
+
)) {
|
|
3843
|
+
diagBuffer.push({ ...receipt, detail: { ...receipt.detail, sourceRef } });
|
|
3844
|
+
}
|
|
3845
|
+
}
|
|
3846
|
+
if (normalized.edges.length > 0) {
|
|
3847
|
+
pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
|
|
3848
|
+
}
|
|
3640
3849
|
const wikiFact = {
|
|
3641
3850
|
id,
|
|
3642
3851
|
entity_id: entityId,
|
|
@@ -3655,10 +3864,11 @@ var IngestionService = class {
|
|
|
3655
3864
|
last_accessed_at: null,
|
|
3656
3865
|
access_count: 0,
|
|
3657
3866
|
deleted_at: null,
|
|
3658
|
-
okf_type:
|
|
3867
|
+
okf_type: normalized.okf_type,
|
|
3659
3868
|
...outcome?.trust
|
|
3660
3869
|
};
|
|
3661
3870
|
await this.entryRepo.upsert(wikiFact, tx);
|
|
3871
|
+
titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
|
|
3662
3872
|
insertedDescriptors.push({
|
|
3663
3873
|
id,
|
|
3664
3874
|
entity_id: entityId,
|
|
@@ -3668,6 +3878,27 @@ var IngestionService = class {
|
|
|
3668
3878
|
});
|
|
3669
3879
|
inserted++;
|
|
3670
3880
|
}
|
|
3881
|
+
if (pendingEdges.length > 0) {
|
|
3882
|
+
for (const req of pendingEdges) {
|
|
3883
|
+
const resolveDrops = [];
|
|
3884
|
+
const resolved = this.ontologyService?.resolveEdges(
|
|
3885
|
+
entityId,
|
|
3886
|
+
req.sourceId,
|
|
3887
|
+
req.sourceType,
|
|
3888
|
+
req.edges,
|
|
3889
|
+
manifest,
|
|
3890
|
+
titleIndex,
|
|
3891
|
+
now,
|
|
3892
|
+
resolveDrops
|
|
3893
|
+
) ?? [];
|
|
3894
|
+
for (const drop of resolveDrops) {
|
|
3895
|
+
diagBuffer.push(edgeDropDiagnostic(drop, { entityId, operation: "ingest", trigger: "call", sourceRef }));
|
|
3896
|
+
}
|
|
3897
|
+
for (const edge of resolved) {
|
|
3898
|
+
await this.edgeRepo.addIgnoreDuplicate(edge, tx);
|
|
3899
|
+
}
|
|
3900
|
+
}
|
|
3901
|
+
}
|
|
3671
3902
|
return { inserted, skippedDuplicate, insertedDescriptors };
|
|
3672
3903
|
}
|
|
3673
3904
|
};
|
|
@@ -3681,6 +3912,9 @@ function resolveLibrarianStrategy(config) {
|
|
|
3681
3912
|
function resolveMaintenanceMode(config) {
|
|
3682
3913
|
return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
|
|
3683
3914
|
}
|
|
3915
|
+
function resolveContextBudgetOrThrow(config) {
|
|
3916
|
+
return resolveContextBudget(config);
|
|
3917
|
+
}
|
|
3684
3918
|
function changedDefaultWarnings(config) {
|
|
3685
3919
|
const warnings = [];
|
|
3686
3920
|
const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
|
|
@@ -5893,7 +6127,16 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5893
6127
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
5894
6128
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
5895
6129
|
if (mode === "emergent" && ontologyUpdates && deps.ontologyService) {
|
|
5896
|
-
manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
6130
|
+
const { manifest: merged, rejected } = await deps.ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
6131
|
+
manifest = merged;
|
|
6132
|
+
for (const reason of rejected) {
|
|
6133
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
6134
|
+
}
|
|
6135
|
+
} else if (mode === "strict" && ontologyUpdates) {
|
|
6136
|
+
const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
|
|
6137
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
6138
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
6139
|
+
}
|
|
5897
6140
|
}
|
|
5898
6141
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
5899
6142
|
for (const existing of currentFactsRows) {
|
|
@@ -5928,6 +6171,17 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5928
6171
|
const validationDrops = [];
|
|
5929
6172
|
const normalized = deps.ontologyService?.validateAndNormalizeFact(ontologyFact, manifest, { strict: false, drops: validationDrops }) ?? { okf_type: null, edges: [] };
|
|
5930
6173
|
for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
|
|
6174
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
6175
|
+
for (const receipt of nodeTypeReceipts(
|
|
6176
|
+
{ entityId, operation: "librarian", trigger },
|
|
6177
|
+
id,
|
|
6178
|
+
ontologyFact.okf_type ?? "",
|
|
6179
|
+
normalized.okf_type,
|
|
6180
|
+
normalized.match
|
|
6181
|
+
)) {
|
|
6182
|
+
diagBuffer.push(receipt);
|
|
6183
|
+
}
|
|
6184
|
+
}
|
|
5931
6185
|
const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
|
|
5932
6186
|
if (grounding?.diagnostic) {
|
|
5933
6187
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
@@ -6030,18 +6284,18 @@ function parseValidFrom(v) {
|
|
|
6030
6284
|
|
|
6031
6285
|
// src/services/librarian/ops/extract.ts
|
|
6032
6286
|
var OPS_MAX_EVENTS_PER_PASS = 50;
|
|
6033
|
-
var OPS_MAX_EXTRACT_CHARS = 24e3;
|
|
6034
6287
|
var RESOLVE_RESERVE_FACTOR = 2;
|
|
6035
6288
|
var MIN_SEGMENT_CHARS = 500;
|
|
6036
6289
|
var MAX_SEGMENT_CALLS = 8;
|
|
6037
6290
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
6038
|
-
async function selectBatch(deps, entityId, wm, meter, guidance) {
|
|
6291
|
+
async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
6039
6292
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
6040
6293
|
if (events.length === 0) return { batch: [] };
|
|
6294
|
+
const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
|
|
6041
6295
|
let n = 0;
|
|
6042
6296
|
let chars = 0;
|
|
6043
6297
|
for (const e of events) {
|
|
6044
|
-
if (n > 0 && chars + e.summary.length >
|
|
6298
|
+
if (n > 0 && chars + e.summary.length > extractCap) break;
|
|
6045
6299
|
chars += e.summary.length;
|
|
6046
6300
|
n++;
|
|
6047
6301
|
}
|
|
@@ -6367,7 +6621,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
|
|
|
6367
6621
|
}
|
|
6368
6622
|
|
|
6369
6623
|
// src/services/librarian/ops/resolve.ts
|
|
6370
|
-
var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
|
|
6371
6624
|
function validateOp(raw, aliases) {
|
|
6372
6625
|
if (!raw || typeof raw !== "object") return null;
|
|
6373
6626
|
const r = raw;
|
|
@@ -6386,7 +6639,7 @@ function validateOp(raw, aliases) {
|
|
|
6386
6639
|
return update;
|
|
6387
6640
|
}
|
|
6388
6641
|
var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
|
|
6389
|
-
async function runResolve(deps, ctx, ambiguous) {
|
|
6642
|
+
async function runResolve(deps, ctx, ambiguous, budget) {
|
|
6390
6643
|
const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
|
|
6391
6644
|
if (ambiguous.length === 0) return out;
|
|
6392
6645
|
const { entityId, trigger } = ctx;
|
|
@@ -6412,7 +6665,7 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
6412
6665
|
onSkip: (g, err) => {
|
|
6413
6666
|
if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
|
|
6414
6667
|
},
|
|
6415
|
-
maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
6668
|
+
maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
|
|
6416
6669
|
maxOutputTokens: deps.options.llmProvider.maxOutputTokens
|
|
6417
6670
|
});
|
|
6418
6671
|
if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
|
|
@@ -6462,7 +6715,16 @@ async function applyOps(deps, ctx, input) {
|
|
|
6462
6715
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
6463
6716
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
6464
6717
|
if (mode === "emergent" && input.ontologyUpdates && deps.ontologyService) {
|
|
6465
|
-
manifest = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
|
|
6718
|
+
const { manifest: merged, rejected: rejected2 } = await deps.ontologyService.mergeEmergentUpdates(entityId, input.ontologyUpdates, tx);
|
|
6719
|
+
manifest = merged;
|
|
6720
|
+
for (const reason of rejected2) {
|
|
6721
|
+
input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
6722
|
+
}
|
|
6723
|
+
} else if (mode === "strict" && input.ontologyUpdates) {
|
|
6724
|
+
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);
|
|
6725
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
6726
|
+
input.diagnostics.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
6727
|
+
}
|
|
6466
6728
|
}
|
|
6467
6729
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
6468
6730
|
for (const f of await deps.entryRepo.findRecentByEntityId(entityId, 100, tx)) {
|
|
@@ -6476,6 +6738,17 @@ async function applyOps(deps, ctx, input) {
|
|
|
6476
6738
|
const id = generateId("fact_");
|
|
6477
6739
|
const drops = [];
|
|
6478
6740
|
const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
|
|
6741
|
+
if (shouldEmitOntologyReceipt(mode)) {
|
|
6742
|
+
for (const receipt of nodeTypeReceipts(
|
|
6743
|
+
{ entityId, operation: "librarian", trigger },
|
|
6744
|
+
id,
|
|
6745
|
+
typeof fact.okf_type === "string" ? fact.okf_type : "",
|
|
6746
|
+
normalized.okf_type,
|
|
6747
|
+
normalized.match
|
|
6748
|
+
)) {
|
|
6749
|
+
input.diagnostics.push(receipt);
|
|
6750
|
+
}
|
|
6751
|
+
}
|
|
6479
6752
|
for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
|
|
6480
6753
|
const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
|
|
6481
6754
|
const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
|
|
@@ -6621,7 +6894,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
6621
6894
|
const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
|
|
6622
6895
|
await deps.seedWatermark(entityId);
|
|
6623
6896
|
const wm = await deps.getWatermark(entityId);
|
|
6624
|
-
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
|
|
6897
|
+
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
|
|
6625
6898
|
if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
|
|
6626
6899
|
if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
|
|
6627
6900
|
if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
|
|
@@ -6649,7 +6922,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
6649
6922
|
});
|
|
6650
6923
|
}
|
|
6651
6924
|
diagnostics.push(gateDiagnostic);
|
|
6652
|
-
const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
|
|
6925
|
+
const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
|
|
6653
6926
|
for (const itemIndex of res.overflowSkipped) {
|
|
6654
6927
|
diagnostics.push({
|
|
6655
6928
|
entityId,
|
|
@@ -6718,7 +6991,6 @@ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
|
|
|
6718
6991
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
6719
6992
|
var CLASSIFIER_MAX_CHOICES = 255;
|
|
6720
6993
|
var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
|
|
6721
|
-
var HEAL_MAX_PROMPT_CHARS = 4e4;
|
|
6722
6994
|
var HEAL_BATCH_SIZE = 25;
|
|
6723
6995
|
var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
6724
6996
|
var MAX_EMBED_ATTEMPTS = 5;
|
|
@@ -8022,7 +8294,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8022
8294
|
};
|
|
8023
8295
|
},
|
|
8024
8296
|
maxOutputTokens: this.options.llmProvider.maxOutputTokens,
|
|
8025
|
-
maxPromptChars:
|
|
8297
|
+
maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
|
|
8026
8298
|
// heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
|
|
8027
8299
|
supportsEscalation: true,
|
|
8028
8300
|
onSkip: (fact, err) => {
|
|
@@ -8185,12 +8457,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8185
8457
|
if (!Number.isInteger(batchSize) || batchSize < 1) {
|
|
8186
8458
|
throw new Error("Invalid batchSize: must be an integer >= 1");
|
|
8187
8459
|
}
|
|
8460
|
+
if (options?.recheckCheckedBefore !== void 0 && (!Number.isInteger(options.recheckCheckedBefore) || options.recheckCheckedBefore < 0)) {
|
|
8461
|
+
throw new Error("Invalid recheckCheckedBefore: must be an integer >= 0");
|
|
8462
|
+
}
|
|
8188
8463
|
if (options?.classifier !== void 0 && options.classifier !== "auto" && options.classifier !== "llm") {
|
|
8189
8464
|
throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
|
|
8190
8465
|
}
|
|
8191
8466
|
const trigger = options?.trigger ?? "call";
|
|
8192
8467
|
const now = Date.now();
|
|
8193
|
-
const recheckCutoff = now - ONTOLOGY_BACKFILL_RECHECK_MS;
|
|
8468
|
+
const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
|
|
8194
8469
|
const zeroed = { scanned: 0, typed: 0, failedValidation: 0, edgesAdded: 0, skipped: 0, abstained: 0 };
|
|
8195
8470
|
const ontologyService = this.ontologyService;
|
|
8196
8471
|
if (!ontologyService) {
|
|
@@ -8234,7 +8509,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8234
8509
|
promptOverride: options?.promptOverride,
|
|
8235
8510
|
meter: options?.meter,
|
|
8236
8511
|
trigger,
|
|
8237
|
-
batchSize: escalated.length
|
|
8512
|
+
batchSize: escalated.length,
|
|
8513
|
+
recheckCutoff
|
|
8238
8514
|
});
|
|
8239
8515
|
return {
|
|
8240
8516
|
scanned: classifierRun.result.scanned,
|
|
@@ -8254,7 +8530,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8254
8530
|
return this._runGenerativeBackfill(entityId, candidates, {
|
|
8255
8531
|
promptOverride: options?.promptOverride,
|
|
8256
8532
|
meter: options?.meter,
|
|
8257
|
-
trigger
|
|
8533
|
+
trigger,
|
|
8534
|
+
recheckCutoff
|
|
8258
8535
|
});
|
|
8259
8536
|
}
|
|
8260
8537
|
/**
|
|
@@ -8284,7 +8561,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8284
8561
|
runOpts.batchSize ?? ONTOLOGY_BACKFILL_BATCH_SIZE;
|
|
8285
8562
|
const ontologyService = this.ontologyService;
|
|
8286
8563
|
const now = Date.now();
|
|
8287
|
-
const recheckCutoff =
|
|
8564
|
+
const recheckCutoff = runOpts.recheckCutoff;
|
|
8288
8565
|
const ontologyContext = await ontologyService.buildPromptContext(entityId);
|
|
8289
8566
|
const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId);
|
|
8290
8567
|
const titleCatalog = buildTitleCatalogBlock(titleRows);
|
|
@@ -8536,7 +8813,16 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8536
8813
|
return;
|
|
8537
8814
|
}
|
|
8538
8815
|
if (txMode === "emergent" && ontologyUpdates) {
|
|
8539
|
-
manifest = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
8816
|
+
const { manifest: merged, rejected } = await ontologyService.mergeEmergentUpdates(entityId, ontologyUpdates, tx);
|
|
8817
|
+
manifest = merged;
|
|
8818
|
+
for (const reason of rejected) {
|
|
8819
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason } });
|
|
8820
|
+
}
|
|
8821
|
+
} else if (txMode === "strict" && ontologyUpdates) {
|
|
8822
|
+
const proposalCount = (Array.isArray(ontologyUpdates.node_types) ? ontologyUpdates.node_types.length : 0) + (Array.isArray(ontologyUpdates.edge_types) ? ontologyUpdates.edge_types.length : 0);
|
|
8823
|
+
for (let i = 0; i < proposalCount; i++) {
|
|
8824
|
+
diagBuffer.push({ ...diagBase, code: "ontology_update_rejected", detail: { reason: "mode_strict" } });
|
|
8825
|
+
}
|
|
8540
8826
|
}
|
|
8541
8827
|
const titleRows = await this.entryRepo.findTitleIndexByEntityId(entityId, tx);
|
|
8542
8828
|
const titleIndex = /* @__PURE__ */ new Map();
|
|
@@ -8570,6 +8856,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
8570
8856
|
for (const drop of validationDrops) {
|
|
8571
8857
|
diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: fact.id }));
|
|
8572
8858
|
}
|
|
8859
|
+
for (const receipt of nodeTypeReceipts(
|
|
8860
|
+
{ entityId, operation: "ontologyBackfill", trigger: "call" },
|
|
8861
|
+
fact.id,
|
|
8862
|
+
typeof classification.okf_type === "string" ? classification.okf_type : "",
|
|
8863
|
+
normalized.okf_type,
|
|
8864
|
+
normalized.match
|
|
8865
|
+
)) {
|
|
8866
|
+
diagBuffer.push(receipt);
|
|
8867
|
+
}
|
|
8573
8868
|
if (!normalized.okf_type) {
|
|
8574
8869
|
failedValidation++;
|
|
8575
8870
|
continue;
|
|
@@ -11254,6 +11549,6 @@ var WriteService = class {
|
|
|
11254
11549
|
}
|
|
11255
11550
|
};
|
|
11256
11551
|
|
|
11257
|
-
export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
11258
|
-
//# sourceMappingURL=chunk-
|
|
11259
|
-
//# sourceMappingURL=chunk-
|
|
11552
|
+
export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
11553
|
+
//# sourceMappingURL=chunk-EN37KODZ.mjs.map
|
|
11554
|
+
//# sourceMappingURL=chunk-EN37KODZ.mjs.map
|