@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.
@@ -4,20 +4,48 @@ import { OkfSource, OkfVerifiedEntry, OkfSourceUsageWindow } from '@equationalap
4
4
  * System-One config surface (specs/system-one-config §1, §10).
5
5
  *
6
6
  * Boundary: S1-0 owns exactly `typing`, `minConfidence` (with the `'typing'`
7
- * member), and `onLowConfidence`. Later PRs add more threshold sites
8
- * (`'edges'`, `'resolve'`, `'healScreen'`) — each as one new line in
7
+ * member), and `onLowConfidence`; the edge-suggestions step adds `edges` and
8
+ * the `'edges'` member; the resolution step adds `resolve` and the
9
+ * `'resolve'` member. Later PRs add more threshold sites
10
+ * (`'healScreen'`) — each as one new line in
9
11
  * `SystemOneThresholdSite`, so sibling PRs merge cleanly. Nothing outside
10
12
  * that boundary belongs here.
11
13
  */
12
- /** Sites a System-One threshold can apply to. Exactly one member today (§10 fence). */
13
- type SystemOneThresholdSite = 'typing';
14
+ /** Sites a System-One threshold can apply to. Exactly three members today: `'typing'`, `'edges'`, and `'resolve'` (§10 fence). */
15
+ type SystemOneThresholdSite = 'typing' | 'edges' | 'resolve';
14
16
  interface SystemOneConfig {
15
17
  /**
16
18
  * Typing mode for ontology backfill. `'auto'` uses
17
- * `llmProvider.classify` when present (no edges proposed); `'llm'`
19
+ * `llmProvider.classify` when present (no edges proposed, unless `systemOne.edges: 'auto'`); `'llm'`
18
20
  * always uses the generative path. Default `'llm'`.
19
21
  */
20
22
  typing?: 'auto' | 'llm';
23
+ /**
24
+ * Edge mode for ontology backfill. `'llm'` (default) keeps edge proposal
25
+ * on the generative path exactly as today. `'auto'` engages the classifier
26
+ * edge screen (§4) when the classifier step runs AND an explicit
27
+ * `minConfidence.edges` floor is set (§3 — missing floor under `'auto'`
28
+ * warns once and the site resolves `'llm'`); answers at or above the
29
+ * floor apply the edge, confident "no" answers are terminal, and facts
30
+ * whose edge answers land in the uncertain band fall through to the
31
+ * generative step of the same pass (§3, §5). There is no `'off'`: this PR
32
+ * adds no configuration that can silently discard a model-proposed edge.
33
+ */
34
+ edges?: 'auto' | 'llm';
35
+ /**
36
+ * Resolution mode for the librarian's ops resolve step. `'llm'` (default)
37
+ * keeps resolution on the generative path exactly as today. `'auto'`
38
+ * engages the classifier resolution screen (§4) when
39
+ * `llmProvider.classify` is present AND an explicit
40
+ * `minConfidence.resolve` floor is set (missing floor under `'auto'`
41
+ * warns once and the site resolves `'llm'`); a confident duplicate
42
+ * answer at or above the floor settles the candidate as a terminal NOOP,
43
+ * and every other answer falls through to the generative resolve of the
44
+ * same pass. An unavailable classifier warns once per process and the
45
+ * whole batch falls through. There is no `'off'`: this adds no
46
+ * configuration that can silently discard a candidate fact.
47
+ */
48
+ resolve?: 'auto' | 'llm';
21
49
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
22
50
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
23
51
  /**
@@ -4328,7 +4356,14 @@ declare class MaintenanceService {
4328
4356
  * untyped fact over the effective manifest's node-type slugs plus the
4329
4357
  * reserved abstain sentinel. Accepted answers go through
4330
4358
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
4331
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
4359
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
4360
+ * classifier screens per-fact edge questions against
4361
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
4362
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
4363
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
4364
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
4365
+ * fall through to the generative step. Edge outcomes are evaluated only for
4366
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
4332
4367
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
4333
4368
  * returned un-stamped in `escalated` for the generative step. Always
4334
4369
  * returns the `OntologyBackfillResult` for its step plus escalation state.
@@ -4,20 +4,48 @@ import { OkfSource, OkfVerifiedEntry, OkfSourceUsageWindow } from '@equationalap
4
4
  * System-One config surface (specs/system-one-config §1, §10).
5
5
  *
6
6
  * Boundary: S1-0 owns exactly `typing`, `minConfidence` (with the `'typing'`
7
- * member), and `onLowConfidence`. Later PRs add more threshold sites
8
- * (`'edges'`, `'resolve'`, `'healScreen'`) — each as one new line in
7
+ * member), and `onLowConfidence`; the edge-suggestions step adds `edges` and
8
+ * the `'edges'` member; the resolution step adds `resolve` and the
9
+ * `'resolve'` member. Later PRs add more threshold sites
10
+ * (`'healScreen'`) — each as one new line in
9
11
  * `SystemOneThresholdSite`, so sibling PRs merge cleanly. Nothing outside
10
12
  * that boundary belongs here.
11
13
  */
12
- /** Sites a System-One threshold can apply to. Exactly one member today (§10 fence). */
13
- type SystemOneThresholdSite = 'typing';
14
+ /** Sites a System-One threshold can apply to. Exactly three members today: `'typing'`, `'edges'`, and `'resolve'` (§10 fence). */
15
+ type SystemOneThresholdSite = 'typing' | 'edges' | 'resolve';
14
16
  interface SystemOneConfig {
15
17
  /**
16
18
  * Typing mode for ontology backfill. `'auto'` uses
17
- * `llmProvider.classify` when present (no edges proposed); `'llm'`
19
+ * `llmProvider.classify` when present (no edges proposed, unless `systemOne.edges: 'auto'`); `'llm'`
18
20
  * always uses the generative path. Default `'llm'`.
19
21
  */
20
22
  typing?: 'auto' | 'llm';
23
+ /**
24
+ * Edge mode for ontology backfill. `'llm'` (default) keeps edge proposal
25
+ * on the generative path exactly as today. `'auto'` engages the classifier
26
+ * edge screen (§4) when the classifier step runs AND an explicit
27
+ * `minConfidence.edges` floor is set (§3 — missing floor under `'auto'`
28
+ * warns once and the site resolves `'llm'`); answers at or above the
29
+ * floor apply the edge, confident "no" answers are terminal, and facts
30
+ * whose edge answers land in the uncertain band fall through to the
31
+ * generative step of the same pass (§3, §5). There is no `'off'`: this PR
32
+ * adds no configuration that can silently discard a model-proposed edge.
33
+ */
34
+ edges?: 'auto' | 'llm';
35
+ /**
36
+ * Resolution mode for the librarian's ops resolve step. `'llm'` (default)
37
+ * keeps resolution on the generative path exactly as today. `'auto'`
38
+ * engages the classifier resolution screen (§4) when
39
+ * `llmProvider.classify` is present AND an explicit
40
+ * `minConfidence.resolve` floor is set (missing floor under `'auto'`
41
+ * warns once and the site resolves `'llm'`); a confident duplicate
42
+ * answer at or above the floor settles the candidate as a terminal NOOP,
43
+ * and every other answer falls through to the generative resolve of the
44
+ * same pass. An unavailable classifier warns once per process and the
45
+ * whole batch falls through. There is no `'off'`: this adds no
46
+ * configuration that can silently discard a candidate fact.
47
+ */
48
+ resolve?: 'auto' | 'llm';
21
49
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
22
50
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
23
51
  /**
@@ -4328,7 +4356,14 @@ declare class MaintenanceService {
4328
4356
  * untyped fact over the effective manifest's node-type slugs plus the
4329
4357
  * reserved abstain sentinel. Accepted answers go through
4330
4358
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
4331
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
4359
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
4360
+ * classifier screens per-fact edge questions against
4361
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
4362
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
4363
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
4364
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
4365
+ * fall through to the generative step. Edge outcomes are evaluated only for
4366
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
4332
4367
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
4333
4368
  * returned un-stamped in `escalated` for the generative step. Always
4334
4369
  * returns the `OntologyBackfillResult` for its step plus escalation state.
@@ -1,2 +1,2 @@
1
- export { a_ as EmbeddingService, a$ as ImportExportService, b0 as IngestionService, b1 as JobManager, b1 as JobManagerType, b2 as MaintenanceService, b3 as RetrievalService, b4 as SearchService, b4 as SearchServiceType, aL as WikiMemoryTestAccess, b5 as WriteService } from './testing-DFyghdSG.mjs';
1
+ export { a_ as EmbeddingService, a$ as ImportExportService, b0 as IngestionService, b1 as JobManager, b1 as JobManagerType, b2 as MaintenanceService, b3 as RetrievalService, b4 as SearchService, b4 as SearchServiceType, aL as WikiMemoryTestAccess, b5 as WriteService } from './testing-DkKZcrhE.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { a_ as EmbeddingService, a$ as ImportExportService, b0 as IngestionService, b1 as JobManager, b1 as JobManagerType, b2 as MaintenanceService, b3 as RetrievalService, b4 as SearchService, b4 as SearchServiceType, aL as WikiMemoryTestAccess, b5 as WriteService } from './testing-DFyghdSG.js';
1
+ export { a_ as EmbeddingService, a$ as ImportExportService, b0 as IngestionService, b1 as JobManager, b1 as JobManagerType, b2 as MaintenanceService, b3 as RetrievalService, b4 as SearchService, b4 as SearchServiceType, aL as WikiMemoryTestAccess, b5 as WriteService } from './testing-DkKZcrhE.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -4116,6 +4116,26 @@ function resolveSystemOneTyping(config, classifierCallOption) {
4116
4116
  }
4117
4117
  return classifierCallOption ?? (systemOneValid ? systemOne.typing : void 0) ?? (legacyValid ? legacy : void 0) ?? "llm";
4118
4118
  }
4119
+ function resolveSystemOneEdges(config) {
4120
+ const edges = config?.systemOne?.edges;
4121
+ if (edges !== void 0 && !isTypingMode(edges)) {
4122
+ warnOnce(
4123
+ `[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.`
4124
+ );
4125
+ return "llm";
4126
+ }
4127
+ return edges ?? "llm";
4128
+ }
4129
+ function resolveSystemOneResolve(config) {
4130
+ const resolve = config?.systemOne?.resolve;
4131
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
4132
+ warnOnce(
4133
+ `[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.`
4134
+ );
4135
+ return "llm";
4136
+ }
4137
+ return resolve ?? "llm";
4138
+ }
4119
4139
  var DEFAULT_SHORTLIST_K = 10;
4120
4140
  function resolveShortlistK(config) {
4121
4141
  const k = config?.ontology?.shortlistK;
@@ -4145,6 +4165,25 @@ function resolveTypingMinConfidence(config) {
4145
4165
  }
4146
4166
  return (systemOneValid ? systemOneFloor : void 0) ?? (legacyValid ? legacyFloor : void 0) ?? DEFAULT_TYPING_MIN_CONFIDENCE;
4147
4167
  }
4168
+ var isEdgesFloor = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0.5 && v <= 1;
4169
+ function resolveEdgesMinConfidence(config) {
4170
+ if (resolveSystemOneEdges(config) !== "auto") return void 0;
4171
+ const floor = config?.systemOne?.minConfidence?.edges;
4172
+ if (isEdgesFloor(floor)) return floor;
4173
+ warnOnce(
4174
+ 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.`
4175
+ );
4176
+ return void 0;
4177
+ }
4178
+ function resolveResolveMinConfidence(config) {
4179
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
4180
+ const floor = config?.systemOne?.minConfidence?.resolve;
4181
+ if (isEdgesFloor(floor)) return floor;
4182
+ warnOnce(
4183
+ 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.`
4184
+ );
4185
+ return void 0;
4186
+ }
4148
4187
 
4149
4188
  // src/utils/embedding.ts
4150
4189
  function parseEmbedding(blob, text) {
@@ -5562,6 +5601,46 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
5562
5601
  }
5563
5602
 
5564
5603
  // src/services/librarian/ops/resolve.ts
5604
+ async function screenResolveCandidates(ambiguous, mode, floor, ask) {
5605
+ const whole = (warnReason) => warnReason ? { settled: /* @__PURE__ */ new Map(), rest: ambiguous, warnReason } : { settled: /* @__PURE__ */ new Map(), rest: ambiguous };
5606
+ if (mode !== "auto") return whole();
5607
+ if (floor === void 0) return whole("no-floor");
5608
+ if (!ask) return whole("no-classifier");
5609
+ const settled = /* @__PURE__ */ new Map();
5610
+ const rest = [];
5611
+ for (const g of ambiguous) {
5612
+ const best = g.neighbours[0];
5613
+ if (!best) {
5614
+ rest.push(g);
5615
+ continue;
5616
+ }
5617
+ const question = {
5618
+ kind: "binary",
5619
+ instructions: `Does this candidate add NO information beyond neighbour ${best.ref} (a pure duplicate: same claims, no new content)?
5620
+ Neighbour ${best.ref} title: ${best.title}
5621
+ Neighbour ${best.ref} body: ${safeSlice(best.body, 0, OPS_NEIGHBOUR_BODY_CHARS)}`
5622
+ };
5623
+ let response;
5624
+ try {
5625
+ response = await ask({
5626
+ state: classifierStateForFact({ title: g.candidate.fact.title, body: g.candidate.fact.body, tags: [] }),
5627
+ questions: { [best.ref]: question }
5628
+ });
5629
+ } catch (err) {
5630
+ if (err instanceof WikiBudgetExhausted) {
5631
+ return { settled: /* @__PURE__ */ new Map(), rest: ambiguous, budgetStop: { requiredEstimate: err.requiredEstimate } };
5632
+ }
5633
+ return whole("classifier-threw");
5634
+ }
5635
+ const checked = validateClassifierAnswer(response, best.ref, question);
5636
+ if (checked.ok && checked.answer.kind === "binary" && checked.answer.probability >= floor) {
5637
+ settled.set(g, { op: "NOOP", targetId: best.id });
5638
+ } else {
5639
+ rest.push(g);
5640
+ }
5641
+ }
5642
+ return { settled, rest };
5643
+ }
5565
5644
  function validateOp(raw, aliases) {
5566
5645
  if (!raw || typeof raw !== "object") return null;
5567
5646
  const r = raw;
@@ -5581,11 +5660,31 @@ function validateOp(raw, aliases) {
5581
5660
  }
5582
5661
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5583
5662
  async function runResolve(deps, ctx, ambiguous, budget) {
5584
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
5663
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [], classifierSettled: [] };
5585
5664
  if (ambiguous.length === 0) return out;
5586
5665
  const { entityId, trigger } = ctx;
5666
+ const mode = resolveSystemOneResolve(deps.options.config);
5667
+ const floor = resolveResolveMinConfidence(deps.options.config);
5668
+ const provider = deps.options.llmProvider;
5669
+ const ask = mode === "auto" && typeof provider.classify === "function" ? (request) => callClassify(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, request) : void 0;
5670
+ const screen = await screenResolveCandidates(ambiguous, mode, floor, ask);
5671
+ if (screen.budgetStop) return { ...out, budgetStop: screen.budgetStop };
5672
+ if (screen.warnReason === "no-classifier") {
5673
+ warnOnce(
5674
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but the provider has no classify(); ambiguous candidates fall through to the generative resolve."
5675
+ );
5676
+ } else if (screen.warnReason === "classifier-threw") {
5677
+ warnOnce(
5678
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but classify() threw during the resolve screen; ambiguous candidates fall through to the generative resolve."
5679
+ );
5680
+ }
5681
+ for (const [g, op] of screen.settled) {
5682
+ out.ops.set(g, op);
5683
+ out.classifierSettled.push(g.candidate.index);
5684
+ }
5685
+ if (screen.rest.length === 0) return out;
5587
5686
  const outcome = await runBatched({
5588
- items: ambiguous,
5687
+ items: screen.rest,
5589
5688
  buildPrompt: (batch) => deps.promptService.buildOpsResolvePrompt(
5590
5689
  batch.map((g, i) => ({
5591
5690
  item: i,
@@ -5874,6 +5973,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5874
5973
  // (index into the merged extract batch)
5875
5974
  });
5876
5975
  }
5976
+ for (const itemIndex of res.classifierSettled) {
5977
+ diagnostics.push({
5978
+ entityId,
5979
+ operation: "librarian",
5980
+ trigger,
5981
+ code: "fact_deduplicated",
5982
+ detail: { itemIndex, reason: "classifier" }
5983
+ // (index into the merged extract batch)
5984
+ });
5985
+ }
5877
5986
  if (res.budgetStop) {
5878
5987
  diagnostics.discard();
5879
5988
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -7424,7 +7533,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7424
7533
  return { ...zeroed, remaining: counts.eligible, deferred: counts.deferred };
7425
7534
  }
7426
7535
  const classifierMode = resolveSystemOneTyping(this.options.config, options?.classifier);
7536
+ const edgeMode = resolveSystemOneEdges(this.options.config);
7427
7537
  const classify = this.options.llmProvider.classify;
7538
+ const edgeMinConfidence = edgeMode === "auto" && classifierMode === "auto" && typeof classify === "function" ? resolveEdgesMinConfidence(this.options.config) : void 0;
7539
+ const edgeSiteMode = edgeMode === "auto" && typeof edgeMinConfidence === "number" ? "auto" : "llm";
7428
7540
  if (classifierMode === "auto" && typeof classify === "function") {
7429
7541
  const slugs = effectiveManifest.node_types.map((n) => n.type);
7430
7542
  if (slugs.length > 0 && slugs.length + 1 <= CLASSIFIER_MAX_CHOICES && !slugs.some((s) => isReservedAbstainSlug(s))) {
@@ -7435,16 +7547,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
7435
7547
  now,
7436
7548
  recheckCutoff,
7437
7549
  options?.meter,
7438
- trigger
7550
+ trigger,
7551
+ shortlistK,
7552
+ edgeSiteMode,
7553
+ edgeMinConfidence
7439
7554
  );
7440
7555
  if (classifierRun.abortedOntologyOff || classifierRun.result.budgetStop) {
7441
7556
  return classifierRun.result;
7442
7557
  }
7443
- if (classifierRun.escalated.length > 0 && this.resolveSystemOneOnLowConfidence() === "llm") {
7558
+ if (classifierRun.escalated.length > 0) {
7444
7559
  const { mode: liveMode } = await ontologyService.getEffectiveState(entityId);
7445
7560
  if (liveMode === "off") {
7446
7561
  const counts = await this.entryRepo.countUntypedByEntityId(entityId, recheckCutoff);
7447
- return { ...zeroed, remaining: 0, deferred: counts.deferred };
7562
+ const committed = classifierRun.result;
7563
+ return {
7564
+ scanned: committed.scanned,
7565
+ typed: committed.typed,
7566
+ failedValidation: committed.failedValidation,
7567
+ edgesAdded: committed.edgesAdded,
7568
+ abstained: committed.abstained,
7569
+ skipped: committed.skipped,
7570
+ remaining: 0,
7571
+ deferred: counts.deferred
7572
+ };
7448
7573
  }
7449
7574
  const escalated = classifierRun.escalated;
7450
7575
  const generative = await this._runGenerativeBackfill(entityId, escalated, {
@@ -7454,7 +7579,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7454
7579
  batchSize: escalated.length,
7455
7580
  recheckCutoff,
7456
7581
  shortlistK,
7457
- maxPromptChars
7582
+ maxPromptChars,
7583
+ edgeSiteMode,
7584
+ edgeMinConfidence
7458
7585
  });
7459
7586
  return {
7460
7587
  scanned: classifierRun.result.scanned,
@@ -7477,7 +7604,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7477
7604
  trigger,
7478
7605
  recheckCutoff,
7479
7606
  shortlistK,
7480
- maxPromptChars
7607
+ maxPromptChars,
7608
+ edgeSiteMode,
7609
+ edgeMinConfidence
7481
7610
  });
7482
7611
  }
7483
7612
  /**
@@ -7513,6 +7642,9 @@ DROP TRIGGER IF EXISTS ${ad};`);
7513
7642
  if (maxPromptChars === void 0) {
7514
7643
  throw new Error("_runGenerativeBackfill: runOpts.maxPromptChars is required (resolved at doRunOntologyBackfill entry)");
7515
7644
  }
7645
+ if (runOpts.edgeSiteMode === void 0) {
7646
+ throw new Error("_runGenerativeBackfill: runOpts.edgeSiteMode is required (resolved at doRunOntologyBackfill entry)");
7647
+ }
7516
7648
  const ontologyService = this.ontologyService;
7517
7649
  const now = Date.now();
7518
7650
  const recheckCutoff = runOpts.recheckCutoff;
@@ -7640,12 +7772,19 @@ DROP TRIGGER IF EXISTS ${ad};`);
7640
7772
  * untyped fact over the effective manifest's node-type slugs plus the
7641
7773
  * reserved abstain sentinel. Accepted answers go through
7642
7774
  * `_applyOntologyBackfillBatch` exactly like LLM classifications. No edges
7643
- * are proposed. Abstains and low-confidence answers are cooldown-stamped
7775
+ * are proposed unless `systemOne.edges` is `'auto'`; under `'auto'` the
7776
+ * classifier screens per-fact edge questions against
7777
+ * `systemOne.minConfidence.edges` (an explicit floor; missing → warn and
7778
+ * `'llm'`). Confident "yes" answers (`p > 0.5 && p >= floor`) apply,
7779
+ * confident "no" answers (`p < 0.5 && 1 - p >= floor`) are terminal, and
7780
+ * everything else (including exactly `p = 0.5`) plus invalid edge answers
7781
+ * fall through to the generative step. Edge outcomes are evaluated only for
7782
+ * typing-ACCEPTED facts. Abstains and low-confidence answers are cooldown-stamped
7644
7783
  * omissions under `onLowConfidence: 'leave'`; under `'llm'` they are
7645
7784
  * returned un-stamped in `escalated` for the generative step. Always
7646
7785
  * returns the `OntologyBackfillResult` for its step plus escalation state.
7647
7786
  */
7648
- async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger) {
7787
+ async _runClassifierBackfill(entityId, candidates, manifest, now, recheckCutoff, meter, trigger, shortlistK, edgeSiteMode, edgeMinConfidence) {
7649
7788
  const minConfidence = resolveTypingMinConfidence(this.options.config);
7650
7789
  const rawConcurrency = this.options.config?.chunkConcurrency ?? 1;
7651
7790
  const concurrency = Number.isFinite(rawConcurrency) && rawConcurrency >= 1 ? Math.floor(rawConcurrency) : 1;
@@ -7655,17 +7794,65 @@ DROP TRIGGER IF EXISTS ${ad};`);
7655
7794
  instructions: `Choose the ontology node type that best describes this fact, or choose "${ONTOLOGY_ABSTAIN_SENTINEL}" if none of the listed types fits.
7656
7795
  ` + manifest.node_types.map((n) => `- ${n.type}: ${n.description}`).join("\n")
7657
7796
  };
7797
+ const edgeScreen = /* @__PURE__ */ new Map();
7798
+ if (edgeSiteMode === "auto" && (manifest.edge_types ?? []).length > 0) {
7799
+ const pool = await this.entryRepo.findShortlistRowsByEntityId(entityId);
7800
+ const poolTitleCounts = /* @__PURE__ */ new Map();
7801
+ for (const r of pool) {
7802
+ const k = normalizeTitleKey(r.title);
7803
+ poolTitleCounts.set(k, (poolTitleCounts.get(k) ?? 0) + 1);
7804
+ }
7805
+ const batchTitleKeys = new Set(candidates.map((f) => normalizeTitleKey(f.title)));
7806
+ const collides = (title) => {
7807
+ const k = normalizeTitleKey(title);
7808
+ return (poolTitleCounts.get(k) ?? 0) > 1 || batchTitleKeys.has(k);
7809
+ };
7810
+ const scorer = createShortlistScorer(pool);
7811
+ const edgeTypeNames = [...new Set(manifest.edge_types.map((e) => e.type))];
7812
+ for (const fact of candidates) {
7813
+ const ranked = buildShortlist({ title: fact.title, body: fact.body }, pool, shortlistK, scorer).filter((row) => !collides(row.title));
7814
+ const questions = {};
7815
+ const keyMap = /* @__PURE__ */ new Map();
7816
+ for (const row of ranked) {
7817
+ for (const edgeType of edgeTypeNames) {
7818
+ const definitions = manifest.edge_types.filter(
7819
+ (e) => e.type === edgeType && typeSatisfies(e.target_type, row.okf_type, manifest)
7820
+ );
7821
+ if (definitions.length === 0) continue;
7822
+ const key = `edge:${edgeType}:${row.id}`;
7823
+ const descriptions = [...new Set(definitions.map((d) => d.description))].join(" / ");
7824
+ questions[key] = {
7825
+ kind: "binary",
7826
+ instructions: `Does this fact have the "${edgeType}" relationship (${descriptions}) to the existing fact titled "${row.title}"?`
7827
+ };
7828
+ keyMap.set(key, { definitions, candidate: { id: row.id, title: row.title, okf_type: row.okf_type } });
7829
+ }
7830
+ }
7831
+ if (keyMap.size > 0) edgeScreen.set(fact.id, { questions, keyMap });
7832
+ }
7833
+ }
7658
7834
  let stopped;
7835
+ const retriedFacts = /* @__PURE__ */ new Set();
7659
7836
  const outcomes = await withConcurrency(
7660
7837
  candidates.map((fact) => async () => {
7661
7838
  if (stopped) return { fact, kind: "unattempted" };
7839
+ const edgeEntry = edgeScreen.get(fact.id);
7840
+ const ask = (questions) => callClassify(
7841
+ this.options,
7842
+ { operation: "ontologyBackfill", entityId, trigger, meter },
7843
+ { state: classifierStateForFact(fact), questions }
7844
+ );
7662
7845
  let response;
7846
+ let screened = edgeEntry !== void 0;
7663
7847
  try {
7664
- response = await callClassify(
7665
- this.options,
7666
- { operation: "ontologyBackfill", entityId, trigger, meter },
7667
- { state: classifierStateForFact(fact), questions: { okf_type: question } }
7668
- );
7848
+ try {
7849
+ response = await ask({ okf_type: question, ...edgeEntry?.questions ?? {} });
7850
+ } catch (err) {
7851
+ if (!edgeEntry || err instanceof WikiBudgetExhausted || !isContextOverflowError(err)) throw err;
7852
+ response = await ask({ okf_type: question });
7853
+ screened = false;
7854
+ retriedFacts.add(fact.id);
7855
+ }
7669
7856
  } catch (err) {
7670
7857
  if (err instanceof WikiBudgetExhausted) {
7671
7858
  stopped ?? (stopped = err);
@@ -7679,17 +7866,54 @@ DROP TRIGGER IF EXISTS ${ad};`);
7679
7866
  if (checked.answer.kind !== "choice") return { fact, kind: "invalid", reason: "kind_mismatch" };
7680
7867
  if (isReservedAbstainSlug(checked.answer.choice)) return { fact, kind: "abstain" };
7681
7868
  if (checked.answer.confidence < minConfidence) return { fact, kind: "low_confidence" };
7682
- return { fact, kind: "accepted", okfType: checked.answer.choice };
7869
+ const okfType = checked.answer.choice;
7870
+ if (!screened || !edgeEntry || typeof edgeMinConfidence !== "number") return { fact, kind: "accepted", okfType };
7871
+ const floor = edgeMinConfidence;
7872
+ const edges = [];
7873
+ const edgeCandidateIds = /* @__PURE__ */ Object.create(null);
7874
+ let evaluated = 0;
7875
+ let uncertain = 0;
7876
+ let invalid = 0;
7877
+ let missing = 0;
7878
+ for (const [key, { definitions, candidate }] of edgeEntry.keyMap) {
7879
+ if (!definitions.some((d) => typeSatisfies(d.source_type, okfType, manifest))) continue;
7880
+ evaluated++;
7881
+ const answer = validateClassifierAnswer(response, key, edgeEntry.questions[key]);
7882
+ if (!answer.ok) {
7883
+ if (answer.reason === "missing_answer") missing++;
7884
+ else invalid++;
7885
+ continue;
7886
+ }
7887
+ if (answer.answer.kind !== "binary") {
7888
+ invalid++;
7889
+ continue;
7890
+ }
7891
+ const p = answer.answer.probability;
7892
+ if (p > 0.5 && p >= floor) {
7893
+ edges.push({ edge_type: definitions[0].type, target_title: candidate.title });
7894
+ edgeCandidateIds[normalizeTitleKey(candidate.title)] = candidate.id;
7895
+ } else if (p < 0.5 && 1 - p >= floor) continue;
7896
+ else uncertain++;
7897
+ }
7898
+ const edgeStats = { uncertain, invalid, missing, allMissing: evaluated > 0 && missing === evaluated };
7899
+ if (edgeStats.allMissing) return { fact, kind: "accepted", okfType, edgeStats };
7900
+ if (uncertain > 0 || invalid > 0 || missing > 0) return { fact, kind: "accepted", okfType, fallthrough: true, edgeStats };
7901
+ return { fact, kind: "accepted", okfType, ...edges.length > 0 ? { edges, edgeCandidateIds } : {} };
7683
7902
  }),
7684
7903
  concurrency
7685
7904
  );
7686
7905
  const escalate = this.resolveSystemOneOnLowConfidence() === "llm";
7687
- const escalated = escalate ? outcomes.filter((o) => o.kind === "abstain" || o.kind === "low_confidence").map((o) => o.fact) : [];
7688
- const isEscalated = (o) => escalate && (o.kind === "abstain" || o.kind === "low_confidence");
7906
+ const isEscalated = (o) => o.kind === "accepted" && o.fallthrough === true || escalate && (o.kind === "abstain" || o.kind === "low_confidence");
7907
+ const escalated = outcomes.filter(isEscalated).map((o) => o.fact);
7689
7908
  const attempted = outcomes.filter((o) => o.kind !== "threw" && o.kind !== "unattempted" && !isEscalated(o)).map((o) => o.fact);
7690
7909
  const unattemptedCount = outcomes.filter((o) => o.kind === "unattempted").length;
7691
7910
  const skipped = outcomes.filter((o) => o.kind === "threw" || o.kind === "overflow_skip").length;
7692
- const classifications = outcomes.filter((o) => o.kind === "accepted").map((o) => ({ id: o.fact.id, okf_type: o.okfType }));
7911
+ const classifications = outcomes.filter((o) => o.kind === "accepted" && o.fallthrough !== true).map((o) => ({
7912
+ id: o.fact.id,
7913
+ okf_type: o.okfType,
7914
+ // An outcome carries `edges` only when the site is 'auto'.
7915
+ ...o.edges && o.edges.length > 0 ? { edges: o.edges, edgeCandidateIds: o.edgeCandidateIds } : {}
7916
+ }));
7693
7917
  const invalidCount = outcomes.filter((o) => o.kind === "invalid").length;
7694
7918
  const abstainCount = outcomes.filter((o) => o.kind === "abstain" && !isEscalated(o)).length;
7695
7919
  let typed = 0;
@@ -7714,7 +7938,21 @@ DROP TRIGGER IF EXISTS ${ad};`);
7714
7938
  const diagBuffer = new DiagnosticBuffer();
7715
7939
  const diagBase = { entityId, operation: "ontologyBackfill", trigger };
7716
7940
  for (const o of outcomes) {
7717
- if (o.kind === "abstain") {
7941
+ if (retriedFacts.has(o.fact.id)) {
7942
+ diagBuffer.push({ ...diagBase, code: "context_overflow_skipped", detail: { factId: o.fact.id, reason: "edge_screen_overflow_retry" } });
7943
+ }
7944
+ if (o.kind === "accepted" && o.edgeStats) {
7945
+ const { invalid, missing, allMissing } = o.edgeStats;
7946
+ const code = allMissing || invalid > 0 || missing > 0 ? "classification_invalid" : "classification_low_confidence";
7947
+ diagBuffer.push({
7948
+ ...diagBase,
7949
+ code,
7950
+ detail: {
7951
+ factId: o.fact.id,
7952
+ reason: allMissing ? "edge_answers_missing" : code === "classification_invalid" ? "edge_answer_invalid" : "edge_uncertain"
7953
+ }
7954
+ });
7955
+ } else if (o.kind === "abstain") {
7718
7956
  if (isEscalated(o)) continue;
7719
7957
  diagBuffer.push({ ...diagBase, code: "classification_abstained", detail: { factId: o.fact.id, writer: "classifier" } });
7720
7958
  } else if (o.kind === "low_confidence") {
@@ -7849,16 +8087,41 @@ DROP TRIGGER IF EXISTS ${ad};`);
7849
8087
  });
7850
8088
  titleIndex.set(normalizeTitleKey(fact.title), { id: fact.id, okf_type: normalized.okf_type });
7851
8089
  if (normalized.edges.length > 0) {
7852
- pendingEdges.push({ sourceId: fact.id, sourceType: normalized.okf_type, edges: normalized.edges });
8090
+ pendingEdges.push({
8091
+ sourceId: fact.id,
8092
+ sourceType: normalized.okf_type,
8093
+ edges: normalized.edges,
8094
+ candidateIds: classification.edgeCandidateIds
8095
+ });
7853
8096
  }
7854
8097
  }
7855
8098
  for (const item of pendingEdges) {
7856
8099
  const resolveDrops = [];
8100
+ let edgesToResolve = item.edges;
8101
+ const screenedIds = item.candidateIds;
8102
+ if (screenedIds) {
8103
+ edgesToResolve = [];
8104
+ for (const edge of item.edges) {
8105
+ const key = normalizeTitleKey(edge.target_title);
8106
+ const screened = screenedIds[key];
8107
+ if (screened !== void 0 && titleIndex.get(key)?.id !== screened) {
8108
+ resolveDrops.push({
8109
+ reason: "target_not_found",
8110
+ sourceId: item.sourceId,
8111
+ edgeType: edge.edge_type,
8112
+ sourceNodeType: item.sourceType,
8113
+ targetNodeType: null
8114
+ });
8115
+ } else {
8116
+ edgesToResolve.push(edge);
8117
+ }
8118
+ }
8119
+ }
7857
8120
  const added = await ontologyService.resolveAndPersistEdges(
7858
8121
  entityId,
7859
8122
  item.sourceId,
7860
8123
  item.sourceType,
7861
- item.edges,
8124
+ edgesToResolve,
7862
8125
  manifest,
7863
8126
  titleIndex,
7864
8127
  tx,