@equationalapplications/core-llm-wiki 9.13.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.
@@ -2271,10 +2271,11 @@ Keep facts concise. Do not return markdown, just raw JSON.`;
2271
2271
  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.
2272
2272
  Return ONLY a valid JSON object matching this schema:
2273
2273
  {
2274
- "downgraded": ["string (fact IDs)"],
2275
- "deleted": ["string (fact IDs)"],
2274
+ "downgraded": [{ "id": "string (fact ID)", "confidence": "number 0-1" }],
2275
+ "deleted": [{ "id": "string (fact ID)", "confidence": "number 0-1" }],
2276
2276
  "newFacts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
2277
2277
  }
2278
+ For downgraded and deleted entries, "confidence" is your confidence in that verdict.
2278
2279
  Do not return markdown, just raw JSON.`;
2279
2280
  var INGEST_SYSTEM_PROMPT = `You are a document ingestion agent. Your job is to extract factual knowledge from the provided document chunk.
2280
2281
  Return ONLY a valid JSON object matching this schema:
@@ -2829,6 +2830,8 @@ var SEVERITY = {
2829
2830
  hook_failed: "warn",
2830
2831
  background_job_failed: "error",
2831
2832
  heal_skipped: "warn",
2833
+ heal_deleted: "info",
2834
+ heal_downgraded: "info",
2832
2835
  grounding_missing: "warn",
2833
2836
  grounding_failed: "warn",
2834
2837
  classification_low_confidence: "info",
@@ -2882,6 +2885,8 @@ var MESSAGE = {
2882
2885
  hook_failed: "A host hook threw or rejected.",
2883
2886
  background_job_failed: "A background maintenance job failed.",
2884
2887
  heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
2888
+ heal_deleted: "Heal soft-deleted a fact (or withheld the delete below the confidence floor).",
2889
+ heal_downgraded: "Heal downgraded a fact to tentative (or withheld the downgrade below the confidence floor).",
2885
2890
  grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
2886
2891
  grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
2887
2892
  classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
@@ -4032,6 +4037,25 @@ function resolveResolveMinConfidence(config) {
4032
4037
  );
4033
4038
  return void 0;
4034
4039
  }
4040
+ function resolveSystemOneHealScreen(config) {
4041
+ const healScreen = config?.systemOne?.healScreen;
4042
+ if (healScreen !== void 0 && !isTypingMode(healScreen)) {
4043
+ warnOnce(
4044
+ `[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.`
4045
+ );
4046
+ return "llm";
4047
+ }
4048
+ return healScreen ?? "llm";
4049
+ }
4050
+ function resolveHealScreenMinConfidence(config) {
4051
+ if (resolveSystemOneHealScreen(config) !== "auto") return void 0;
4052
+ const floor = config?.systemOne?.minConfidence?.healScreen;
4053
+ if (isEdgesFloor(floor)) return floor;
4054
+ warnOnce(
4055
+ 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.`
4056
+ );
4057
+ return void 0;
4058
+ }
4035
4059
 
4036
4060
  // src/utils/classifier.ts
4037
4061
  var isUnit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
@@ -8333,12 +8357,24 @@ DROP TRIGGER IF EXISTS ${ad};`);
8333
8357
  * `result.remaining > 0` for convergence — see {@link HealResult.remaining}
8334
8358
  * for what convergence means here, and for the no-progress flags
8335
8359
  * (`searchUnavailable`, `budgetStop`) a loop must also stop on.
8360
+ *
8361
+ * Heal screen (`systemOne.healScreen: 'auto'` + `minConfidence.healScreen`):
8362
+ * a model-directed delete or downgrade whose valid `confidence` is below the
8363
+ * floor is withheld from every reader (apply, sync, removals, counts, id
8364
+ * lists); a missing or invalid confidence is applied unscreened. Each
8365
+ * model-directed move emits a `heal_deleted` / `heal_downgraded` receipt
8366
+ * after commit (`applied`, `applied_unscreened`, or `below_floor`), in every
8367
+ * mode. An `applied` receipt records that the model VERDICT was applied
8368
+ * (`downgradeByIds` runs unconditionally): a fact that was already at
8369
+ * reduced confidence still gets an `applied` receipt. A withheld delete paired with a restating `newFact` leaves the fact
8370
+ * live and the restatement is skipped as `fact_deduplicated`.
8336
8371
  */
8337
8372
  async doRunHeal(entityId, options) {
8338
8373
  const promptOverride = options?.promptOverride;
8339
8374
  const batchSize = options?.batchSize ?? HEAL_BATCH_SIZE;
8340
8375
  const trigger = options?.trigger ?? "call";
8341
8376
  const diagBase = { entityId, operation: "heal", trigger };
8377
+ const healFloor = resolveHealScreenMinConfidence(this.options.config);
8342
8378
  if (!Number.isInteger(batchSize) || batchSize < 1) {
8343
8379
  throw new Error("Invalid batchSize: must be an integer >= 1");
8344
8380
  }
@@ -8384,6 +8420,8 @@ DROP TRIGGER IF EXISTS ${ad};`);
8384
8420
  downgraded: staleDowngradedIds.length,
8385
8421
  deleted: orphanedIds.length,
8386
8422
  newFactsCreated: 0,
8423
+ downgradedIds: Array.from(new Set(staleDowngradedIds)),
8424
+ deletedIds: Array.from(new Set(orphanedIds)),
8387
8425
  skipped: [],
8388
8426
  degraded: [],
8389
8427
  remaining: counts2.eligible,
@@ -8434,10 +8472,30 @@ DROP TRIGGER IF EXISTS ${ad};`);
8434
8472
  call: (prompts) => callLlm(this.options, { operation: "heal", entityId, trigger, meter: options?.meter }, prompts),
8435
8473
  parse: (responseText, batch, prompts) => {
8436
8474
  const result = parseJsonResponse(responseText);
8475
+ const normalize = (raw) => {
8476
+ const ids = [];
8477
+ const confidence = /* @__PURE__ */ new Map();
8478
+ if (!Array.isArray(raw)) return { ids, confidence };
8479
+ for (const entry of raw) {
8480
+ const id = typeof entry === "string" ? entry : entry?.id;
8481
+ if (typeof id !== "string") continue;
8482
+ ids.push(id);
8483
+ const c = typeof entry === "object" && entry !== null ? entry.confidence : void 0;
8484
+ if (typeof c === "number" && Number.isFinite(c) && c >= 0 && c <= 1) {
8485
+ const prev = confidence.get(id);
8486
+ if (prev === void 0 || c < prev) confidence.set(id, c);
8487
+ }
8488
+ }
8489
+ return { ids, confidence };
8490
+ };
8491
+ const down = normalize(result.downgraded);
8492
+ const del = normalize(result.deleted);
8437
8493
  return {
8438
8494
  batch,
8439
- downgraded: Array.isArray(result.downgraded) ? result.downgraded : [],
8440
- deleted: Array.isArray(result.deleted) ? result.deleted : [],
8495
+ downgraded: down.ids,
8496
+ deleted: del.ids,
8497
+ downgradedConfidence: down.confidence,
8498
+ deletedConfidence: del.confidence,
8441
8499
  newFacts: Array.isArray(result.newFacts) ? result.newFacts : [],
8442
8500
  corpus: corpusByPrompt.get(prompts) ?? null
8443
8501
  };
@@ -8477,8 +8535,42 @@ DROP TRIGGER IF EXISTS ${ad};`);
8477
8535
  newFactCorpora.push(batchResult.corpus);
8478
8536
  });
8479
8537
  }
8538
+ const downgradeConfidence = /* @__PURE__ */ new Map();
8539
+ const deleteConfidence = /* @__PURE__ */ new Map();
8540
+ const mergeLowest = (into, id, c) => {
8541
+ if (c === void 0) return;
8542
+ const prev = into.get(id);
8543
+ if (prev === void 0 || c < prev) into.set(id, c);
8544
+ };
8545
+ for (const batchResult of outcome.results) {
8546
+ const mutableIds = new Set(batchResult.batch.map((f) => f.id));
8547
+ for (const id of batchResult.downgraded) if (mutableIds.has(id)) mergeLowest(downgradeConfidence, id, batchResult.downgradedConfidence.get(id));
8548
+ for (const id of batchResult.deleted) if (mutableIds.has(id)) mergeLowest(deleteConfidence, id, batchResult.deletedConfidence.get(id));
8549
+ }
8480
8550
  const safeDowngraded = Array.from(safeDowngradedSet);
8481
8551
  const safeDeleted = Array.from(safeDeletedSet);
8552
+ const withheldDowngraded = /* @__PURE__ */ new Map();
8553
+ const withheldDeleted = /* @__PURE__ */ new Map();
8554
+ let appliedDowngraded = safeDowngraded;
8555
+ let appliedDeleted = safeDeleted;
8556
+ if (healFloor !== void 0) {
8557
+ const screen = (ids, confidences, withheld) => {
8558
+ const applied = [];
8559
+ for (const id of ids) {
8560
+ const c = confidences.get(id);
8561
+ if (c !== void 0 && c < healFloor) withheld.set(id, c);
8562
+ else applied.push(id);
8563
+ }
8564
+ return applied;
8565
+ };
8566
+ appliedDowngraded = screen(safeDowngraded, downgradeConfidence, withheldDowngraded);
8567
+ appliedDeleted = screen(safeDeleted, deleteConfidence, withheldDeleted);
8568
+ if (appliedDowngraded.some((id) => !downgradeConfidence.has(id)) || appliedDeleted.some((id) => !deleteConfidence.has(id))) {
8569
+ warnOnce(
8570
+ '[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).'
8571
+ );
8572
+ }
8573
+ }
8482
8574
  const diagBuffer = new DiagnosticBuffer();
8483
8575
  const validNewFacts = [];
8484
8576
  const validNewFactItemIndexes = [];
@@ -8495,10 +8587,10 @@ DROP TRIGGER IF EXISTS ${ad};`);
8495
8587
  }
8496
8588
  });
8497
8589
  const insertedFacts = [];
8498
- const uniqueDeletedFactIds = Array.from(new Set(safeDeleted));
8590
+ const uniqueDeletedFactIds = Array.from(new Set(appliedDeleted));
8499
8591
  await this.db.withTransactionAsync(async (tx) => {
8500
- await this.entryRepo.downgradeByIds(safeDowngraded, entityId, tx);
8501
- await this.entryRepo.softDeleteByIds(safeDeleted, entityId, tx);
8592
+ await this.entryRepo.downgradeByIds(appliedDowngraded, entityId, tx);
8593
+ await this.entryRepo.softDeleteByIds(appliedDeleted, entityId, tx);
8502
8594
  const healFactsForDedupe = await this.entryRepo.findInferredTitlesByEntityId(entityId, tx);
8503
8595
  for (const [k, fact] of validNewFacts.entries()) {
8504
8596
  const newTokens = titleTokens(fact.title);
@@ -8562,11 +8654,29 @@ DROP TRIGGER IF EXISTS ${ad};`);
8562
8654
  for (const { item, reason } of outcome.skipped) {
8563
8655
  diagBuffer.push({ ...diagBase, code: "heal_skipped", detail: { factId: item.id, reason } });
8564
8656
  }
8657
+ const pushReceipts = (code, applied, confidences, withheld) => {
8658
+ for (const factId of applied) {
8659
+ if (healFloor !== void 0 && !confidences.has(factId)) {
8660
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied_unscreened" } });
8661
+ } else {
8662
+ diagBuffer.push({ ...diagBase, code, detail: { factId, reason: "applied" } });
8663
+ }
8664
+ }
8665
+ for (const [factId, confidence] of withheld) {
8666
+ diagBuffer.push({
8667
+ ...diagBase,
8668
+ code,
8669
+ detail: { factId, reason: "below_floor", ...confidence !== void 0 ? { confidence } : {} }
8670
+ });
8671
+ }
8672
+ };
8673
+ pushReceipts("heal_downgraded", appliedDowngraded, downgradeConfidence, withheldDowngraded);
8674
+ pushReceipts("heal_deleted", appliedDeleted, deleteConfidence, withheldDeleted);
8565
8675
  diagBuffer.flush(this.options);
8566
8676
  const healSyncIds = Array.from(/* @__PURE__ */ new Set([
8567
8677
  ...orphanedIds,
8568
8678
  ...staleDowngradedIds,
8569
- ...safeDowngraded,
8679
+ ...appliedDowngraded,
8570
8680
  ...uniqueDeletedFactIds,
8571
8681
  ...insertedFacts.map((f) => f.id)
8572
8682
  ]));
@@ -8585,13 +8695,15 @@ DROP TRIGGER IF EXISTS ${ad};`);
8585
8695
  }
8586
8696
  let scanned = outcome.skipped.length;
8587
8697
  for (const batchResult of outcome.results) scanned += batchResult.batch.length;
8588
- const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...safeDowngraded]);
8698
+ const allDowngraded = /* @__PURE__ */ new Set([...staleDowngradedIds, ...appliedDowngraded]);
8589
8699
  const allDeleted = /* @__PURE__ */ new Set([...orphanedIds, ...uniqueDeletedFactIds]);
8590
8700
  const counts = await this.entryRepo.countHealCandidatesByEntityId(entityId, recheckCutoff);
8591
8701
  return {
8592
8702
  scanned,
8593
8703
  downgraded: allDowngraded.size,
8594
8704
  deleted: allDeleted.size,
8705
+ downgradedIds: Array.from(allDowngraded),
8706
+ deletedIds: Array.from(allDeleted),
8595
8707
  newFactsCreated: insertedFacts.length,
8596
8708
  skipped: outcome.skipped.map(({ item, reason }) => ({ id: item.id, reason })),
8597
8709
  degraded: healedDegraded,
@@ -11878,6 +11990,6 @@ var WriteService = class {
11878
11990
  }
11879
11991
  };
11880
11992
 
11881
- export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneResolve, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11882
- //# sourceMappingURL=chunk-4TG7RQF6.mjs.map
11883
- //# sourceMappingURL=chunk-4TG7RQF6.mjs.map
11993
+ export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
11994
+ //# sourceMappingURL=chunk-2FCE7ZAC.mjs.map
11995
+ //# sourceMappingURL=chunk-2FCE7ZAC.mjs.map