@equationalapplications/core-llm-wiki 9.12.0 → 9.14.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.
@@ -5,13 +5,14 @@ import { OkfSource, OkfVerifiedEntry, OkfSourceUsageWindow } from '@equationalap
5
5
  *
6
6
  * Boundary: S1-0 owns exactly `typing`, `minConfidence` (with the `'typing'`
7
7
  * member), and `onLowConfidence`; the edge-suggestions step adds `edges` and
8
- * the `'edges'` member. Later PRs add more threshold sites
9
- * (`'resolve'`, `'healScreen'`) — each as one new line in
10
- * `SystemOneThresholdSite`, so sibling PRs merge cleanly. Nothing outside
8
+ * the `'edges'` member; the resolution step added the `'resolve'` member and
9
+ * the heal-screen step added the `'healScreen'` member. Each landed as one
10
+ * new line in
11
+ * `SystemOneThresholdSite`, so sibling PRs merged cleanly. Nothing outside
11
12
  * that boundary belongs here.
12
13
  */
13
- /** Sites a System-One threshold can apply to. Exactly two members today: `'typing'` and `'edges'` (§10 fence). */
14
- type SystemOneThresholdSite = 'typing' | 'edges';
14
+ /** Sites a System-One threshold can apply to. Exactly four members today: `'typing'`, `'edges'`, `'resolve'` and `'healScreen'` (§10 fence). */
15
+ type SystemOneThresholdSite = 'typing' | 'edges' | 'resolve' | 'healScreen';
15
16
  interface SystemOneConfig {
16
17
  /**
17
18
  * Typing mode for ontology backfill. `'auto'` uses
@@ -31,6 +32,34 @@ interface SystemOneConfig {
31
32
  * adds no configuration that can silently discard a model-proposed edge.
32
33
  */
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';
49
+ /**
50
+ * Heal-screen mode. `'llm'` (default) keeps heal exactly as today: every
51
+ * model-directed verdict the mutable-ids guard admits is applied, no
52
+ * confidence is read. `'auto'` floors each model-directed downgrade and
53
+ * delete on the confidence the model declares in its verdict (§4): at or
54
+ * above the `minConfidence.healScreen` floor the verdict applies with a
55
+ * per-fact receipt (§5); below it the verdict is withheld — the fact is
56
+ * left untouched, never silently discarded, and the withheld move is
57
+ * itself receipted (§5). The deterministic SQL passes (orphan-marking,
58
+ * stale-inferred downgrade) are rule-driven host policy and are NEVER
59
+ * gated by this key (§4). There is no `'off'`: this PR adds no
60
+ * configuration that can silently discard a model-directed heal action.
61
+ */
62
+ healScreen?: 'auto' | 'llm';
34
63
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
35
64
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
36
65
  /**
@@ -250,6 +279,25 @@ interface HealResult {
250
279
  downgraded: number;
251
280
  /** Facts soft-deleted — the orphan-marking SQL pass plus model-directed deletes, deduped. */
252
281
  deleted: number;
282
+ /**
283
+ * Every fact id this heal run left at reduced confidence (stale-inferred
284
+ * SQL pass plus model-directed downgrades, deduped) — the ids behind
285
+ * `downgraded`. Optional so existing `HealResult` literals (host mocks)
286
+ * keep compiling; `doRunHeal` always populates it today. NOT disjoint
287
+ * with `deletedIds`: a fact both downgraded and deleted in one pass
288
+ * appears in BOTH lists (union-not-sum semantics — see the
289
+ * `allDowngraded` / `allDeleted` unions in `doRunHeal`) — hosts must not
290
+ * treat the lists as disjoint.
291
+ */
292
+ downgradedIds?: string[];
293
+ /**
294
+ * Every fact id this heal run soft-deleted (orphan SQL pass plus
295
+ * model-directed deletes, deduped) — the ids behind `deleted`. Optional
296
+ * so existing `HealResult` literals (host mocks) keep compiling;
297
+ * `doRunHeal` always populates it today. NOT disjoint with
298
+ * `downgradedIds` (see above).
299
+ */
300
+ deletedIds?: string[];
253
301
  /** New facts synthesized by heal. */
254
302
  newFactsCreated: number;
255
303
  /**
@@ -437,7 +485,7 @@ interface WikiConfig {
437
485
  * System-One config surface (specs/system-one-config §1): typing mode,
438
486
  * per-site confidence floor, and low-confidence routing. Resolution chains
439
487
  * live in `utils/engineDefaults.ts` (`resolveSystemOneTyping`,
440
- * `resolveTypingMinConfidence`).
488
+ * `resolveTypingMinConfidence`, `resolveSystemOneHealScreen`, `resolveHealScreenMinConfidence`).
441
489
  */
442
490
  systemOne?: SystemOneConfig;
443
491
  /** Default node cap for traverseGraph(), unless overridden per-call. Default 20. */
@@ -960,7 +1008,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
960
1008
  * Closed for this release series, but new codes are added in minor versions:
961
1009
  * hosts must tolerate codes they do not recognize.
962
1010
  */
963
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'classification_abstained' | 'node_type_assigned' | 'context_overflow_skipped' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'ontology_backfill_held' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable' | 'node_type_dropped' | 'node_type_folded' | 'ontology_update_rejected' | 'ingest_zero_facts';
1011
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'heal_deleted' | 'heal_downgraded' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'classification_abstained' | 'node_type_assigned' | 'context_overflow_skipped' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'ontology_backfill_held' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable' | 'node_type_dropped' | 'node_type_folded' | 'ontology_update_rejected' | 'ingest_zero_facts';
964
1012
  /** The service run that emitted the diagnostic. */
965
1013
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
966
1014
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -4301,6 +4349,17 @@ declare class MaintenanceService {
4301
4349
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
4302
4350
  * for what convergence means here, and for the no-progress flags
4303
4351
  * (`searchUnavailable`, `budgetStop`) a loop must also stop on.
4352
+ *
4353
+ * Heal screen (`systemOne.healScreen: 'auto'` + `minConfidence.healScreen`):
4354
+ * a model-directed delete or downgrade whose valid `confidence` is below the
4355
+ * floor is withheld from every reader (apply, sync, removals, counts, id
4356
+ * lists); a missing or invalid confidence is applied unscreened. Each
4357
+ * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
4358
+ * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
4359
+ * mode. An `applied` receipt records that the model VERDICT was applied
4360
+ * (`downgradeByIds` runs unconditionally): a fact that was already at
4361
+ * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
4362
+ * live and the restatement is skipped as `fact_deduplicated`.
4304
4363
  */
4305
4364
  doRunHeal(entityId: string, options?: {
4306
4365
  promptOverride?: string;
@@ -5,13 +5,14 @@ import { OkfSource, OkfVerifiedEntry, OkfSourceUsageWindow } from '@equationalap
5
5
  *
6
6
  * Boundary: S1-0 owns exactly `typing`, `minConfidence` (with the `'typing'`
7
7
  * member), and `onLowConfidence`; the edge-suggestions step adds `edges` and
8
- * the `'edges'` member. Later PRs add more threshold sites
9
- * (`'resolve'`, `'healScreen'`) — each as one new line in
10
- * `SystemOneThresholdSite`, so sibling PRs merge cleanly. Nothing outside
8
+ * the `'edges'` member; the resolution step added the `'resolve'` member and
9
+ * the heal-screen step added the `'healScreen'` member. Each landed as one
10
+ * new line in
11
+ * `SystemOneThresholdSite`, so sibling PRs merged cleanly. Nothing outside
11
12
  * that boundary belongs here.
12
13
  */
13
- /** Sites a System-One threshold can apply to. Exactly two members today: `'typing'` and `'edges'` (§10 fence). */
14
- type SystemOneThresholdSite = 'typing' | 'edges';
14
+ /** Sites a System-One threshold can apply to. Exactly four members today: `'typing'`, `'edges'`, `'resolve'` and `'healScreen'` (§10 fence). */
15
+ type SystemOneThresholdSite = 'typing' | 'edges' | 'resolve' | 'healScreen';
15
16
  interface SystemOneConfig {
16
17
  /**
17
18
  * Typing mode for ontology backfill. `'auto'` uses
@@ -31,6 +32,34 @@ interface SystemOneConfig {
31
32
  * adds no configuration that can silently discard a model-proposed edge.
32
33
  */
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';
49
+ /**
50
+ * Heal-screen mode. `'llm'` (default) keeps heal exactly as today: every
51
+ * model-directed verdict the mutable-ids guard admits is applied, no
52
+ * confidence is read. `'auto'` floors each model-directed downgrade and
53
+ * delete on the confidence the model declares in its verdict (§4): at or
54
+ * above the `minConfidence.healScreen` floor the verdict applies with a
55
+ * per-fact receipt (§5); below it the verdict is withheld — the fact is
56
+ * left untouched, never silently discarded, and the withheld move is
57
+ * itself receipted (§5). The deterministic SQL passes (orphan-marking,
58
+ * stale-inferred downgrade) are rule-driven host policy and are NEVER
59
+ * gated by this key (§4). There is no `'off'`: this PR adds no
60
+ * configuration that can silently discard a model-directed heal action.
61
+ */
62
+ healScreen?: 'auto' | 'llm';
34
63
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
35
64
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
36
65
  /**
@@ -250,6 +279,25 @@ interface HealResult {
250
279
  downgraded: number;
251
280
  /** Facts soft-deleted — the orphan-marking SQL pass plus model-directed deletes, deduped. */
252
281
  deleted: number;
282
+ /**
283
+ * Every fact id this heal run left at reduced confidence (stale-inferred
284
+ * SQL pass plus model-directed downgrades, deduped) — the ids behind
285
+ * `downgraded`. Optional so existing `HealResult` literals (host mocks)
286
+ * keep compiling; `doRunHeal` always populates it today. NOT disjoint
287
+ * with `deletedIds`: a fact both downgraded and deleted in one pass
288
+ * appears in BOTH lists (union-not-sum semantics — see the
289
+ * `allDowngraded` / `allDeleted` unions in `doRunHeal`) — hosts must not
290
+ * treat the lists as disjoint.
291
+ */
292
+ downgradedIds?: string[];
293
+ /**
294
+ * Every fact id this heal run soft-deleted (orphan SQL pass plus
295
+ * model-directed deletes, deduped) — the ids behind `deleted`. Optional
296
+ * so existing `HealResult` literals (host mocks) keep compiling;
297
+ * `doRunHeal` always populates it today. NOT disjoint with
298
+ * `downgradedIds` (see above).
299
+ */
300
+ deletedIds?: string[];
253
301
  /** New facts synthesized by heal. */
254
302
  newFactsCreated: number;
255
303
  /**
@@ -437,7 +485,7 @@ interface WikiConfig {
437
485
  * System-One config surface (specs/system-one-config §1): typing mode,
438
486
  * per-site confidence floor, and low-confidence routing. Resolution chains
439
487
  * live in `utils/engineDefaults.ts` (`resolveSystemOneTyping`,
440
- * `resolveTypingMinConfidence`).
488
+ * `resolveTypingMinConfidence`, `resolveSystemOneHealScreen`, `resolveHealScreenMinConfidence`).
441
489
  */
442
490
  systemOne?: SystemOneConfig;
443
491
  /** Default node cap for traverseGraph(), unless overridden per-call. Default 20. */
@@ -960,7 +1008,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
960
1008
  * Closed for this release series, but new codes are added in minor versions:
961
1009
  * hosts must tolerate codes they do not recognize.
962
1010
  */
963
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'classification_abstained' | 'node_type_assigned' | 'context_overflow_skipped' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'ontology_backfill_held' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable' | 'node_type_dropped' | 'node_type_folded' | 'ontology_update_rejected' | 'ingest_zero_facts';
1011
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'heal_deleted' | 'heal_downgraded' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'classification_abstained' | 'node_type_assigned' | 'context_overflow_skipped' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'ontology_backfill_held' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable' | 'node_type_dropped' | 'node_type_folded' | 'ontology_update_rejected' | 'ingest_zero_facts';
964
1012
  /** The service run that emitted the diagnostic. */
965
1013
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
966
1014
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -4301,6 +4349,17 @@ declare class MaintenanceService {
4301
4349
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
4302
4350
  * for what convergence means here, and for the no-progress flags
4303
4351
  * (`searchUnavailable`, `budgetStop`) a loop must also stop on.
4352
+ *
4353
+ * Heal screen (`systemOne.healScreen: 'auto'` + `minConfidence.healScreen`):
4354
+ * a model-directed delete or downgrade whose valid `confidence` is below the
4355
+ * floor is withheld from every reader (apply, sync, removals, counts, id
4356
+ * lists); a missing or invalid confidence is applied unscreened. Each
4357
+ * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
4358
+ * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
4359
+ * mode. An `applied` receipt records that the model VERDICT was applied
4360
+ * (`downgradeByIds` runs unconditionally): a fact that was already at
4361
+ * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
4362
+ * live and the restatement is skipped as `fact_deduplicated`.
4304
4363
  */
4305
4364
  doRunHeal(entityId: string, options?: {
4306
4365
  promptOverride?: string;
@@ -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-imNjsm-X.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-BclOvn3q.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-imNjsm-X.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-BclOvn3q.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -721,6 +721,8 @@ var SEVERITY = {
721
721
  hook_failed: "warn",
722
722
  background_job_failed: "error",
723
723
  heal_skipped: "warn",
724
+ heal_deleted: "info",
725
+ heal_downgraded: "info",
724
726
  grounding_missing: "warn",
725
727
  grounding_failed: "warn",
726
728
  classification_low_confidence: "info",
@@ -774,6 +776,8 @@ var MESSAGE = {
774
776
  hook_failed: "A host hook threw or rejected.",
775
777
  background_job_failed: "A background maintenance job failed.",
776
778
  heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
779
+ heal_deleted: "Heal soft-deleted a fact (or withheld the delete below the confidence floor).",
780
+ heal_downgraded: "Heal downgraded a fact to tentative (or withheld the downgrade below the confidence floor).",
777
781
  grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
778
782
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
779
783
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
@@ -2465,10 +2469,11 @@ Keep facts concise. Do not return markdown, just raw JSON.`;
2465
2469
  var HEAL_SYSTEM_PROMPT = `You are a memory grooming agent. Your job is to review a full dump of facts and recent events to resolve contradictions, downgrade stale claims, and flag obsolete facts for deletion.
2466
2470
  Return ONLY a valid JSON object matching this schema:
2467
2471
  {
2468
- "downgraded": ["string (fact IDs)"],
2469
- "deleted": ["string (fact IDs)"],
2472
+ "downgraded": [{ "id": "string (fact ID)", "confidence": "number 0-1" }],
2473
+ "deleted": [{ "id": "string (fact ID)", "confidence": "number 0-1" }],
2470
2474
  "newFacts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
2471
2475
  }
2476
+ For downgraded and deleted entries, "confidence" is your confidence in that verdict.
2472
2477
  Do not return markdown, just raw JSON.`;
2473
2478
  var INGEST_SYSTEM_PROMPT = `You are a document ingestion agent. Your job is to extract factual knowledge from the provided document chunk.
2474
2479
  Return ONLY a valid JSON object matching this schema:
@@ -4126,6 +4131,16 @@ function resolveSystemOneEdges(config) {
4126
4131
  }
4127
4132
  return edges ?? "llm";
4128
4133
  }
4134
+ function resolveSystemOneResolve(config) {
4135
+ const resolve = config?.systemOne?.resolve;
4136
+ if (resolve !== void 0 && !isTypingMode(resolve)) {
4137
+ warnOnce(
4138
+ `[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.`
4139
+ );
4140
+ return "llm";
4141
+ }
4142
+ return resolve ?? "llm";
4143
+ }
4129
4144
  var DEFAULT_SHORTLIST_K = 10;
4130
4145
  function resolveShortlistK(config) {
4131
4146
  const k = config?.ontology?.shortlistK;
@@ -4165,6 +4180,34 @@ function resolveEdgesMinConfidence(config) {
4165
4180
  );
4166
4181
  return void 0;
4167
4182
  }
4183
+ function resolveResolveMinConfidence(config) {
4184
+ if (resolveSystemOneResolve(config) !== "auto") return void 0;
4185
+ const floor = config?.systemOne?.minConfidence?.resolve;
4186
+ if (isEdgesFloor(floor)) return floor;
4187
+ warnOnce(
4188
+ 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.`
4189
+ );
4190
+ return void 0;
4191
+ }
4192
+ function resolveSystemOneHealScreen(config) {
4193
+ const healScreen = config?.systemOne?.healScreen;
4194
+ if (healScreen !== void 0 && !isTypingMode(healScreen)) {
4195
+ warnOnce(
4196
+ `[core-llm-wiki] systemOne: \`systemOne.healScreen\` is ${formatConfigValue(healScreen)}, which is not 'auto' or 'llm'. The key is treated as unset; the default ('llm') applies.`
4197
+ );
4198
+ return "llm";
4199
+ }
4200
+ return healScreen ?? "llm";
4201
+ }
4202
+ function resolveHealScreenMinConfidence(config) {
4203
+ if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4204
+ const floor = config?.systemOne?.minConfidence?.healScreen;
4205
+ if (isEdgesFloor(floor)) return floor;
4206
+ warnOnce(
4207
+ floor === void 0 ? "[core-llm-wiki] systemOne: `systemOne.minConfidence.healScreen` is required when `systemOne.healScreen` is 'auto'. The heal screen is off for this site; heal stays ungated." : `[core-llm-wiki] systemOne: \`systemOne.minConfidence.healScreen\` is ${formatConfigValue(floor)}, which is not a finite number in [0.5, 1]. The heal screen is off for this site; heal stays ungated.`
4208
+ );
4209
+ return void 0;
4210
+ }
4168
4211
 
4169
4212
  // src/utils/embedding.ts
4170
4213
  function parseEmbedding(blob, text) {
@@ -5582,6 +5625,46 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
5582
5625
  }
5583
5626
 
5584
5627
  // src/services/librarian/ops/resolve.ts
5628
+ async function screenResolveCandidates(ambiguous, mode, floor, ask) {
5629
+ const whole = (warnReason) => warnReason ? { settled: /* @__PURE__ */ new Map(), rest: ambiguous, warnReason } : { settled: /* @__PURE__ */ new Map(), rest: ambiguous };
5630
+ if (mode !== "auto") return whole();
5631
+ if (floor === void 0) return whole("no-floor");
5632
+ if (!ask) return whole("no-classifier");
5633
+ const settled = /* @__PURE__ */ new Map();
5634
+ const rest = [];
5635
+ for (const g of ambiguous) {
5636
+ const best = g.neighbours[0];
5637
+ if (!best) {
5638
+ rest.push(g);
5639
+ continue;
5640
+ }
5641
+ const question = {
5642
+ kind: "binary",
5643
+ instructions: `Does this candidate add NO information beyond neighbour ${best.ref} (a pure duplicate: same claims, no new content)?
5644
+ Neighbour ${best.ref} title: ${best.title}
5645
+ Neighbour ${best.ref} body: ${safeSlice(best.body, 0, OPS_NEIGHBOUR_BODY_CHARS)}`
5646
+ };
5647
+ let response;
5648
+ try {
5649
+ response = await ask({
5650
+ state: classifierStateForFact({ title: g.candidate.fact.title, body: g.candidate.fact.body, tags: [] }),
5651
+ questions: { [best.ref]: question }
5652
+ });
5653
+ } catch (err) {
5654
+ if (err instanceof WikiBudgetExhausted) {
5655
+ return { settled: /* @__PURE__ */ new Map(), rest: ambiguous, budgetStop: { requiredEstimate: err.requiredEstimate } };
5656
+ }
5657
+ return whole("classifier-threw");
5658
+ }
5659
+ const checked = validateClassifierAnswer(response, best.ref, question);
5660
+ if (checked.ok && checked.answer.kind === "binary" && checked.answer.probability >= floor) {
5661
+ settled.set(g, { op: "NOOP", targetId: best.id });
5662
+ } else {
5663
+ rest.push(g);
5664
+ }
5665
+ }
5666
+ return { settled, rest };
5667
+ }
5585
5668
  function validateOp(raw, aliases) {
5586
5669
  if (!raw || typeof raw !== "object") return null;
5587
5670
  const r = raw;
@@ -5601,11 +5684,31 @@ function validateOp(raw, aliases) {
5601
5684
  }
5602
5685
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5603
5686
  async function runResolve(deps, ctx, ambiguous, budget) {
5604
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
5687
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [], classifierSettled: [] };
5605
5688
  if (ambiguous.length === 0) return out;
5606
5689
  const { entityId, trigger } = ctx;
5690
+ const mode = resolveSystemOneResolve(deps.options.config);
5691
+ const floor = resolveResolveMinConfidence(deps.options.config);
5692
+ const provider = deps.options.llmProvider;
5693
+ const ask = mode === "auto" && typeof provider.classify === "function" ? (request) => callClassify(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, request) : void 0;
5694
+ const screen = await screenResolveCandidates(ambiguous, mode, floor, ask);
5695
+ if (screen.budgetStop) return { ...out, budgetStop: screen.budgetStop };
5696
+ if (screen.warnReason === "no-classifier") {
5697
+ warnOnce(
5698
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but the provider has no classify(); ambiguous candidates fall through to the generative resolve."
5699
+ );
5700
+ } else if (screen.warnReason === "classifier-threw") {
5701
+ warnOnce(
5702
+ "[core-llm-wiki] systemOne: `systemOne.resolve` is 'auto' but classify() threw during the resolve screen; ambiguous candidates fall through to the generative resolve."
5703
+ );
5704
+ }
5705
+ for (const [g, op] of screen.settled) {
5706
+ out.ops.set(g, op);
5707
+ out.classifierSettled.push(g.candidate.index);
5708
+ }
5709
+ if (screen.rest.length === 0) return out;
5607
5710
  const outcome = await runBatched({
5608
- items: ambiguous,
5711
+ items: screen.rest,
5609
5712
  buildPrompt: (batch) => deps.promptService.buildOpsResolvePrompt(
5610
5713
  batch.map((g, i) => ({
5611
5714
  item: i,
@@ -5894,6 +5997,16 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5894
5997
  // (index into the merged extract batch)
5895
5998
  });
5896
5999
  }
6000
+ for (const itemIndex of res.classifierSettled) {
6001
+ diagnostics.push({
6002
+ entityId,
6003
+ operation: "librarian",
6004
+ trigger,
6005
+ code: "fact_deduplicated",
6006
+ detail: { itemIndex, reason: "classifier" }
6007
+ // (index into the merged extract batch)
6008
+ });
6009
+ }
5897
6010
  if (res.budgetStop) {
5898
6011
  diagnostics.discard();
5899
6012
  return { processedThrough: null, factsWritten: 0, budgetStop: res.budgetStop };
@@ -7144,12 +7257,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
7144
7257
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
7145
7258
  * for what convergence means here, and for the no-progress flags
7146
7259
  * (`searchUnavailable`, `budgetStop`) a loop must also stop on.
7260
+ *
7261
+ * Heal screen (`systemOne.healScreen: 'auto'` + `minConfidence.healScreen`):
7262
+ * a model-directed delete or downgrade whose valid `confidence` is below the
7263
+ * floor is withheld from every reader (apply, sync, removals, counts, id
7264
+ * lists); a missing or invalid confidence is applied unscreened. Each
7265
+ * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
7266
+ * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
7267
+ * mode. An `applied` receipt records that the model VERDICT was applied
7268
+ * (`downgradeByIds` runs unconditionally): a fact that was already at
7269
+ * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
7270
+ * live and the restatement is skipped as `fact_deduplicated`.
7147
7271
  */
7148
7272
  async doRunHeal(entityId, options) {
7149
7273
  const promptOverride = options?.promptOverride;
7150
7274
  const batchSize = options?.batchSize ?? HEAL_BATCH_SIZE;
7151
7275
  const trigger = options?.trigger ?? "call";
7152
7276
  const diagBase = { entityId, operation: "heal", trigger };
7277
+ const healFloor = resolveHealScreenMinConfidence(this.options.config);
7153
7278
  if (!Number.isInteger(batchSize) || batchSize < 1) {
7154
7279
  throw new Error("Invalid batchSize: must be an integer >= 1");
7155
7280
  }
@@ -7195,6 +7320,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7195
7320
  downgraded: staleDowngradedIds.length,
7196
7321
  deleted: orphanedIds.length,
7197
7322
  newFactsCreated: 0,
7323
+ downgradedIds: Array.from(new Set(staleDowngradedIds)),
7324
+ deletedIds: Array.from(new Set(orphanedIds)),
7198
7325
  skipped: [],
7199
7326
  degraded: [],
7200
7327
  remaining: counts2.eligible,
@@ -7245,10 +7372,30 @@ DROP TRIGGER IF EXISTS ${ad};`);
7245
7372
  call: (prompts) => callLlm(this.options, { operation: "heal", entityId, trigger, meter: options?.meter }, prompts),
7246
7373
  parse: (responseText, batch, prompts) => {
7247
7374
  const result = parseJsonResponse(responseText);
7375
+ const normalize = (raw) => {
7376
+ const ids = [];
7377
+ const confidence = /* @__PURE__ */ new Map();
7378
+ if (!Array.isArray(raw)) return { ids, confidence };
7379
+ for (const entry of raw) {
7380
+ const id = typeof entry === "string" ? entry : entry?.id;
7381
+ if (typeof id !== "string") continue;
7382
+ ids.push(id);
7383
+ const c = typeof entry === "object" && entry !== null ? entry.confidence : void 0;
7384
+ if (typeof c === "number" && Number.isFinite(c) && c >= 0 && c <= 1) {
7385
+ const prev = confidence.get(id);
7386
+ if (prev === void 0 || c < prev) confidence.set(id, c);
7387
+ }
7388
+ }
7389
+ return { ids, confidence };
7390
+ };
7391
+ const down = normalize(result.downgraded);
7392
+ const del = normalize(result.deleted);
7248
7393
  return {
7249
7394
  batch,
7250
- downgraded: Array.isArray(result.downgraded) ? result.downgraded : [],
7251
- deleted: Array.isArray(result.deleted) ? result.deleted : [],
7395
+ downgraded: down.ids,
7396
+ deleted: del.ids,
7397
+ downgradedConfidence: down.confidence,
7398
+ deletedConfidence: del.confidence,
7252
7399
  newFacts: Array.isArray(result.newFacts) ? result.newFacts : [],
7253
7400
  corpus: corpusByPrompt.get(prompts) ?? null
7254
7401
  };
@@ -7288,8 +7435,42 @@ DROP TRIGGER IF EXISTS ${ad};`);
7288
7435
  newFactCorpora.push(batchResult.corpus);
7289
7436
  });
7290
7437
  }
7438
+ const downgradeConfidence = /* @__PURE__ */ new Map();
7439
+ const deleteConfidence = /* @__PURE__ */ new Map();
7440
+ const mergeLowest = (into, id, c) => {
7441
+ if (c === void 0) return;
7442
+ const prev = into.get(id);
7443
+ if (prev === void 0 || c < prev) into.set(id, c);
7444
+ };
7445
+ for (const batchResult of outcome.results) {
7446
+ const mutableIds = new Set(batchResult.batch.map((f) => f.id));
7447
+ for (const id of batchResult.downgraded) if (mutableIds.has(id)) mergeLowest(downgradeConfidence, id, batchResult.downgradedConfidence.get(id));
7448
+ for (const id of batchResult.deleted) if (mutableIds.has(id)) mergeLowest(deleteConfidence, id, batchResult.deletedConfidence.get(id));
7449
+ }
7291
7450
  const safeDowngraded = Array.from(safeDowngradedSet);
7292
7451
  const safeDeleted = Array.from(safeDeletedSet);
7452
+ const withheldDowngraded = /* @__PURE__ */ new Map();
7453
+ const withheldDeleted = /* @__PURE__ */ new Map();
7454
+ let appliedDowngraded = safeDowngraded;
7455
+ let appliedDeleted = safeDeleted;
7456
+ if (healFloor !== void 0) {
7457
+ const screen = (ids, confidences, withheld) => {
7458
+ const applied = [];
7459
+ for (const id of ids) {
7460
+ const c = confidences.get(id);
7461
+ if (c !== void 0 && c < healFloor) withheld.set(id, c);
7462
+ else applied.push(id);
7463
+ }
7464
+ return applied;
7465
+ };
7466
+ appliedDowngraded = screen(safeDowngraded, downgradeConfidence, withheldDowngraded);
7467
+ appliedDeleted = screen(safeDeleted, deleteConfidence, withheldDeleted);
7468
+ if (appliedDowngraded.some((id) => !downgradeConfidence.has(id)) || appliedDeleted.some((id) => !deleteConfidence.has(id))) {
7469
+ warnOnce(
7470
+ '[core-llm-wiki] systemOne: heal returned downgraded/deleted verdicts without a valid `confidence` (out-of-range or non-numeric), so the heal screen could not gate them and they were applied. Restore the schema \u2014 or a `healSystemPrompt` override \u2014 to the `{ "id", "confidence" }` entry contract with confidences in 0-1 (see HEAL_SYSTEM_PROMPT).'
7471
+ );
7472
+ }
7473
+ }
7293
7474
  const diagBuffer = new DiagnosticBuffer();
7294
7475
  const validNewFacts = [];
7295
7476
  const validNewFactItemIndexes = [];
@@ -7306,10 +7487,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7306
7487
  }
7307
7488
  });
7308
7489
  const insertedFacts = [];
7309
- const uniqueDeletedFactIds = Array.from(new Set(safeDeleted));
7490
+ const uniqueDeletedFactIds = Array.from(new Set(appliedDeleted));
7310
7491
  await this.db.withTransactionAsync(async (tx) => {
7311
- await this.entryRepo.downgradeByIds(safeDowngraded, entityId, tx);
7312
- await this.entryRepo.softDeleteByIds(safeDeleted, entityId, tx);
7492
+ await this.entryRepo.downgradeByIds(appliedDowngraded, entityId, tx);
7493
+ await this.entryRepo.softDeleteByIds(appliedDeleted, entityId, tx);
7313
7494
  const healFactsForDedupe = await this.entryRepo.findInferredTitlesByEntityId(entityId, tx);
7314
7495
  for (const [k, fact] of validNewFacts.entries()) {
7315
7496
  const newTokens = titleTokens(fact.title);
@@ -7373,11 +7554,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
7373
7554
  for (const { item, reason } of outcome.skipped) {
7374
7555
  diagBuffer.push({ ...diagBase, code: "heal_skipped", detail: { factId: item.id, reason } });
7375
7556
  }
7557
+ const pushReceipts = (code, applied, confidences, withheld) => {
7558
+ for (const factId of applied) {
7559
+ if (healFloor !== void 0 && !confidences.has(factId)) {
7560
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied_unscreened" } });
7561
+ } else {
7562
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied" } });
7563
+ }
7564
+ }
7565
+ for (const [factId, confidence] of withheld) {
7566
+ diagBuffer.push({
7567
+ ...diagBase,
7568
+ code,
7569
+ detail: { factId, reason: "below_floor", ...confidence !== void 0 ? { confidence } : {} }
7570
+ });
7571
+ }
7572
+ };
7573
+ pushReceipts("heal_downgraded", appliedDowngraded, downgradeConfidence, withheldDowngraded);
7574
+ pushReceipts("heal_deleted", appliedDeleted, deleteConfidence, withheldDeleted);
7376
7575
  diagBuffer.flush(this.options);
7377
7576
  const healSyncIds = Array.from(/* @__PURE__ */ new Set([
7378
7577
  ...orphanedIds,
7379
7578
  ...staleDowngradedIds,
7380
- ...safeDowngraded,
7579
+ ...appliedDowngraded,
7381
7580
  ...uniqueDeletedFactIds,
7382
7581
  ...insertedFacts.map((f) => f.id)
7383
7582
  ]));
@@ -7396,13 +7595,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
7396
7595
  }
7397
7596
  let scanned = outcome.skipped.length;
7398
7597
  for (const batchResult of outcome.results) scanned += batchResult.batch.length;
7399
- const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...safeDowngraded]);
7598
+ const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...appliedDowngraded]);
7400
7599
  const allDeleted = /* @__PURE__ */ new Set([...orphanedIds, ...uniqueDeletedFactIds]);
7401
7600
  const counts = await this.entryRepo.countHealCandidatesByEntityId(entityId, recheckCutoff);
7402
7601
  return {
7403
7602
  scanned,
7404
7603
  downgraded: allDowngraded.size,
7405
7604
  deleted: allDeleted.size,
7605
+ downgradedIds: Array.from(allDowngraded),
7606
+ deletedIds: Array.from(allDeleted),
7406
7607
  newFactsCreated: insertedFacts.length,
7407
7608
  skipped: outcome.skipped.map(({ item, reason }) => ({ id: item.id, reason })),
7408
7609
  degraded: healedDegraded,