@equationalapplications/core-llm-wiki 9.14.1 → 9.15.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-JCMA74YK.mjs} +3382 -3159
- package/dist/chunk-JCMA74YK.mjs.map +1 -0
- package/dist/index.d.mts +10 -3
- package/dist/index.d.ts +10 -3
- package/dist/index.js +1220 -949
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +53 -6
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BclOvn3q.d.mts → testing-ziEQOLjo.d.mts} +97 -29
- package/dist/{testing-BclOvn3q.d.ts → testing-ziEQOLjo.d.ts} +97 -29
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +295 -61
- 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/testing.js
CHANGED
|
@@ -733,6 +733,8 @@ var SEVERITY = {
|
|
|
733
733
|
llm_usage: "info",
|
|
734
734
|
librarian_gate: "info",
|
|
735
735
|
librarian_op_rejected: "warn",
|
|
736
|
+
librarian_rewritten: "info",
|
|
737
|
+
librarian_superseded: "info",
|
|
736
738
|
contradicts_document: "warn",
|
|
737
739
|
resolve_failed: "warn",
|
|
738
740
|
read_budget: "info",
|
|
@@ -788,6 +790,8 @@ var MESSAGE = {
|
|
|
788
790
|
llm_usage: "An LLM call completed; token usage attached.",
|
|
789
791
|
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
790
792
|
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
793
|
+
librarian_rewritten: "The librarian rewrote an engine-inferred fact in place; the previous text was not kept.",
|
|
794
|
+
librarian_superseded: "The librarian ended a fact\u2019s validity with a replacement fact.",
|
|
791
795
|
contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
|
|
792
796
|
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
793
797
|
read_budget: "A read was packed to a token budget.",
|
|
@@ -1321,6 +1325,17 @@ function normalizeTitleKey(title) {
|
|
|
1321
1325
|
function normalizeSlug(raw) {
|
|
1322
1326
|
return raw.trim().toLowerCase().replace(/[_\-\s]+/g, "");
|
|
1323
1327
|
}
|
|
1328
|
+
function resolveNodeTypeMatch(raw, manifest) {
|
|
1329
|
+
const slug = typeof raw === "string" ? raw.trim() : "";
|
|
1330
|
+
if (!slug) return null;
|
|
1331
|
+
const lowered = slug.toLowerCase();
|
|
1332
|
+
const exact = manifest.node_types.find((n) => n.type.toLowerCase() === lowered);
|
|
1333
|
+
if (exact) return { slug: exact.type, via: "exact" };
|
|
1334
|
+
const normalized = normalizeSlug(slug);
|
|
1335
|
+
if (!normalized) return null;
|
|
1336
|
+
const candidates = manifest.node_types.filter((n) => normalizeSlug(n.type) === normalized);
|
|
1337
|
+
return candidates.length === 1 ? { slug: candidates[0].type, via: "normalize" } : null;
|
|
1338
|
+
}
|
|
1324
1339
|
var ONTOLOGY_ABSTAIN_SENTINEL = "none_of_these";
|
|
1325
1340
|
function isReservedAbstainSlug(raw) {
|
|
1326
1341
|
return typeof raw === "string" && raw.trim().toLowerCase() === ONTOLOGY_ABSTAIN_SENTINEL;
|
|
@@ -2710,16 +2725,36 @@ ${guidanceSection(guidance)}`;
|
|
|
2710
2725
|
} while (out !== prev);
|
|
2711
2726
|
return out;
|
|
2712
2727
|
}
|
|
2713
|
-
|
|
2728
|
+
/** Write-site variant (ingest, librarian, ops extract). Body identical to the backfill variant by design (specs/type-on-write §5). */
|
|
2729
|
+
buildWriteSystemPrompt(template, variables, ontologyContext) {
|
|
2730
|
+
const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
|
|
2731
|
+
const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
|
|
2732
|
+
const shouldHydrate = Object.keys(variables).some(
|
|
2733
|
+
(key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
|
|
2734
|
+
) || ontologyContext != null && hasOntologyPlaceholders;
|
|
2735
|
+
const hydrated = shouldHydrate ? this.hydrate(effective, {
|
|
2736
|
+
...variables,
|
|
2737
|
+
...ontologyContext ? { ontologyManifest: ontologyContext.ontologyManifest, ontologyModeInstructions: ontologyContext.ontologyModeInstructions } : {}
|
|
2738
|
+
}) : effective;
|
|
2739
|
+
return hasOntologyPlaceholders ? hydrated : this.appendWriteOntology(hydrated, ontologyContext);
|
|
2740
|
+
}
|
|
2741
|
+
appendWriteOntology(systemPrompt, ctx) {
|
|
2742
|
+
if (!ctx) return systemPrompt;
|
|
2743
|
+
return `${systemPrompt}
|
|
2744
|
+
|
|
2745
|
+
${ctx.ontologyModeInstructions}`;
|
|
2746
|
+
}
|
|
2747
|
+
/** Backfill-site variant. Body identical to the write variant by design (specs/type-on-write §5). */
|
|
2748
|
+
buildBackfillSystemPrompt(template, variables, ontologyContext) {
|
|
2714
2749
|
const hasOntologyPlaceholders = this.hasOntologyPlaceholders(template);
|
|
2715
2750
|
const effective = hasOntologyPlaceholders && ontologyContext == null ? this.stripOntologyPlaceholders(template) : template;
|
|
2716
2751
|
const shouldHydrate = Object.keys(variables).some(
|
|
2717
2752
|
(key) => new RegExp(`\\{\\{\\s*${key}\\s*\\}\\}`).test(effective)
|
|
2718
2753
|
) || ontologyContext != null && hasOntologyPlaceholders;
|
|
2719
2754
|
const hydrated = shouldHydrate ? this.hydrate(effective, { ...variables, ...ontologyContext ?? {} }) : effective;
|
|
2720
|
-
return hasOntologyPlaceholders ? hydrated : this.
|
|
2755
|
+
return hasOntologyPlaceholders ? hydrated : this.appendBackfillOntology(hydrated, ontologyContext);
|
|
2721
2756
|
}
|
|
2722
|
-
|
|
2757
|
+
appendBackfillOntology(systemPrompt, ctx) {
|
|
2723
2758
|
if (!ctx) return systemPrompt;
|
|
2724
2759
|
return `${systemPrompt}
|
|
2725
2760
|
|
|
@@ -2730,13 +2765,13 @@ ${ctx.ontologyModeInstructions}`;
|
|
|
2730
2765
|
const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
|
|
2731
2766
|
if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
|
|
2732
2767
|
return {
|
|
2733
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
2768
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
|
|
2734
2769
|
userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
|
|
2735
2770
|
${documentChunk}`
|
|
2736
2771
|
};
|
|
2737
2772
|
}
|
|
2738
2773
|
return {
|
|
2739
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
2774
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "ingest"),
|
|
2740
2775
|
userPrompt: `Document Chunk:
|
|
2741
2776
|
${documentChunk}`
|
|
2742
2777
|
};
|
|
@@ -2749,7 +2784,7 @@ ${documentChunk}`
|
|
|
2749
2784
|
const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
|
|
2750
2785
|
if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
|
|
2751
2786
|
return {
|
|
2752
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
2787
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
|
|
2753
2788
|
userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
|
|
2754
2789
|
${JSON.stringify(events, null, 2)}
|
|
2755
2790
|
|
|
@@ -2759,7 +2794,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
|
|
|
2759
2794
|
};
|
|
2760
2795
|
}
|
|
2761
2796
|
return {
|
|
2762
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
2797
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(template, ontologyContext), guidance), "librarian"),
|
|
2763
2798
|
userPrompt: `Events:
|
|
2764
2799
|
${JSON.stringify(events, null, 2)}
|
|
2765
2800
|
|
|
@@ -2850,7 +2885,7 @@ The following document anchors are provided for contradiction detection only. Do
|
|
|
2850
2885
|
const hasFacts = /\{\{\s*facts\s*\}\}/.test(template);
|
|
2851
2886
|
if (hasFacts || this.hasOntologyPlaceholders(template)) {
|
|
2852
2887
|
return {
|
|
2853
|
-
systemPrompt: this.
|
|
2888
|
+
systemPrompt: this.buildBackfillSystemPrompt(template, { facts }, ontologyContext),
|
|
2854
2889
|
userPrompt: hasFacts ? "Please classify the facts." : `Facts:
|
|
2855
2890
|
${JSON.stringify(facts, null, 2)}`
|
|
2856
2891
|
};
|
|
@@ -2858,7 +2893,7 @@ ${JSON.stringify(facts, null, 2)}`
|
|
|
2858
2893
|
const factsBlock = `Facts:
|
|
2859
2894
|
${JSON.stringify(facts, null, 2)}`;
|
|
2860
2895
|
return {
|
|
2861
|
-
systemPrompt: this.
|
|
2896
|
+
systemPrompt: this.appendBackfillOntology(template, ontologyContext),
|
|
2862
2897
|
userPrompt: candidateSections !== void 0 ? `${factsBlock}
|
|
2863
2898
|
|
|
2864
2899
|
${candidateSections}` : factsBlock
|
|
@@ -2869,7 +2904,7 @@ ${candidateSections}` : factsBlock
|
|
|
2869
2904
|
const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
|
|
2870
2905
|
const grounding = this.groundingFor("librarian");
|
|
2871
2906
|
return {
|
|
2872
|
-
systemPrompt: this.appendGrounding(this.appendGuidance(this.
|
|
2907
|
+
systemPrompt: this.appendGrounding(this.appendGuidance(this.appendWriteOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
|
|
2873
2908
|
userPrompt: `Events:
|
|
2874
2909
|
${lines.join("\n")}`,
|
|
2875
2910
|
// Corpus entries are one-per-batch-event in batch order (summaries are
|
|
@@ -2890,13 +2925,14 @@ ${JSON.stringify({ items })}` };
|
|
|
2890
2925
|
* placeholders and leaves data placeholders verbatim; heal never receives
|
|
2891
2926
|
* ontology context, matching `buildHealPrompt`.
|
|
2892
2927
|
*/
|
|
2893
|
-
buildInstructionTemplates(
|
|
2928
|
+
buildInstructionTemplates(writeContext, librarianStrategy, guidance, backfillContext, ingestContext) {
|
|
2894
2929
|
const o = this.globalOverrides;
|
|
2930
|
+
const backfill = backfillContext !== void 0 ? backfillContext : writeContext ? { ontologyManifest: writeContext.ontologyManifest, ontologyModeInstructions: writeContext.ontologyModeInstructions } : null;
|
|
2895
2931
|
return {
|
|
2896
|
-
ingest: this.appendGrounding(this.appendGuidance(this.
|
|
2897
|
-
librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.
|
|
2932
|
+
ingest: this.appendGrounding(this.appendGuidance(this.buildWriteSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ingestContext !== void 0 ? ingestContext : writeContext), guidance), "ingest"),
|
|
2933
|
+
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"),
|
|
2898
2934
|
heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
|
|
2899
|
-
ontologyBackfill: this.
|
|
2935
|
+
ontologyBackfill: this.buildBackfillSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, backfill)
|
|
2900
2936
|
};
|
|
2901
2937
|
}
|
|
2902
2938
|
};
|
|
@@ -3182,7 +3218,7 @@ var IngestionService = class {
|
|
|
3182
3218
|
}
|
|
3183
3219
|
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
3184
3220
|
if (chunks2.length === 0) return zeroChunkResult();
|
|
3185
|
-
const ontologyContext = await this.ontologyService?.
|
|
3221
|
+
const ontologyContext = await this.ontologyService?.buildWritePromptContext(entityId, { engaged: false }) ?? null;
|
|
3186
3222
|
const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
|
|
3187
3223
|
if (diagnostic) {
|
|
3188
3224
|
emitDiagnostic(this.options, {
|
|
@@ -4199,6 +4235,16 @@ function resolveSystemOneHealScreen(config) {
|
|
|
4199
4235
|
}
|
|
4200
4236
|
return healScreen ?? "llm";
|
|
4201
4237
|
}
|
|
4238
|
+
function resolveSystemOneTypeOnWrite(config) {
|
|
4239
|
+
const typeOnWrite = config?.systemOne?.typeOnWrite;
|
|
4240
|
+
if (typeOnWrite !== void 0 && !isTypingMode(typeOnWrite)) {
|
|
4241
|
+
warnOnce(
|
|
4242
|
+
`[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.`
|
|
4243
|
+
);
|
|
4244
|
+
return "llm";
|
|
4245
|
+
}
|
|
4246
|
+
return typeOnWrite ?? "llm";
|
|
4247
|
+
}
|
|
4202
4248
|
function resolveHealScreenMinConfidence(config) {
|
|
4203
4249
|
if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
|
|
4204
4250
|
const floor = config?.systemOne?.minConfidence?.healScreen;
|
|
@@ -5052,6 +5098,152 @@ async function restartRebuildAfterVacuum(db, prefix, meta) {
|
|
|
5052
5098
|
});
|
|
5053
5099
|
}
|
|
5054
5100
|
|
|
5101
|
+
// src/services/typing/typeOnWrite.ts
|
|
5102
|
+
var CLASSIFIER_MAX_CHOICES = 255;
|
|
5103
|
+
function isManifestRepresentable(manifest) {
|
|
5104
|
+
const slugs = manifest.node_types.map((n) => n.type);
|
|
5105
|
+
return slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s));
|
|
5106
|
+
}
|
|
5107
|
+
function canEngageWriteTyping(config, provider, mode, manifest) {
|
|
5108
|
+
return resolveSystemOneTypeOnWrite(config) === "auto" && typeof provider.classify === "function" && mode !== "off" && isManifestRepresentable(manifest);
|
|
5109
|
+
}
|
|
5110
|
+
function buildTypingQuestion(manifest) {
|
|
5111
|
+
return {
|
|
5112
|
+
kind: "choice",
|
|
5113
|
+
options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
|
|
5114
|
+
instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
|
|
5115
|
+
` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
|
|
5116
|
+
};
|
|
5117
|
+
}
|
|
5118
|
+
function volunteeredTypeResolves(rawOkfType, manifest) {
|
|
5119
|
+
return typeof rawOkfType === "string" && resolveNodeTypeMatch(rawOkfType, manifest) !== null;
|
|
5120
|
+
}
|
|
5121
|
+
async function classifyFactsForWrite(options, ctx, facts, manifest, floor) {
|
|
5122
|
+
const question = buildTypingQuestion(manifest);
|
|
5123
|
+
const rawConcurrency = options.config?.chunkConcurrency ?? 1;
|
|
5124
|
+
const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
|
|
5125
|
+
let stopped = false;
|
|
5126
|
+
return withConcurrency(
|
|
5127
|
+
facts.map((fact) => async () => {
|
|
5128
|
+
if (stopped) return { kind: "unattempted" };
|
|
5129
|
+
let response;
|
|
5130
|
+
try {
|
|
5131
|
+
response = await callClassify(
|
|
5132
|
+
options,
|
|
5133
|
+
{ operation: ctx.operation, entityId: ctx.entityId, trigger: ctx.trigger, meter: ctx.meter },
|
|
5134
|
+
{ state: classifierStateForFact(fact), questions: { okf_type: question } }
|
|
5135
|
+
);
|
|
5136
|
+
} catch (err) {
|
|
5137
|
+
if (err instanceof WikiBudgetExhausted) {
|
|
5138
|
+
stopped = true;
|
|
5139
|
+
return { kind: "unattempted" };
|
|
5140
|
+
}
|
|
5141
|
+
if (isContextOverflowError(err)) return { kind: "overflow_skip" };
|
|
5142
|
+
return { kind: "threw" };
|
|
5143
|
+
}
|
|
5144
|
+
const checked = validateClassifierAnswer(response, "okf_type", question);
|
|
5145
|
+
if (!checked.ok) return { kind: "invalid", reason: checked.reason };
|
|
5146
|
+
if (checked.answer.kind !== "choice") return { kind: "invalid", reason: "kind_mismatch" };
|
|
5147
|
+
if (isReservedAbstainSlug(checked.answer.choice)) return { kind: "abstain" };
|
|
5148
|
+
if (checked.answer.confidence < floor) return { kind: "low_confidence" };
|
|
5149
|
+
return { kind: "accepted", okfType: checked.answer.choice, confidence: checked.answer.confidence };
|
|
5150
|
+
}),
|
|
5151
|
+
concurrency
|
|
5152
|
+
);
|
|
5153
|
+
}
|
|
5154
|
+
function emptyTypingCounters() {
|
|
5155
|
+
return { asked: 0, typed: 0, abstained: 0, lowConfidence: 0, invalid: 0, skipped: 0, unattempted: 0 };
|
|
5156
|
+
}
|
|
5157
|
+
function tallyTypingOutcome(c, o) {
|
|
5158
|
+
switch (o.kind) {
|
|
5159
|
+
case "unattempted":
|
|
5160
|
+
c.unattempted++;
|
|
5161
|
+
return;
|
|
5162
|
+
case "accepted":
|
|
5163
|
+
c.asked++;
|
|
5164
|
+
return;
|
|
5165
|
+
case "abstain":
|
|
5166
|
+
c.asked++;
|
|
5167
|
+
c.abstained++;
|
|
5168
|
+
return;
|
|
5169
|
+
case "low_confidence":
|
|
5170
|
+
c.asked++;
|
|
5171
|
+
c.lowConfidence++;
|
|
5172
|
+
return;
|
|
5173
|
+
case "invalid":
|
|
5174
|
+
case "threw":
|
|
5175
|
+
c.asked++;
|
|
5176
|
+
c.invalid++;
|
|
5177
|
+
return;
|
|
5178
|
+
case "overflow_skip":
|
|
5179
|
+
c.asked++;
|
|
5180
|
+
c.skipped++;
|
|
5181
|
+
return;
|
|
5182
|
+
}
|
|
5183
|
+
}
|
|
5184
|
+
function typingOutcomeReceipt(base, factId, outcome) {
|
|
5185
|
+
switch (outcome.kind) {
|
|
5186
|
+
case "abstain":
|
|
5187
|
+
return { ...base, code: "classification_abstained", detail: { factId, writer: "classifier" } };
|
|
5188
|
+
case "low_confidence":
|
|
5189
|
+
return { ...base, code: "classification_low_confidence", detail: { factId, reason: "below_threshold" } };
|
|
5190
|
+
case "invalid":
|
|
5191
|
+
return { ...base, code: "classification_invalid", detail: { factId, reason: outcome.reason } };
|
|
5192
|
+
case "threw":
|
|
5193
|
+
return { ...base, code: "classification_invalid", detail: { factId, reason: "classify_threw" } };
|
|
5194
|
+
case "overflow_skip":
|
|
5195
|
+
return { ...base, code: "context_overflow_skipped", detail: { factId } };
|
|
5196
|
+
default:
|
|
5197
|
+
return null;
|
|
5198
|
+
}
|
|
5199
|
+
}
|
|
5200
|
+
function normalizeForWrite(ontology, fact, manifest, mode, outcome, base, factId) {
|
|
5201
|
+
const drops = [];
|
|
5202
|
+
const receipts = [];
|
|
5203
|
+
const emit = shouldEmitOntologyReceipt(mode);
|
|
5204
|
+
let normalized = ontology?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
|
|
5205
|
+
if (emit) {
|
|
5206
|
+
receipts.push(...nodeTypeReceipts(
|
|
5207
|
+
base,
|
|
5208
|
+
factId,
|
|
5209
|
+
typeof fact.okf_type === "string" ? fact.okf_type : "",
|
|
5210
|
+
normalized.okf_type,
|
|
5211
|
+
normalized.match
|
|
5212
|
+
));
|
|
5213
|
+
}
|
|
5214
|
+
let typedByClassifier = false;
|
|
5215
|
+
if (!normalized.okf_type && outcome?.kind === "accepted" && mode !== "off") {
|
|
5216
|
+
const second = ontology?.validateAndNormalizeFact(
|
|
5217
|
+
{ ...fact, okf_type: outcome.okfType, edges: [] },
|
|
5218
|
+
manifest,
|
|
5219
|
+
{ strict: false }
|
|
5220
|
+
) ?? { okf_type: null};
|
|
5221
|
+
if (emit) {
|
|
5222
|
+
receipts.push(...nodeTypeReceipts(base, factId, outcome.okfType, second.okf_type, second.match));
|
|
5223
|
+
}
|
|
5224
|
+
normalized = { okf_type: second.okf_type, edges: [] };
|
|
5225
|
+
if (second.okf_type) {
|
|
5226
|
+
typedByClassifier = true;
|
|
5227
|
+
if (emit) {
|
|
5228
|
+
receipts.push({
|
|
5229
|
+
...base,
|
|
5230
|
+
code: "node_type_assigned",
|
|
5231
|
+
detail: { factId, okfType: second.okf_type, writer: "classifier", confidence: outcome.confidence }
|
|
5232
|
+
});
|
|
5233
|
+
}
|
|
5234
|
+
}
|
|
5235
|
+
} else if (normalized.okf_type) {
|
|
5236
|
+
if (emit) {
|
|
5237
|
+
receipts.push({ ...base, code: "node_type_assigned", detail: { factId, okfType: normalized.okf_type, writer: "llm" } });
|
|
5238
|
+
}
|
|
5239
|
+
}
|
|
5240
|
+
if (outcome && outcome.kind !== "accepted" && emit && !normalized.okf_type) {
|
|
5241
|
+
const r = typingOutcomeReceipt(base, factId, outcome);
|
|
5242
|
+
if (r) receipts.push(r);
|
|
5243
|
+
}
|
|
5244
|
+
return { normalized, drops, receipts, typedByClassifier };
|
|
5245
|
+
}
|
|
5246
|
+
|
|
5055
5247
|
// src/services/librarian/constants.ts
|
|
5056
5248
|
var FUZZY_THRESHOLD = 0.5;
|
|
5057
5249
|
var MIN_TOKENS_TO_QUALIFY = 3;
|
|
@@ -5069,7 +5261,9 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5069
5261
|
tags: typeof rest.tags === "string" ? JSON.parse(rest.tags) : rest.tags
|
|
5070
5262
|
};
|
|
5071
5263
|
});
|
|
5072
|
-
const
|
|
5264
|
+
const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
|
|
5265
|
+
const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
|
|
5266
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
|
|
5073
5267
|
const promptEvents = events.reverse();
|
|
5074
5268
|
const librarianGrounding = deps.promptService.groundingFor("librarian");
|
|
5075
5269
|
const { systemPrompt, userPrompt, groundingCorpus: librarianCorpus = [] } = deps.promptService.buildLibrarianPrompt(
|
|
@@ -5115,6 +5309,22 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5115
5309
|
if (valid) validTasks.push(valid);
|
|
5116
5310
|
else diagBuffer.push({ ...diagBase, code: "task_rejected", detail: { itemIndex, reason: taskRejectionReason(raw) } });
|
|
5117
5311
|
});
|
|
5312
|
+
const typingCounters = engaged ? emptyTypingCounters() : void 0;
|
|
5313
|
+
const typingOutcomes = /* @__PURE__ */ new Map();
|
|
5314
|
+
if (engaged && typingState && typingCounters) {
|
|
5315
|
+
const asked = validFacts.filter((f) => !volunteeredTypeResolves(f.okf_type, typingState.manifest));
|
|
5316
|
+
const outcomes = await classifyFactsForWrite(
|
|
5317
|
+
deps.options,
|
|
5318
|
+
{ entityId, trigger, meter: ctx.meter, operation: "librarian" },
|
|
5319
|
+
asked,
|
|
5320
|
+
typingState.manifest,
|
|
5321
|
+
resolveTypingMinConfidence(deps.options.config)
|
|
5322
|
+
);
|
|
5323
|
+
asked.forEach((f, i) => {
|
|
5324
|
+
typingOutcomes.set(f, outcomes[i]);
|
|
5325
|
+
tallyTypingOutcome(typingCounters, outcomes[i]);
|
|
5326
|
+
});
|
|
5327
|
+
}
|
|
5118
5328
|
const now = Date.now();
|
|
5119
5329
|
const insertedFacts = [];
|
|
5120
5330
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
@@ -5161,20 +5371,18 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5161
5371
|
}
|
|
5162
5372
|
const ontologyFact = fact;
|
|
5163
5373
|
const id = generateId("fact_");
|
|
5164
|
-
const validationDrops =
|
|
5165
|
-
|
|
5374
|
+
const { normalized, drops: validationDrops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
|
|
5375
|
+
deps.ontologyService,
|
|
5376
|
+
ontologyFact,
|
|
5377
|
+
manifest,
|
|
5378
|
+
mode,
|
|
5379
|
+
typingOutcomes.get(fact),
|
|
5380
|
+
diagBase,
|
|
5381
|
+
id
|
|
5382
|
+
);
|
|
5166
5383
|
for (const drop of validationDrops) diagBuffer.push(edgeDropDiagnostic(drop, { ...diagBase, factId: id }));
|
|
5167
|
-
|
|
5168
|
-
|
|
5169
|
-
{ entityId, operation: "librarian", trigger },
|
|
5170
|
-
id,
|
|
5171
|
-
ontologyFact.okf_type ?? "",
|
|
5172
|
-
normalized.okf_type,
|
|
5173
|
-
normalized.match
|
|
5174
|
-
)) {
|
|
5175
|
-
diagBuffer.push(receipt);
|
|
5176
|
-
}
|
|
5177
|
-
}
|
|
5384
|
+
for (const receipt of doorReceipts) diagBuffer.push(receipt);
|
|
5385
|
+
if (typedByClassifier && typingCounters) typingCounters.typed++;
|
|
5178
5386
|
const grounding = librarianGrounding ? groundingOutcome(checkGrounding(fact.evidence, librarianCorpus, librarianGrounding), now) : null;
|
|
5179
5387
|
if (grounding?.diagnostic) {
|
|
5180
5388
|
diagBuffer.push({ ...diagBase, code: grounding.diagnostic.code, detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: grounding.diagnostic.reason } });
|
|
@@ -5254,7 +5462,7 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
|
|
|
5254
5462
|
}
|
|
5255
5463
|
deps.searchService.evictCache(entityId);
|
|
5256
5464
|
const processedThrough = events.length > 0 ? { at: events[events.length - 1].created_at, id: events[events.length - 1].id } : null;
|
|
5257
|
-
const out = { processedThrough, factsWritten: insertedFacts.length };
|
|
5465
|
+
const out = { processedThrough, factsWritten: insertedFacts.length, ...typingCounters ? { typing: typingCounters } : {} };
|
|
5258
5466
|
return out;
|
|
5259
5467
|
};
|
|
5260
5468
|
|
|
@@ -5281,7 +5489,7 @@ var RESOLVE_RESERVE_FACTOR = 2;
|
|
|
5281
5489
|
var MIN_SEGMENT_CHARS = 500;
|
|
5282
5490
|
var MAX_SEGMENT_CALLS = 8;
|
|
5283
5491
|
var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
|
|
5284
|
-
async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
5492
|
+
async function selectBatch(deps, entityId, wm, meter, guidance, budget, engaged = false) {
|
|
5285
5493
|
const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
|
|
5286
5494
|
if (events.length === 0) return { batch: [] };
|
|
5287
5495
|
const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
|
|
@@ -5294,7 +5502,7 @@ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
|
|
|
5294
5502
|
}
|
|
5295
5503
|
let batch = labelEvents(events.slice(0, n));
|
|
5296
5504
|
if (meter && meter.budget !== void 0) {
|
|
5297
|
-
const ontologyContext = await deps.ontologyService?.
|
|
5505
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(entityId, { engaged }) ?? null;
|
|
5298
5506
|
for (; ; ) {
|
|
5299
5507
|
const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
|
|
5300
5508
|
if (meter.fits(need)) break;
|
|
@@ -5450,8 +5658,8 @@ async function extractWithOverflowRetry(deps, ctx, ontologyContext, batch, probe
|
|
|
5450
5658
|
return { ...merged, batch: [lone] };
|
|
5451
5659
|
}
|
|
5452
5660
|
}
|
|
5453
|
-
async function runExtract(deps, ctx, batch) {
|
|
5454
|
-
const ontologyContext = await deps.ontologyService?.
|
|
5661
|
+
async function runExtract(deps, ctx, batch, engaged = false) {
|
|
5662
|
+
const ontologyContext = await deps.ontologyService?.buildWritePromptContext(ctx.entityId, { engaged }) ?? null;
|
|
5455
5663
|
return extractWithOverflowRetry(deps, ctx, ontologyContext, batch, { checked: false });
|
|
5456
5664
|
}
|
|
5457
5665
|
async function extractOnce(deps, ctx, ontologyContext, batch) {
|
|
@@ -5777,6 +5985,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
5777
5985
|
const failed = new Set(input.failed);
|
|
5778
5986
|
const written = [];
|
|
5779
5987
|
const updatedIds = [];
|
|
5988
|
+
const supersededIds = [];
|
|
5780
5989
|
const now = Date.now();
|
|
5781
5990
|
await deps.db.withTransactionAsync(async (tx) => {
|
|
5782
5991
|
let { mode, manifest } = await deps.ontologyService?.getEffectiveState(entityId, tx) ?? { mode: "off", manifest: { node_types: [], edge_types: [] } };
|
|
@@ -5802,19 +6011,17 @@ async function applyOps(deps, ctx, input) {
|
|
|
5802
6011
|
const title = overrides?.title ?? fact.title;
|
|
5803
6012
|
const body = overrides?.body ?? fact.body;
|
|
5804
6013
|
const id = generateId("fact_");
|
|
5805
|
-
const drops =
|
|
5806
|
-
|
|
5807
|
-
|
|
5808
|
-
|
|
5809
|
-
|
|
5810
|
-
|
|
5811
|
-
|
|
5812
|
-
|
|
5813
|
-
|
|
5814
|
-
|
|
5815
|
-
|
|
5816
|
-
}
|
|
5817
|
-
}
|
|
6014
|
+
const { normalized, drops, receipts: doorReceipts, typedByClassifier } = normalizeForWrite(
|
|
6015
|
+
deps.ontologyService,
|
|
6016
|
+
fact,
|
|
6017
|
+
manifest,
|
|
6018
|
+
mode,
|
|
6019
|
+
input.typing?.outcomes.get(g),
|
|
6020
|
+
diagBase,
|
|
6021
|
+
id
|
|
6022
|
+
);
|
|
6023
|
+
for (const receipt of doorReceipts) input.diagnostics.push(receipt);
|
|
6024
|
+
if (typedByClassifier && input.typing) input.typing.counters.typed++;
|
|
5818
6025
|
for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
|
|
5819
6026
|
const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
|
|
5820
6027
|
const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
|
|
@@ -5899,6 +6106,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
5899
6106
|
titleIndex.delete(normalizeTitleKey(existing.title));
|
|
5900
6107
|
titleIndex.set(normalizeTitleKey(newTitle), { id: existing.id, okf_type: existing.okf_type ?? null });
|
|
5901
6108
|
updatedIds.push(existing.id);
|
|
6109
|
+
input.diagnostics.push({ ...diagBase, code: "librarian_rewritten", detail: { factId: existing.id } });
|
|
5902
6110
|
continue;
|
|
5903
6111
|
}
|
|
5904
6112
|
}
|
|
@@ -5912,6 +6120,8 @@ async function applyOps(deps, ctx, input) {
|
|
|
5912
6120
|
const newId = await insert(g, false, supersedeFrom, overrides);
|
|
5913
6121
|
try {
|
|
5914
6122
|
await temporal.supersedeInTx(tx, entityId, op.targetId, newId, supersedeFrom, now);
|
|
6123
|
+
supersededIds.push(op.targetId);
|
|
6124
|
+
input.diagnostics.push({ ...diagBase, code: "librarian_superseded", detail: { factId: op.targetId, replacementId: newId } });
|
|
5915
6125
|
} catch (err) {
|
|
5916
6126
|
if (!(err instanceof WikiSupersedeError)) throw err;
|
|
5917
6127
|
input.diagnostics.push({
|
|
@@ -5951,7 +6161,7 @@ async function applyOps(deps, ctx, input) {
|
|
|
5951
6161
|
await deps.taskRepo.upsert(taskObj, tx);
|
|
5952
6162
|
}
|
|
5953
6163
|
});
|
|
5954
|
-
return { written, updatedIds };
|
|
6164
|
+
return { written, updatedIds, supersededIds };
|
|
5955
6165
|
}
|
|
5956
6166
|
|
|
5957
6167
|
// src/services/librarian/ops/index.ts
|
|
@@ -5960,7 +6170,9 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
5960
6170
|
const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
|
|
5961
6171
|
await deps.seedWatermark(entityId);
|
|
5962
6172
|
const wm = await deps.getWatermark(entityId);
|
|
5963
|
-
const
|
|
6173
|
+
const typingState = deps.ontologyService ? await deps.ontologyService.getEffectiveState(entityId) : void 0;
|
|
6174
|
+
const engaged = typingState !== void 0 && canEngageWriteTyping(deps.options.config, deps.options.llmProvider, typingState.mode, typingState.manifest);
|
|
6175
|
+
const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config), engaged);
|
|
5964
6176
|
if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
|
|
5965
6177
|
if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
|
|
5966
6178
|
if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
|
|
@@ -5968,7 +6180,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
5968
6180
|
}
|
|
5969
6181
|
let ex;
|
|
5970
6182
|
try {
|
|
5971
|
-
ex = await runExtract(deps, ctx, sel.batch);
|
|
6183
|
+
ex = await runExtract(deps, ctx, sel.batch, engaged);
|
|
5972
6184
|
} catch (err) {
|
|
5973
6185
|
if (err instanceof WikiBudgetExhausted) {
|
|
5974
6186
|
return { processedThrough: null, factsWritten: 0, budgetStop: { requiredEstimate: err.requiredEstimate } };
|
|
@@ -6013,7 +6225,33 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
6013
6225
|
diagnostics.discard();
|
|
6014
6226
|
return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
|
|
6015
6227
|
}
|
|
6016
|
-
const
|
|
6228
|
+
const typingCounters = engaged ? emptyTypingCounters() : void 0;
|
|
6229
|
+
const typingOutcomes = /* @__PURE__ */ new Map();
|
|
6230
|
+
if (engaged && typingState && typingCounters) {
|
|
6231
|
+
const failed = new Set(res.failed);
|
|
6232
|
+
const rejected = new Set(res.rejected);
|
|
6233
|
+
const asked = gated.filter((g) => {
|
|
6234
|
+
if (g.decision.kind === "noop") return false;
|
|
6235
|
+
if (volunteeredTypeResolves(g.candidate.fact.okf_type, typingState.manifest)) return false;
|
|
6236
|
+
if (g.decision.kind === "add" || failed.has(g)) return true;
|
|
6237
|
+
const op = res.ops.get(g);
|
|
6238
|
+
if (rejected.has(g) || !op) return true;
|
|
6239
|
+
return op.op !== "NOOP";
|
|
6240
|
+
});
|
|
6241
|
+
const outcomes = await classifyFactsForWrite(
|
|
6242
|
+
deps.options,
|
|
6243
|
+
{ entityId, trigger, meter: ctx.meter, operation: "librarian" },
|
|
6244
|
+
asked.map((g) => g.candidate.fact),
|
|
6245
|
+
typingState.manifest,
|
|
6246
|
+
resolveTypingMinConfidence(deps.options.config)
|
|
6247
|
+
);
|
|
6248
|
+
asked.forEach((g, n) => {
|
|
6249
|
+
typingOutcomes.set(g, outcomes[n]);
|
|
6250
|
+
tallyTypingOutcome(typingCounters, outcomes[n]);
|
|
6251
|
+
});
|
|
6252
|
+
}
|
|
6253
|
+
const { written, updatedIds, supersededIds } = await applyOps(deps, ctx, {
|
|
6254
|
+
typing: typingCounters ? { outcomes: typingOutcomes, counters: typingCounters } : void 0,
|
|
6017
6255
|
gated,
|
|
6018
6256
|
ops: res.ops,
|
|
6019
6257
|
rejected: res.rejected,
|
|
@@ -6042,7 +6280,10 @@ var runOpsLibrarianPass = async (deps, ctx) => {
|
|
|
6042
6280
|
const last = ex.batch[ex.batch.length - 1].event;
|
|
6043
6281
|
return {
|
|
6044
6282
|
processedThrough: { at: last.created_at, id: last.id },
|
|
6045
|
-
factsWritten: written.length + updatedIds.length
|
|
6283
|
+
factsWritten: written.length + updatedIds.length,
|
|
6284
|
+
...typingCounters ? { typing: typingCounters } : {},
|
|
6285
|
+
rewrittenIds: updatedIds,
|
|
6286
|
+
supersededIds
|
|
6046
6287
|
};
|
|
6047
6288
|
};
|
|
6048
6289
|
|
|
@@ -6064,7 +6305,6 @@ async function runLibrarianStrategy(deps, ctx) {
|
|
|
6064
6305
|
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.`;
|
|
6065
6306
|
var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
|
|
6066
6307
|
var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
6067
|
-
var CLASSIFIER_MAX_CHOICES = 255;
|
|
6068
6308
|
var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
|
|
6069
6309
|
var HEAL_BATCH_SIZE = 25;
|
|
6070
6310
|
var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
@@ -7652,8 +7892,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7652
7892
|
const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
|
|
7653
7893
|
const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
|
|
7654
7894
|
if (classifierMode === "auto" && typeof classify === "function") {
|
|
7655
|
-
|
|
7656
|
-
if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
|
|
7895
|
+
if (isManifestRepresentable(effectiveManifest)) {
|
|
7657
7896
|
const classifierRun = await this._runClassifierBackfill(
|
|
7658
7897
|
entityId,
|
|
7659
7898
|
candidates,
|
|
@@ -7902,12 +8141,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
|
|
|
7902
8141
|
const minConfidence = resolveTypingMinConfidence(this.options.config);
|
|
7903
8142
|
const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
|
|
7904
8143
|
const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
|
|
7905
|
-
const question =
|
|
7906
|
-
kind: "choice",
|
|
7907
|
-
options: [...manifest.node_types.map((n) => n.type), ONTOLOGY_ABSTAIN_SENTINEL],
|
|
7908
|
-
instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
|
|
7909
|
-
` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
|
|
7910
|
-
};
|
|
8144
|
+
const question = buildTypingQuestion(manifest);
|
|
7911
8145
|
const edgeScreen = /* @__PURE__ */ new Map();
|
|
7912
8146
|
if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
|
|
7913
8147
|
const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
|