@equationalapplications/core-llm-wiki 9.10.0 → 9.12.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.
@@ -2751,6 +2751,7 @@ var DEFAULT_CHUNK_OVERLAP = 400;
2751
2751
 
2752
2752
  // src/utils/contextCaps.ts
2753
2753
  var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
2754
+ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
2754
2755
  var HEAL_MAX_PROMPT_CHARS = 4e4;
2755
2756
  var OPS_MAX_EXTRACT_CHARS = 24e3;
2756
2757
 
@@ -2761,7 +2762,8 @@ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
2761
2762
  var OP_FLOOR = {
2762
2763
  resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
2763
2764
  heal: HEAL_MAX_PROMPT_CHARS,
2764
- extract: OPS_MAX_EXTRACT_CHARS
2765
+ extract: OPS_MAX_EXTRACT_CHARS,
2766
+ backfill: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS
2765
2767
  };
2766
2768
  function bad(key, value, why) {
2767
2769
  return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
@@ -2799,12 +2801,11 @@ function declaredPromptCap(budget, op) {
2799
2801
  const derived = Math.floor(
2800
2802
  (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
2801
2803
  );
2802
- if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
2803
- return Math.max(OP_FLOOR.heal, derived);
2804
+ return Math.max(OP_FLOOR[op], derived);
2804
2805
  }
2805
2806
  function resolveMaxPromptChars(budget, op) {
2806
2807
  if (budget.mode !== "declared") {
2807
- return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
2808
+ return OP_FLOOR[op];
2808
2809
  }
2809
2810
  if (op === "extract") {
2810
2811
  const resolveDerived = declaredPromptCap(budget, "resolve");
@@ -3963,6 +3964,16 @@ function resolveSystemOneTyping(config, classifierCallOption) {
3963
3964
  }
3964
3965
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
3965
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
+ }
3966
3977
  var DEFAULT_SHORTLIST_K = 10;
3967
3978
  function resolveShortlistK(config) {
3968
3979
  const k = config?.ontology?.shortlistK;
@@ -3992,6 +4003,16 @@ function resolveTypingMinConfidence(config) {
3992
4003
  }
3993
4004
  return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
3994
4005
  }
4006
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4007
+ function resolveEdgesMinConfidence(config) {
4008
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
4009
+ const floor = config?.systemOne?.minConfidence?.edges;
4010
+ if (isEdgesFloor(floor)) return floor;
4011
+ warnOnce(
4012
+ 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.`
4013
+ );
4014
+ return void 0;
4015
+ }
3995
4016
 
3996
4017
  // src/utils/classifier.ts
3997
4018
  var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
@@ -7027,7 +7048,6 @@ async function runLibrarianStrategy(deps, ctx) {
7027
7048
  // src/services/MaintenanceService.ts
7028
7049
  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.`;
7029
7050
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
7030
- var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
7031
7051
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
7032
7052
  var CLASSIFIER_MAX_CHOICES = 255;
7033
7053
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
@@ -8504,6 +8524,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8504
8524
  throw new TypeError(`Invalid classifier option: ${JSON.stringify(options.classifier)} \u2014 must be 'auto' or 'llm'`);
8505
8525
  }
8506
8526
  const shortlistK = resolveShortlistK(this.options.config);
8527
+ const maxPromptChars = resolveMaxPromptChars(resolveContextBudget(this.options.config), "backfill");
8507
8528
  const trigger = options?.trigger ?? "call";
8508
8529
  const now = Date.now();
8509
8530
  const recheckCutoff = options?.recheckCheckedBefore ?? now - ONTOLOGY_BACKFILL_RECHECK_MS;
@@ -8523,7 +8544,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
8523
8544
  return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
8524
8545
  }
8525
8546
  const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
8547
+ const edgeMode = resolveSystemOneEdges(this.options.config);
8526
8548
  const classify = this.options.llmProvider.classify;
8549
+ const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
8550
+ const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
8527
8551
  if (classifierMode === "auto" && typeof classify === "function") {
8528
8552
  const slugs = effectiveManifest.node_types.map((n) => n.type);
8529
8553
  if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
@@ -8534,16 +8558,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
8534
8558
  now,
8535
8559
  recheckCutoff,
8536
8560
  options?.meter,
8537
- trigger
8561
+ trigger,
8562
+ shortlistK,
8563
+ edgeSiteMode,
8564
+ edgeMinConfidence
8538
8565
  );
8539
8566
  if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
8540
8567
  return classifierRun.result;
8541
8568
  }
8542
- if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
8569
+ if (classifierRun.escalated.length > 0) {
8543
8570
  const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
8544
8571
  if (liveMode === "off") {
8545
8572
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
8546
- return { ...zeroed, remaining: 0, deferred: counts.deferred };
8573
+ const committed = classifierRun.result;
8574
+ return {
8575
+ scanned: committed.scanned,
8576
+ typed: committed.typed,
8577
+ failedValidation: committed.failedValidation,
8578
+ edgesAdded: committed.edgesAdded,
8579
+ abstained: committed.abstained,
8580
+ skipped: committed.skipped,
8581
+ remaining: 0,
8582
+ deferred: counts.deferred
8583
+ };
8547
8584
  }
8548
8585
  const escalated = classifierRun.escalated;
8549
8586
  const generative = await this._runGenerativeBackfill(entityId, escalated, {
@@ -8552,7 +8589,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
8552
8589
  trigger,
8553
8590
  batchSize: escalated.length,
8554
8591
  recheckCutoff,
8555
- shortlistK
8592
+ shortlistK,
8593
+ maxPromptChars,
8594
+ edgeSiteMode,
8595
+ edgeMinConfidence
8556
8596
  });
8557
8597
  return {
8558
8598
  scanned: classifierRun.result.scanned,
@@ -8574,7 +8614,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
8574
8614
  meter: options?.meter,
8575
8615
  trigger,
8576
8616
  recheckCutoff,
8577
- shortlistK
8617
+ shortlistK,
8618
+ maxPromptChars,
8619
+ edgeSiteMode,
8620
+ edgeMinConfidence
8578
8621
  });
8579
8622
  }
8580
8623
  /**
@@ -8606,6 +8649,13 @@ DROP TRIGGER IF EXISTS ${ad};`);
8606
8649
  if (shortlistK === void 0) {
8607
8650
  throw new Error("_runGenerativeBackfill: runOpts.shortlistK is required (resolved at doRunOntologyBackfill entry)");
8608
8651
  }
8652
+ const maxPromptChars = runOpts.maxPromptChars;
8653
+ if (maxPromptChars === void 0) {
8654
+ throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
8655
+ }
8656
+ if (runOpts.edgeSiteMode === void 0) {
8657
+ throw new Error("_runGenerativeBackfill: runOpts.edgeSiteMode is required (resolved at doRunOntologyBackfill entry)");
8658
+ }
8609
8659
  const ontologyService = this.ontologyService;
8610
8660
  const now = Date.now();
8611
8661
  const recheckCutoff = runOpts.recheckCutoff;
@@ -8644,7 +8694,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
8644
8694
  };
8645
8695
  },
8646
8696
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
8647
- maxPromptChars: ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS,
8697
+ maxPromptChars,
8648
8698
  onSkip: (fact, err) => {
8649
8699
  if (isContextOverflowError(err)) {
8650
8700
  emitDiagnostic(this.options, {
@@ -8733,12 +8783,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
8733
8783
  * untyped fact over the effective manifest's node-type slugs plus the
8734
8784
  * reserved abstain sentinel. Accepted answers go through
8735
8785
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
8736
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
8786
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
8787
+ * classifier screens per-fact edge questions against
8788
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
8789
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
8790
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
8791
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
8792
+ * fall through to the generative step. Edge outcomes are evaluated only for
8793
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
8737
8794
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
8738
8795
  * returned un-stamped in `escalated` for the generative step. Always
8739
8796
  * returns the `OntologyBackfillResult` for its step plus escalation state.
8740
8797
  */
8741
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
8798
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger, shortlistK, edgeSiteMode, edgeMinConfidence) {
8742
8799
  const minConfidence = resolveTypingMinConfidence(this.options.config);
8743
8800
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
8744
8801
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
@@ -8748,17 +8805,65 @@ DROP TRIGGER IF EXISTS ${ad};`);
8748
8805
  instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
8749
8806
  ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
8750
8807
  };
8808
+ const edgeScreen = /* @__PURE__ */ new Map();
8809
+ if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
8810
+ const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
8811
+ const poolTitleCounts = /* @__PURE__ */ new Map();
8812
+ for (const r of pool) {
8813
+ const k = normalizeTitleKey(r.title);
8814
+ poolTitleCounts.set(k, (poolTitleCounts.get(k) ?? 0) + 1);
8815
+ }
8816
+ const batchTitleKeys = new Set(candidates.map((f) => normalizeTitleKey(f.title)));
8817
+ const collides = (title) => {
8818
+ const k = normalizeTitleKey(title);
8819
+ return (poolTitleCounts.get(k) ?? 0) > 1 || batchTitleKeys.has(k);
8820
+ };
8821
+ const scorer = createShortlistScorer(pool);
8822
+ const edgeTypeNames = [...new Set(manifest.edge_types.map((e) => e.type))];
8823
+ for (const fact of candidates) {
8824
+ const ranked = buildShortlist({ title: fact.title, body: fact.body }, pool, shortlistK, scorer).filter((row) => !collides(row.title));
8825
+ const questions = {};
8826
+ const keyMap = /* @__PURE__ */ new Map();
8827
+ for (const row of ranked) {
8828
+ for (const edgeType of edgeTypeNames) {
8829
+ const definitions = manifest.edge_types.filter(
8830
+ (e) => e.type === edgeType && typeSatisfies(e.target_type, row.okf_type, manifest)
8831
+ );
8832
+ if (definitions.length === 0) continue;
8833
+ const key = `edge:${edgeType}:${row.id}`;
8834
+ const descriptions = [...new Set(definitions.map((d) => d.description))].join(" / ");
8835
+ questions[key] = {
8836
+ kind: "binary",
8837
+ instructions: `Does this fact have the "${edgeType}" relationship (${descriptions}) to the existing fact titled "${row.title}"?`
8838
+ };
8839
+ keyMap.set(key, { definitions, candidate: { id: row.id, title: row.title, okf_type: row.okf_type } });
8840
+ }
8841
+ }
8842
+ if (keyMap.size > 0) edgeScreen.set(fact.id, { questions, keyMap });
8843
+ }
8844
+ }
8751
8845
  let stopped;
8846
+ const retriedFacts = /* @__PURE__ */ new Set();
8752
8847
  const outcomes = await withConcurrency(
8753
8848
  candidates.map((fact) => async () => {
8754
8849
  if (stopped) return { fact, kind: "unattempted" };
8850
+ const edgeEntry = edgeScreen.get(fact.id);
8851
+ const ask = (questions) => callClassify(
8852
+ this.options,
8853
+ { operation: "ontologyBackfill", entityId, trigger, meter },
8854
+ { state: classifierStateForFact(fact), questions }
8855
+ );
8755
8856
  let response;
8857
+ let screened = edgeEntry !== void 0;
8756
8858
  try {
8757
- response = await callClassify(
8758
- this.options,
8759
- { operation: "ontologyBackfill", entityId, trigger, meter },
8760
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
8761
- );
8859
+ try {
8860
+ response = await ask({ okf_type: question, ...edgeEntry?.questions ?? {} });
8861
+ } catch (err) {
8862
+ if (!edgeEntry || err instanceof WikiBudgetExhausted || !isContextOverflowError(err)) throw err;
8863
+ response = await ask({ okf_type: question });
8864
+ screened = false;
8865
+ retriedFacts.add(fact.id);
8866
+ }
8762
8867
  } catch (err) {
8763
8868
  if (err instanceof WikiBudgetExhausted) {
8764
8869
  stopped ?? (stopped = err);
@@ -8772,17 +8877,54 @@ DROP TRIGGER IF EXISTS ${ad};`);
8772
8877
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
8773
8878
  if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
8774
8879
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
8775
- return { fact, kind: "accepted", okfType: checked.answer.choice };
8880
+ const okfType = checked.answer.choice;
8881
+ if (!screened || !edgeEntry || typeof edgeMinConfidence !== "number") return { fact, kind: "accepted", okfType };
8882
+ const floor = edgeMinConfidence;
8883
+ const edges = [];
8884
+ const edgeCandidateIds = /* @__PURE__ */ Object.create(null);
8885
+ let evaluated = 0;
8886
+ let uncertain = 0;
8887
+ let invalid = 0;
8888
+ let missing = 0;
8889
+ for (const [key, { definitions, candidate }] of edgeEntry.keyMap) {
8890
+ if (!definitions.some((d) => typeSatisfies(d.source_type, okfType, manifest))) continue;
8891
+ evaluated++;
8892
+ const answer = validateClassifierAnswer(response, key, edgeEntry.questions[key]);
8893
+ if (!answer.ok) {
8894
+ if (answer.reason === "missing_answer") missing++;
8895
+ else invalid++;
8896
+ continue;
8897
+ }
8898
+ if (answer.answer.kind !== "binary") {
8899
+ invalid++;
8900
+ continue;
8901
+ }
8902
+ const p = answer.answer.probability;
8903
+ if (p > 0.5 && p >= floor) {
8904
+ edges.push({ edge_type: definitions[0].type, target_title: candidate.title });
8905
+ edgeCandidateIds[normalizeTitleKey(candidate.title)] = candidate.id;
8906
+ } else if (p < 0.5 && 1 - p >= floor) continue;
8907
+ else uncertain++;
8908
+ }
8909
+ const edgeStats = { uncertain, invalid, missing, allMissing: evaluated > 0 && missing === evaluated };
8910
+ if (edgeStats.allMissing) return { fact, kind: "accepted", okfType, edgeStats };
8911
+ if (uncertain > 0 || invalid > 0 || missing > 0) return { fact, kind: "accepted", okfType, fallthrough: true, edgeStats };
8912
+ return { fact, kind: "accepted", okfType, ...edges.length > 0 ? { edges, edgeCandidateIds } : {} };
8776
8913
  }),
8777
8914
  concurrency
8778
8915
  );
8779
8916
  const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
8780
- const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
8781
- const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
8917
+ const isEscalated = (o) => o.kind === "accepted" && o.fallthrough === true || escalate && (o.kind === "abstain" || o.kind === "low_confidence");
8918
+ const escalated = outcomes.filter(isEscalated).map((o) => o.fact);
8782
8919
  const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
8783
8920
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
8784
8921
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
8785
- const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
8922
+ const classifications = outcomes.filter((o) => o.kind === "accepted" && o.fallthrough !== true).map((o) => ({
8923
+ id: o.fact.id,
8924
+ okf_type: o.okfType,
8925
+ // An outcome carries `edges` only when the site is 'auto'.
8926
+ ...o.edges && o.edges.length > 0 ? { edges: o.edges, edgeCandidateIds: o.edgeCandidateIds } : {}
8927
+ }));
8786
8928
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
8787
8929
  const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
8788
8930
  let typed = 0;
@@ -8807,7 +8949,21 @@ DROP TRIGGER IF EXISTS ${ad};`);
8807
8949
  const diagBuffer = new DiagnosticBuffer();
8808
8950
  const diagBase = { entityId, operation: "ontologyBackfill", trigger };
8809
8951
  for (const o of outcomes) {
8810
- if (o.kind === "abstain") {
8952
+ if (retriedFacts.has(o.fact.id)) {
8953
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id, reason: "edge_screen_overflow_retry" } });
8954
+ }
8955
+ if (o.kind === "accepted" && o.edgeStats) {
8956
+ const { invalid, missing, allMissing } = o.edgeStats;
8957
+ const code = allMissing || invalid > 0 || missing > 0 ? "classification_invalid" : "classification_low_confidence";
8958
+ diagBuffer.push({
8959
+ ...diagBase,
8960
+ code,
8961
+ detail: {
8962
+ factId: o.fact.id,
8963
+ reason: allMissing ? "edge_answers_missing" : code === "classification_invalid" ? "edge_answer_invalid" : "edge_uncertain"
8964
+ }
8965
+ });
8966
+ } else if (o.kind === "abstain") {
8811
8967
  if (isEscalated(o)) continue;
8812
8968
  diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
8813
8969
  } else if (o.kind === "low_confidence") {
@@ -8942,16 +9098,41 @@ DROP TRIGGER IF EXISTS ${ad};`);
8942
9098
  });
8943
9099
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
8944
9100
  if (normalized.edges.length > 0) {
8945
- pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
9101
+ pendingEdges.push({
9102
+ sourceId: fact.id,
9103
+ sourceType: normalized.okf_type,
9104
+ edges: normalized.edges,
9105
+ candidateIds: classification.edgeCandidateIds
9106
+ });
8946
9107
  }
8947
9108
  }
8948
9109
  for (const item of pendingEdges) {
8949
9110
  const resolveDrops = [];
9111
+ let edgesToResolve = item.edges;
9112
+ const screenedIds = item.candidateIds;
9113
+ if (screenedIds) {
9114
+ edgesToResolve = [];
9115
+ for (const edge of item.edges) {
9116
+ const key = normalizeTitleKey(edge.target_title);
9117
+ const screened = screenedIds[key];
9118
+ if (screened !== void 0 && titleIndex.get(key)?.id !== screened) {
9119
+ resolveDrops.push({
9120
+ reason: "target_not_found",
9121
+ sourceId: item.sourceId,
9122
+ edgeType: edge.edge_type,
9123
+ sourceNodeType: item.sourceType,
9124
+ targetNodeType: null
9125
+ });
9126
+ } else {
9127
+ edgesToResolve.push(edge);
9128
+ }
9129
+ }
9130
+ }
8950
9131
  const added = await ontologyService.resolveAndPersistEdges(
8951
9132
  entityId,
8952
9133
  item.sourceId,
8953
9134
  item.sourceType,
8954
- item.edges,
9135
+ edgesToResolve,
8955
9136
  manifest,
8956
9137
  titleIndex,
8957
9138
  tx,
@@ -11608,6 +11789,6 @@ var WriteService = class {
11608
11789
  }
11609
11790
  };
11610
11791
 
11611
- 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 };
11612
- //# sourceMappingURL=chunk-RPE6OMUZ.mjs.map
11613
- //# sourceMappingURL=chunk-RPE6OMUZ.mjs.map
11792
+ 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, resolveSystemOneEdges, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11793
+ //# sourceMappingURL=chunk-KB37MGFF.mjs.map
11794
+ //# sourceMappingURL=chunk-KB37MGFF.mjs.map