@equationalapplications/core-llm-wiki 9.11.0 → 9.13.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.
@@ -3964,6 +3964,26 @@ function resolveSystemOneTyping(config, classifierCallOption) {
3964
3964
  }
3965
3965
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3966
3966
  }
3967
+ function resolveSystemOneEdges(config) {
3968
+ const edges = config?.systemOne?.edges;
3969
+ if (edges !== void 0 && !isTypingMode(edges)) {
3970
+ warnOnce(
3971
+ `[core-llm-wiki] systemOne: \`systemOne.edges\` is ${formatConfigValue(edges)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3972
+ );
3973
+ return "llm";
3974
+ }
3975
+ return edges ?? "llm";
3976
+ }
3977
+ function resolveSystemOneResolve(config) {
3978
+ const resolve = config?.systemOne?.resolve;
3979
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
3980
+ warnOnce(
3981
+ `[core-llm-wiki] systemOne: \`systemOne.resolve\` is ${formatConfigValue(resolve)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
3982
+ );
3983
+ return "llm";
3984
+ }
3985
+ return resolve ?? "llm";
3986
+ }
3967
3987
  var DEFAULT_SHORTLIST_K = 10;
3968
3988
  function resolveShortlistK(config) {
3969
3989
  const k = config?.ontology?.shortlistK;
@@ -3993,6 +4013,25 @@ function resolveTypingMinConfidence(config) {
3993
4013
  }
3994
4014
  return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3995
4015
  }
4016
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4017
+ function resolveEdgesMinConfidence(config) {
4018
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
4019
+ const floor = config?.systemOne?.minConfidence?.edges;
4020
+ if (isEdgesFloor(floor)) return floor;
4021
+ warnOnce(
4022
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.edges` is required when `systemOne.edges` is 'auto'. The edge screen is off for this site; edges stay on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.edges\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The edge screen is off for this site; edges stay on the generative path.`
4023
+ );
4024
+ return void 0;
4025
+ }
4026
+ function resolveResolveMinConfidence(config) {
4027
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
4028
+ const floor = config?.systemOne?.minConfidence?.resolve;
4029
+ if (isEdgesFloor(floor)) return floor;
4030
+ warnOnce(
4031
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.resolve` is required when `systemOne.resolve` is 'auto'. A wrong NOOP drops a live fact, so there is no default floor. The resolution screen is off; resolution stays on the generative path." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.resolve\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. A wrong NOOP drops a live fact, so the resolution screen is off; resolution stays on the generative path.`
4032
+ );
4033
+ return void 0;
4034
+ }
3996
4035
 
3997
4036
  // src/utils/classifier.ts
3998
4037
  var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
@@ -6662,6 +6701,46 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
6662
6701
  }
6663
6702
 
6664
6703
  // src/services/librarian/ops/resolve.ts
6704
+ async function screenResolveCandidates(ambiguous, mode, floor, ask) {
6705
+ const whole = (warnReason) => warnReason ? { settled: /* @__PURE__ */ new Map(), rest: ambiguous, warnReason } : { settled: /* @__PURE__ */ new Map(), rest: ambiguous };
6706
+ if (mode !== "auto") return whole();
6707
+ if (floor === void 0) return whole("no-floor");
6708
+ if (!ask) return whole("no-classifier");
6709
+ const settled = /* @__PURE__ */ new Map();
6710
+ const rest = [];
6711
+ for (const g of ambiguous) {
6712
+ const best = g.neighbours[0];
6713
+ if (!best) {
6714
+ rest.push(g);
6715
+ continue;
6716
+ }
6717
+ const question = {
6718
+ kind: "binary",
6719
+ instructions: `Does this candidate add NO information beyond neighbour ${best.ref} (a pure duplicate: same claims, no new content)?
6720
+ Neighbour ${best.ref} title: ${best.title}
6721
+ Neighbour ${best.ref} body: ${safeSlice(best.body, 0, OPS_NEIGHBOUR_BODY_CHARS)}`
6722
+ };
6723
+ let response;
6724
+ try {
6725
+ response = await ask({
6726
+ state: classifierStateForFact({ title: g.candidate.fact.title, body: g.candidate.fact.body, tags: [] }),
6727
+ questions: { [best.ref]: question }
6728
+ });
6729
+ } catch (err) {
6730
+ if (err instanceof WikiBudgetExhausted) {
6731
+ return { settled: /* @__PURE__ */ new Map(), rest: ambiguous, budgetStop: { requiredEstimate: err.requiredEstimate } };
6732
+ }
6733
+ return whole("classifier-threw");
6734
+ }
6735
+ const checked = validateClassifierAnswer(response, best.ref, question);
6736
+ if (checked.ok && checked.answer.kind === "binary" && checked.answer.probability >= floor) {
6737
+ settled.set(g, { op: "NOOP", targetId: best.id });
6738
+ } else {
6739
+ rest.push(g);
6740
+ }
6741
+ }
6742
+ return { settled, rest };
6743
+ }
6665
6744
  function validateOp(raw, aliases) {
6666
6745
  if (!raw || typeof raw !== "object") return null;
6667
6746
  const r = raw;
@@ -6681,11 +6760,31 @@ function validateOp(raw, aliases) {
6681
6760
  }
6682
6761
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
6683
6762
  async function runResolve(deps, ctx, ambiguous, budget) {
6684
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
6763
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [], classifierSettled: [] };
6685
6764
  if (ambiguous.length === 0) return out;
6686
6765
  const { entityId, trigger } = ctx;
6766
+ const mode = resolveSystemOneResolve(deps.options.config);
6767
+ const floor = resolveResolveMinConfidence(deps.options.config);
6768
+ const provider = deps.options.llmProvider;
6769
+ const ask = mode === "auto" && typeof provider.classify === "function" ? (request) => callClassify(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, request) : void 0;
6770
+ const screen = await screenResolveCandidates(ambiguous, mode, floor, ask);
6771
+ if (screen.budgetStop) return { ...out, budgetStop: screen.budgetStop };
6772
+ if (screen.warnReason === "no-classifier") {
6773
+ warnOnce(
6774
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but the provider has no classify(); ambiguous candidates fall through to the generative resolve."
6775
+ );
6776
+ } else if (screen.warnReason === "classifier-threw") {
6777
+ warnOnce(
6778
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but classify() threw during the resolve screen; ambiguous candidates fall through to the generative resolve."
6779
+ );
6780
+ }
6781
+ for (const [g, op] of screen.settled) {
6782
+ out.ops.set(g, op);
6783
+ out.classifierSettled.push(g.candidate.index);
6784
+ }
6785
+ if (screen.rest.length === 0) return out;
6687
6786
  const outcome = await runBatched({
6688
- items: ambiguous,
6787
+ items: screen.rest,
6689
6788
  buildPrompt: (batch) => deps.promptService.buildOpsResolvePrompt(
6690
6789
  batch.map((g, i) => ({
6691
6790
  item: i,
@@ -6974,6 +7073,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
6974
7073
  // (index into the merged extract batch)
6975
7074
  });
6976
7075
  }
7076
+ for (const itemIndex of res.classifierSettled) {
7077
+ diagnostics.push({
7078
+ entityId,
7079
+ operation: "librarian",
7080
+ trigger,
7081
+ code: "fact_deduplicated",
7082
+ detail: { itemIndex, reason: "classifier" }
7083
+ // (index into the merged extract batch)
7084
+ });
7085
+ }
6977
7086
  if (res.budgetStop) {
6978
7087
  diagnostics.discard();
6979
7088
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -8524,7 +8633,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
8524
8633
  return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
8525
8634
  }
8526
8635
  const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
8636
+ const edgeMode = resolveSystemOneEdges(this.options.config);
8527
8637
  const classify = this.options.llmProvider.classify;
8638
+ const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
8639
+ const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
8528
8640
  if (classifierMode === "auto" && typeof classify === "function") {
8529
8641
  const slugs = effectiveManifest.node_types.map((n) => n.type);
8530
8642
  if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
@@ -8535,16 +8647,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
8535
8647
  now,
8536
8648
  recheckCutoff,
8537
8649
  options?.meter,
8538
- trigger
8650
+ trigger,
8651
+ shortlistK,
8652
+ edgeSiteMode,
8653
+ edgeMinConfidence
8539
8654
  );
8540
8655
  if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
8541
8656
  return classifierRun.result;
8542
8657
  }
8543
- if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
8658
+ if (classifierRun.escalated.length > 0) {
8544
8659
  const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
8545
8660
  if (liveMode === "off") {
8546
8661
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8547
- return { ...zeroed, remaining: 0, deferred: counts.deferred };
8662
+ const committed = classifierRun.result;
8663
+ return {
8664
+ scanned: committed.scanned,
8665
+ typed: committed.typed,
8666
+ failedValidation: committed.failedValidation,
8667
+ edgesAdded: committed.edgesAdded,
8668
+ abstained: committed.abstained,
8669
+ skipped: committed.skipped,
8670
+ remaining: 0,
8671
+ deferred: counts.deferred
8672
+ };
8548
8673
  }
8549
8674
  const escalated = classifierRun.escalated;
8550
8675
  const generative = await this._runGenerativeBackfill(entityId, escalated, {
@@ -8554,7 +8679,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8554
8679
  batchSize: escalated.length,
8555
8680
  recheckCutoff,
8556
8681
  shortlistK,
8557
- maxPromptChars
8682
+ maxPromptChars,
8683
+ edgeSiteMode,
8684
+ edgeMinConfidence
8558
8685
  });
8559
8686
  return {
8560
8687
  scanned: classifierRun.result.scanned,
@@ -8577,7 +8704,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8577
8704
  trigger,
8578
8705
  recheckCutoff,
8579
8706
  shortlistK,
8580
- maxPromptChars
8707
+ maxPromptChars,
8708
+ edgeSiteMode,
8709
+ edgeMinConfidence
8581
8710
  });
8582
8711
  }
8583
8712
  /**
@@ -8613,6 +8742,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
8613
8742
  if (maxPromptChars === void 0) {
8614
8743
  throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
8615
8744
  }
8745
+ if (runOpts.edgeSiteMode === void 0) {
8746
+ throw new Error("_runGenerativeBackfill: runOpts.edgeSiteMode is required (resolved at doRunOntologyBackfill entry)");
8747
+ }
8616
8748
  const ontologyService = this.ontologyService;
8617
8749
  const now = Date.now();
8618
8750
  const recheckCutoff = runOpts.recheckCutoff;
@@ -8740,12 +8872,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
8740
8872
  * untyped fact over the effective manifest's node-type slugs plus the
8741
8873
  * reserved abstain sentinel. Accepted answers go through
8742
8874
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
8743
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
8875
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
8876
+ * classifier screens per-fact edge questions against
8877
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
8878
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
8879
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
8880
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
8881
+ * fall through to the generative step. Edge outcomes are evaluated only for
8882
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
8744
8883
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
8745
8884
  * returned un-stamped in `escalated` for the generative step. Always
8746
8885
  * returns the `OntologyBackfillResult` for its step plus escalation state.
8747
8886
  */
8748
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
8887
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger, shortlistK, edgeSiteMode, edgeMinConfidence) {
8749
8888
  const minConfidence = resolveTypingMinConfidence(this.options.config);
8750
8889
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
8751
8890
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
@@ -8755,17 +8894,65 @@ DROP TRIGGER IF EXISTS ${ad};`);
8755
8894
  instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
8756
8895
  ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
8757
8896
  };
8897
+ const edgeScreen = /* @__PURE__ */ new Map();
8898
+ if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
8899
+ const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
8900
+ const poolTitleCounts = /* @__PURE__ */ new Map();
8901
+ for (const r of pool) {
8902
+ const k = normalizeTitleKey(r.title);
8903
+ poolTitleCounts.set(k, (poolTitleCounts.get(k) ?? 0) + 1);
8904
+ }
8905
+ const batchTitleKeys = new Set(candidates.map((f) => normalizeTitleKey(f.title)));
8906
+ const collides = (title) => {
8907
+ const k = normalizeTitleKey(title);
8908
+ return (poolTitleCounts.get(k) ?? 0) > 1 || batchTitleKeys.has(k);
8909
+ };
8910
+ const scorer = createShortlistScorer(pool);
8911
+ const edgeTypeNames = [...new Set(manifest.edge_types.map((e) => e.type))];
8912
+ for (const fact of candidates) {
8913
+ const ranked = buildShortlist({ title: fact.title, body: fact.body }, pool, shortlistK, scorer).filter((row) => !collides(row.title));
8914
+ const questions = {};
8915
+ const keyMap = /* @__PURE__ */ new Map();
8916
+ for (const row of ranked) {
8917
+ for (const edgeType of edgeTypeNames) {
8918
+ const definitions = manifest.edge_types.filter(
8919
+ (e) => e.type === edgeType && typeSatisfies(e.target_type, row.okf_type, manifest)
8920
+ );
8921
+ if (definitions.length === 0) continue;
8922
+ const key = `edge:${edgeType}:${row.id}`;
8923
+ const descriptions = [...new Set(definitions.map((d) => d.description))].join(" / ");
8924
+ questions[key] = {
8925
+ kind: "binary",
8926
+ instructions: `Does this fact have the "${edgeType}" relationship (${descriptions}) to the existing fact titled "${row.title}"?`
8927
+ };
8928
+ keyMap.set(key, { definitions, candidate: { id: row.id, title: row.title, okf_type: row.okf_type } });
8929
+ }
8930
+ }
8931
+ if (keyMap.size > 0) edgeScreen.set(fact.id, { questions, keyMap });
8932
+ }
8933
+ }
8758
8934
  let stopped;
8935
+ const retriedFacts = /* @__PURE__ */ new Set();
8759
8936
  const outcomes = await withConcurrency(
8760
8937
  candidates.map((fact) => async () => {
8761
8938
  if (stopped) return { fact, kind: "unattempted" };
8939
+ const edgeEntry = edgeScreen.get(fact.id);
8940
+ const ask = (questions) => callClassify(
8941
+ this.options,
8942
+ { operation: "ontologyBackfill", entityId, trigger, meter },
8943
+ { state: classifierStateForFact(fact), questions }
8944
+ );
8762
8945
  let response;
8946
+ let screened = edgeEntry !== void 0;
8763
8947
  try {
8764
- response = await callClassify(
8765
- this.options,
8766
- { operation: "ontologyBackfill", entityId, trigger, meter },
8767
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
8768
- );
8948
+ try {
8949
+ response = await ask({ okf_type: question, ...edgeEntry?.questions ?? {} });
8950
+ } catch (err) {
8951
+ if (!edgeEntry || err instanceof WikiBudgetExhausted || !isContextOverflowError(err)) throw err;
8952
+ response = await ask({ okf_type: question });
8953
+ screened = false;
8954
+ retriedFacts.add(fact.id);
8955
+ }
8769
8956
  } catch (err) {
8770
8957
  if (err instanceof WikiBudgetExhausted) {
8771
8958
  stopped ?? (stopped = err);
@@ -8779,17 +8966,54 @@ DROP TRIGGER IF EXISTS ${ad};`);
8779
8966
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
8780
8967
  if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
8781
8968
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
8782
- return { fact, kind: "accepted", okfType: checked.answer.choice };
8969
+ const okfType = checked.answer.choice;
8970
+ if (!screened || !edgeEntry || typeof edgeMinConfidence !== "number") return { fact, kind: "accepted", okfType };
8971
+ const floor = edgeMinConfidence;
8972
+ const edges = [];
8973
+ const edgeCandidateIds = /* @__PURE__ */ Object.create(null);
8974
+ let evaluated = 0;
8975
+ let uncertain = 0;
8976
+ let invalid = 0;
8977
+ let missing = 0;
8978
+ for (const [key, { definitions, candidate }] of edgeEntry.keyMap) {
8979
+ if (!definitions.some((d) => typeSatisfies(d.source_type, okfType, manifest))) continue;
8980
+ evaluated++;
8981
+ const answer = validateClassifierAnswer(response, key, edgeEntry.questions[key]);
8982
+ if (!answer.ok) {
8983
+ if (answer.reason === "missing_answer") missing++;
8984
+ else invalid++;
8985
+ continue;
8986
+ }
8987
+ if (answer.answer.kind !== "binary") {
8988
+ invalid++;
8989
+ continue;
8990
+ }
8991
+ const p = answer.answer.probability;
8992
+ if (p > 0.5 && p >= floor) {
8993
+ edges.push({ edge_type: definitions[0].type, target_title: candidate.title });
8994
+ edgeCandidateIds[normalizeTitleKey(candidate.title)] = candidate.id;
8995
+ } else if (p < 0.5 && 1 - p >= floor) continue;
8996
+ else uncertain++;
8997
+ }
8998
+ const edgeStats = { uncertain, invalid, missing, allMissing: evaluated > 0 && missing === evaluated };
8999
+ if (edgeStats.allMissing) return { fact, kind: "accepted", okfType, edgeStats };
9000
+ if (uncertain > 0 || invalid > 0 || missing > 0) return { fact, kind: "accepted", okfType, fallthrough: true, edgeStats };
9001
+ return { fact, kind: "accepted", okfType, ...edges.length > 0 ? { edges, edgeCandidateIds } : {} };
8783
9002
  }),
8784
9003
  concurrency
8785
9004
  );
8786
9005
  const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
8787
- const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
8788
- const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
9006
+ const isEscalated = (o) => o.kind === "accepted" && o.fallthrough === true || escalate && (o.kind === "abstain" || o.kind === "low_confidence");
9007
+ const escalated = outcomes.filter(isEscalated).map((o) => o.fact);
8789
9008
  const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
8790
9009
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
8791
9010
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
8792
- const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
9011
+ const classifications = outcomes.filter((o) => o.kind === "accepted" && o.fallthrough !== true).map((o) => ({
9012
+ id: o.fact.id,
9013
+ okf_type: o.okfType,
9014
+ // An outcome carries `edges` only when the site is 'auto'.
9015
+ ...o.edges && o.edges.length > 0 ? { edges: o.edges, edgeCandidateIds: o.edgeCandidateIds } : {}
9016
+ }));
8793
9017
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
8794
9018
  const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
8795
9019
  let typed = 0;
@@ -8814,7 +9038,21 @@ DROP TRIGGER IF EXISTS ${ad};`);
8814
9038
  const diagBuffer = new DiagnosticBuffer();
8815
9039
  const diagBase = { entityId, operation: "ontologyBackfill", trigger };
8816
9040
  for (const o of outcomes) {
8817
- if (o.kind === "abstain") {
9041
+ if (retriedFacts.has(o.fact.id)) {
9042
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id, reason: "edge_screen_overflow_retry" } });
9043
+ }
9044
+ if (o.kind === "accepted" && o.edgeStats) {
9045
+ const { invalid, missing, allMissing } = o.edgeStats;
9046
+ const code = allMissing || invalid > 0 || missing > 0 ? "classification_invalid" : "classification_low_confidence";
9047
+ diagBuffer.push({
9048
+ ...diagBase,
9049
+ code,
9050
+ detail: {
9051
+ factId: o.fact.id,
9052
+ reason: allMissing ? "edge_answers_missing" : code === "classification_invalid" ? "edge_answer_invalid" : "edge_uncertain"
9053
+ }
9054
+ });
9055
+ } else if (o.kind === "abstain") {
8818
9056
  if (isEscalated(o)) continue;
8819
9057
  diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
8820
9058
  } else if (o.kind === "low_confidence") {
@@ -8949,16 +9187,41 @@ DROP TRIGGER IF EXISTS ${ad};`);
8949
9187
  });
8950
9188
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
8951
9189
  if (normalized.edges.length > 0) {
8952
- pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
9190
+ pendingEdges.push({
9191
+ sourceId: fact.id,
9192
+ sourceType: normalized.okf_type,
9193
+ edges: normalized.edges,
9194
+ candidateIds: classification.edgeCandidateIds
9195
+ });
8953
9196
  }
8954
9197
  }
8955
9198
  for (const item of pendingEdges) {
8956
9199
  const resolveDrops = [];
9200
+ let edgesToResolve = item.edges;
9201
+ const screenedIds = item.candidateIds;
9202
+ if (screenedIds) {
9203
+ edgesToResolve = [];
9204
+ for (const edge of item.edges) {
9205
+ const key = normalizeTitleKey(edge.target_title);
9206
+ const screened = screenedIds[key];
9207
+ if (screened !== void 0 && titleIndex.get(key)?.id !== screened) {
9208
+ resolveDrops.push({
9209
+ reason: "target_not_found",
9210
+ sourceId: item.sourceId,
9211
+ edgeType: edge.edge_type,
9212
+ sourceNodeType: item.sourceType,
9213
+ targetNodeType: null
9214
+ });
9215
+ } else {
9216
+ edgesToResolve.push(edge);
9217
+ }
9218
+ }
9219
+ }
8957
9220
  const added = await ontologyService.resolveAndPersistEdges(
8958
9221
  entityId,
8959
9222
  item.sourceId,
8960
9223
  item.sourceType,
8961
- item.edges,
9224
+ edgesToResolve,
8962
9225
  manifest,
8963
9226
  titleIndex,
8964
9227
  tx,
@@ -11615,6 +11878,6 @@ var WriteService = class {
11615
11878
  }
11616
11879
  };
11617
11880
 
11618
- 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 };
11619
- //# sourceMappingURL=chunk-QUVPQVJ6.mjs.map
11620
- //# sourceMappingURL=chunk-QUVPQVJ6.mjs.map
11881
+ 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, resolveEdgesMinConfidence, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneResolve, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11882
+ //# sourceMappingURL=chunk-4TG7RQF6.mjs.map
11883
+ //# sourceMappingURL=chunk-4TG7RQF6.mjs.map