@equationalapplications/core-llm-wiki 9.13.0 → 9.14.1

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,14 +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; the resolution step adds `resolve` and the
9
- * `'resolve'` member. Later PRs add more threshold sites
10
- * (`'healScreen'`) — each as one new line in
11
- * `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
12
12
  * that boundary belongs here.
13
13
  */
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
+ /** 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';
16
16
  interface SystemOneConfig {
17
17
  /**
18
18
  * Typing mode for ontology backfill. `'auto'` uses
@@ -46,6 +46,20 @@ interface SystemOneConfig {
46
46
  * configuration that can silently discard a candidate fact.
47
47
  */
48
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';
49
63
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
50
64
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
51
65
  /**
@@ -265,6 +279,25 @@ interface HealResult {
265
279
  downgraded: number;
266
280
  /** Facts soft-deleted — the orphan-marking SQL pass plus model-directed deletes, deduped. */
267
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[];
268
301
  /** New facts synthesized by heal. */
269
302
  newFactsCreated: number;
270
303
  /**
@@ -452,7 +485,7 @@ interface WikiConfig {
452
485
  * System-One config surface (specs/system-one-config §1): typing mode,
453
486
  * per-site confidence floor, and low-confidence routing. Resolution chains
454
487
  * live in `utils/engineDefaults.ts` (`resolveSystemOneTyping`,
455
- * `resolveTypingMinConfidence`).
488
+ * `resolveTypingMinConfidence`, `resolveSystemOneHealScreen`, `resolveHealScreenMinConfidence`).
456
489
  */
457
490
  systemOne?: SystemOneConfig;
458
491
  /** Default node cap for traverseGraph(), unless overridden per-call. Default 20. */
@@ -975,7 +1008,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
975
1008
  * Closed for this release series, but new codes are added in minor versions:
976
1009
  * hosts must tolerate codes they do not recognize.
977
1010
  */
978
- 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';
979
1012
  /** The service run that emitted the diagnostic. */
980
1013
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
981
1014
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -4316,6 +4349,17 @@ declare class MaintenanceService {
4316
4349
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
4317
4350
  * for what convergence means here, and for the no-progress flags
4318
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`.
4319
4363
  */
4320
4364
  doRunHeal(entityId: string, options?: {
4321
4365
  promptOverride?: string;
@@ -5,14 +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; the resolution step adds `resolve` and the
9
- * `'resolve'` member. Later PRs add more threshold sites
10
- * (`'healScreen'`) — each as one new line in
11
- * `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
12
12
  * that boundary belongs here.
13
13
  */
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
+ /** 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';
16
16
  interface SystemOneConfig {
17
17
  /**
18
18
  * Typing mode for ontology backfill. `'auto'` uses
@@ -46,6 +46,20 @@ interface SystemOneConfig {
46
46
  * configuration that can silently discard a candidate fact.
47
47
  */
48
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';
49
63
  /** Per-site minimum confidence. Only the classifier path reads a floor. */
50
64
  minConfidence?: Partial<Record<SystemOneThresholdSite, number>>;
51
65
  /**
@@ -265,6 +279,25 @@ interface HealResult {
265
279
  downgraded: number;
266
280
  /** Facts soft-deleted — the orphan-marking SQL pass plus model-directed deletes, deduped. */
267
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[];
268
301
  /** New facts synthesized by heal. */
269
302
  newFactsCreated: number;
270
303
  /**
@@ -452,7 +485,7 @@ interface WikiConfig {
452
485
  * System-One config surface (specs/system-one-config §1): typing mode,
453
486
  * per-site confidence floor, and low-confidence routing. Resolution chains
454
487
  * live in `utils/engineDefaults.ts` (`resolveSystemOneTyping`,
455
- * `resolveTypingMinConfidence`).
488
+ * `resolveTypingMinConfidence`, `resolveSystemOneHealScreen`, `resolveHealScreenMinConfidence`).
456
489
  */
457
490
  systemOne?: SystemOneConfig;
458
491
  /** Default node cap for traverseGraph(), unless overridden per-call. Default 20. */
@@ -975,7 +1008,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
975
1008
  * Closed for this release series, but new codes are added in minor versions:
976
1009
  * hosts must tolerate codes they do not recognize.
977
1010
  */
978
- 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';
979
1012
  /** The service run that emitted the diagnostic. */
980
1013
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
981
1014
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -4316,6 +4349,17 @@ declare class MaintenanceService {
4316
4349
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
4317
4350
  * for what convergence means here, and for the no-progress flags
4318
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`.
4319
4363
  */
4320
4364
  doRunHeal(entityId: string, options?: {
4321
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-DkKZcrhE.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-DkKZcrhE.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:
@@ -4184,6 +4189,25 @@ function resolveResolveMinConfidence(config) {
4184
4189
  );
4185
4190
  return void 0;
4186
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
+ }
4187
4211
 
4188
4212
  // src/utils/embedding.ts
4189
4213
  function parseEmbedding(blob, text) {
@@ -4422,6 +4446,8 @@ var CONTEXT_OVERFLOW_PATTERNS = [
4422
4446
  // classify as input overflow (it would split the batch and stamp a cooldown).
4423
4447
  /(input|prompt).{0,40}exceed(s|ed)? .{0,30}(context|maximum)/i,
4424
4448
  /context limit/i,
4449
+ // llama.rn (RNLlamaJSI.cpp): prompt >= n_ctx with ctx_shift off
4450
+ /\bcontext is full\b/i,
4425
4451
  /too long for (the )?requested model/i,
4426
4452
  // vLLM dual-match wording (errata E2 ruling): the regex ENFORCES the dual-match —
4427
4453
  // "max_tokens ... too large" PLUS a context clause; a bare message is NOT overflow
@@ -7233,6 +7259,17 @@ DROP TRIGGER IF EXISTS ${ad};`);
7233
7259
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
7234
7260
  * for what convergence means here, and for the no-progress flags
7235
7261
  * (`searchUnavailable`, `budgetStop`) a loop must also stop on.
7262
+ *
7263
+ * Heal screen (`systemOne.healScreen: 'auto'` + `minConfidence.healScreen`):
7264
+ * a model-directed delete or downgrade whose valid `confidence` is below the
7265
+ * floor is withheld from every reader (apply, sync, removals, counts, id
7266
+ * lists); a missing or invalid confidence is applied unscreened. Each
7267
+ * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
7268
+ * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
7269
+ * mode. An `applied` receipt records that the model VERDICT was applied
7270
+ * (`downgradeByIds` runs unconditionally): a fact that was already at
7271
+ * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
7272
+ * live and the restatement is skipped as `fact_deduplicated`.
7236
7273
  */
7237
7274
  async doRunHeal(entityId, options) {
7238
7275
  const promptOverride = options?.promptOverride;
@@ -7246,6 +7283,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
7246
7283
  if (!Number.isInteger(bodyTruncationChars) || bodyTruncationChars < 1) {
7247
7284
  throw new Error("Invalid bodyTruncationChars: must be an integer >= 1");
7248
7285
  }
7286
+ const healFloor = resolveHealScreenMinConfidence(this.options.config);
7249
7287
  const now = Date.now();
7250
7288
  const recheckCutoff = now - HEAL_RECHECK_MS;
7251
7289
  const orphanAfterDays = this.options.config?.orphanAfterDays !== void 0 ? this.options.config?.orphanAfterDays : 30;
@@ -7284,6 +7322,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
7284
7322
  downgraded: staleDowngradedIds.length,
7285
7323
  deleted: orphanedIds.length,
7286
7324
  newFactsCreated: 0,
7325
+ downgradedIds: Array.from(new Set(staleDowngradedIds)),
7326
+ deletedIds: Array.from(new Set(orphanedIds)),
7287
7327
  skipped: [],
7288
7328
  degraded: [],
7289
7329
  remaining: counts2.eligible,
@@ -7334,10 +7374,30 @@ DROP TRIGGER IF EXISTS ${ad};`);
7334
7374
  call: (prompts) => callLlm(this.options, { operation: "heal", entityId, trigger, meter: options?.meter }, prompts),
7335
7375
  parse: (responseText, batch, prompts) => {
7336
7376
  const result = parseJsonResponse(responseText);
7377
+ const normalize = (raw) => {
7378
+ const ids = [];
7379
+ const confidence = /* @__PURE__ */ new Map();
7380
+ if (!Array.isArray(raw)) return { ids, confidence };
7381
+ for (const entry of raw) {
7382
+ const id = typeof entry === "string" ? entry : entry?.id;
7383
+ if (typeof id !== "string") continue;
7384
+ ids.push(id);
7385
+ const c = typeof entry === "object" && entry !== null ? entry.confidence : void 0;
7386
+ if (typeof c === "number" && Number.isFinite(c) && c >= 0 && c <= 1) {
7387
+ const prev = confidence.get(id);
7388
+ if (prev === void 0 || c < prev) confidence.set(id, c);
7389
+ }
7390
+ }
7391
+ return { ids, confidence };
7392
+ };
7393
+ const down = normalize(result.downgraded);
7394
+ const del = normalize(result.deleted);
7337
7395
  return {
7338
7396
  batch,
7339
- downgraded: Array.isArray(result.downgraded) ? result.downgraded : [],
7340
- deleted: Array.isArray(result.deleted) ? result.deleted : [],
7397
+ downgraded: down.ids,
7398
+ deleted: del.ids,
7399
+ downgradedConfidence: down.confidence,
7400
+ deletedConfidence: del.confidence,
7341
7401
  newFacts: Array.isArray(result.newFacts) ? result.newFacts : [],
7342
7402
  corpus: corpusByPrompt.get(prompts) ?? null
7343
7403
  };
@@ -7377,8 +7437,42 @@ DROP TRIGGER IF EXISTS ${ad};`);
7377
7437
  newFactCorpora.push(batchResult.corpus);
7378
7438
  });
7379
7439
  }
7440
+ const downgradeConfidence = /* @__PURE__ */ new Map();
7441
+ const deleteConfidence = /* @__PURE__ */ new Map();
7442
+ const mergeLowest = (into, id, c) => {
7443
+ if (c === void 0) return;
7444
+ const prev = into.get(id);
7445
+ if (prev === void 0 || c < prev) into.set(id, c);
7446
+ };
7447
+ for (const batchResult of outcome.results) {
7448
+ const mutableIds = new Set(batchResult.batch.map((f) => f.id));
7449
+ for (const id of batchResult.downgraded) if (mutableIds.has(id)) mergeLowest(downgradeConfidence, id, batchResult.downgradedConfidence.get(id));
7450
+ for (const id of batchResult.deleted) if (mutableIds.has(id)) mergeLowest(deleteConfidence, id, batchResult.deletedConfidence.get(id));
7451
+ }
7380
7452
  const safeDowngraded = Array.from(safeDowngradedSet);
7381
7453
  const safeDeleted = Array.from(safeDeletedSet);
7454
+ const withheldDowngraded = /* @__PURE__ */ new Map();
7455
+ const withheldDeleted = /* @__PURE__ */ new Map();
7456
+ let appliedDowngraded = safeDowngraded;
7457
+ let appliedDeleted = safeDeleted;
7458
+ if (healFloor !== void 0) {
7459
+ const screen = (ids, confidences, withheld) => {
7460
+ const applied = [];
7461
+ for (const id of ids) {
7462
+ const c = confidences.get(id);
7463
+ if (c !== void 0 && c < healFloor) withheld.set(id, c);
7464
+ else applied.push(id);
7465
+ }
7466
+ return applied;
7467
+ };
7468
+ appliedDowngraded = screen(safeDowngraded, downgradeConfidence, withheldDowngraded);
7469
+ appliedDeleted = screen(safeDeleted, deleteConfidence, withheldDeleted);
7470
+ if (appliedDowngraded.some((id) => !downgradeConfidence.has(id)) || appliedDeleted.some((id) => !deleteConfidence.has(id))) {
7471
+ warnOnce(
7472
+ '[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).'
7473
+ );
7474
+ }
7475
+ }
7382
7476
  const diagBuffer = new DiagnosticBuffer();
7383
7477
  const validNewFacts = [];
7384
7478
  const validNewFactItemIndexes = [];
@@ -7395,10 +7489,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
7395
7489
  }
7396
7490
  });
7397
7491
  const insertedFacts = [];
7398
- const uniqueDeletedFactIds = Array.from(new Set(safeDeleted));
7492
+ const uniqueDeletedFactIds = Array.from(new Set(appliedDeleted));
7399
7493
  await this.db.withTransactionAsync(async (tx) => {
7400
- await this.entryRepo.downgradeByIds(safeDowngraded, entityId, tx);
7401
- await this.entryRepo.softDeleteByIds(safeDeleted, entityId, tx);
7494
+ await this.entryRepo.downgradeByIds(appliedDowngraded, entityId, tx);
7495
+ await this.entryRepo.softDeleteByIds(appliedDeleted, entityId, tx);
7402
7496
  const healFactsForDedupe = await this.entryRepo.findInferredTitlesByEntityId(entityId, tx);
7403
7497
  for (const [k, fact] of validNewFacts.entries()) {
7404
7498
  const newTokens = titleTokens(fact.title);
@@ -7462,11 +7556,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
7462
7556
  for (const { item, reason } of outcome.skipped) {
7463
7557
  diagBuffer.push({ ...diagBase, code: "heal_skipped", detail: { factId: item.id, reason } });
7464
7558
  }
7559
+ const pushReceipts = (code, applied, confidences, withheld) => {
7560
+ for (const factId of applied) {
7561
+ if (healFloor !== void 0 && !confidences.has(factId)) {
7562
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied_unscreened" } });
7563
+ } else {
7564
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied" } });
7565
+ }
7566
+ }
7567
+ for (const [factId, confidence] of withheld) {
7568
+ diagBuffer.push({
7569
+ ...diagBase,
7570
+ code,
7571
+ detail: { factId, reason: "below_floor", confidence }
7572
+ });
7573
+ }
7574
+ };
7575
+ pushReceipts("heal_downgraded", appliedDowngraded, downgradeConfidence, withheldDowngraded);
7576
+ pushReceipts("heal_deleted", appliedDeleted, deleteConfidence, withheldDeleted);
7465
7577
  diagBuffer.flush(this.options);
7466
7578
  const healSyncIds = Array.from(/* @__PURE__ */ new Set([
7467
7579
  ...orphanedIds,
7468
7580
  ...staleDowngradedIds,
7469
- ...safeDowngraded,
7581
+ ...appliedDowngraded,
7470
7582
  ...uniqueDeletedFactIds,
7471
7583
  ...insertedFacts.map((f) => f.id)
7472
7584
  ]));
@@ -7485,13 +7597,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
7485
7597
  }
7486
7598
  let scanned = outcome.skipped.length;
7487
7599
  for (const batchResult of outcome.results) scanned += batchResult.batch.length;
7488
- const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...safeDowngraded]);
7600
+ const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...appliedDowngraded]);
7489
7601
  const allDeleted = /* @__PURE__ */ new Set([...orphanedIds, ...uniqueDeletedFactIds]);
7490
7602
  const counts = await this.entryRepo.countHealCandidatesByEntityId(entityId, recheckCutoff);
7491
7603
  return {
7492
7604
  scanned,
7493
7605
  downgraded: allDowngraded.size,
7494
7606
  deleted: allDeleted.size,
7607
+ downgradedIds: Array.from(allDowngraded),
7608
+ deletedIds: Array.from(allDeleted),
7495
7609
  newFactsCreated: insertedFacts.length,
7496
7610
  skipped: outcome.skipped.map(({ item, reason }) => ({ id: item.id, reason })),
7497
7611
  degraded: healedDegraded,